Skip to content

Commit

Permalink
neaten up code generation a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Mar 14, 2022
1 parent cf27caf commit 2d367e7
Showing 1 changed file with 34 additions and 23 deletions.
57 changes: 34 additions & 23 deletions packages/kit/src/core/sync/write_types.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { write_if_changed } from './utils.js';

/** @param {string} imports */
const header = (imports) => `
// this file is auto-generated
import type { ${imports} } from '@sveltejs/kit';`;

/** @param {string} arg */
const endpoint = (arg) => `
export type RequestHandler<Output extends ResponseBody = ResponseBody> = GenericRequestHandler<${arg}, Output>;`;

/** @param {string} arg */
const page = (arg) => `
export type Load<
InputProps extends Record<string, any> = Record<string, any>,
OutputProps extends Record<string, any> = InputProps
> = GenericLoad<${arg}, InputProps, OutputProps>;`;

/**
* @param {import('types').ValidatedConfig} config
* @param {import('types').ManifestData} manifest_data
Expand Down Expand Up @@ -53,29 +69,24 @@ export function write_types(config, manifest_data) {
const arg =
params.length > 0 ? `{ ${params.map((param) => `${param}: string`).join('; ')} }` : '{}';

const imports = [
type !== 'page' && 'RequestHandler as GenericRequestHandler',
type !== 'endpoint' && 'Load as GenericLoad'
]
.filter(Boolean)
.join(', ');

const file = `${config.kit.outDir}/types/${key || 'index'}.d.ts`;
const content = [
'// this file is auto-generated',
`import type { ${imports} } from '@sveltejs/kit';`,
type !== 'endpoint' && "import type { ResponseBody } from '@sveltejs/kit';",
type !== 'page' &&
`export type RequestHandler<Output extends ResponseBody = ResponseBody> = GenericRequestHandler<${arg}, Output>;`,
type !== 'endpoint' &&
`export type Load<
InputProps extends Record<string, any> = Record<string, any>,
OutputProps extends Record<string, any> = InputProps
> = GenericLoad<${arg}, InputProps, OutputProps>;`
]
.filter(Boolean)
.join('\n');
const imports = [];
const content = [];

if (type !== 'page') {
imports.push('RequestHandler as GenericRequestHandler, ResponseBody');
content.push(endpoint(arg));
}

if (type !== 'endpoint') {
imports.push('Load as GenericLoad');
content.push(page(arg));
}

content.unshift(header(imports.join(', ')));

write_if_changed(file, content);
write_if_changed(
`${config.kit.outDir}/types/${key || 'index'}.d.ts`,
content.join('\n').trim()
);
});
}

0 comments on commit 2d367e7

Please sign in to comment.