@sveltejs/kit 1.0.0-next.52 → 1.0.0-next.520

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/README.md +6 -3
  2. package/package.json +93 -67
  3. package/postinstall.js +47 -0
  4. package/scripts/special-types/$env+dynamic+private.md +10 -0
  5. package/scripts/special-types/$env+dynamic+public.md +8 -0
  6. package/scripts/special-types/$env+static+private.md +19 -0
  7. package/scripts/special-types/$env+static+public.md +7 -0
  8. package/scripts/special-types/$lib.md +5 -0
  9. package/src/cli.js +108 -0
  10. package/src/constants.js +7 -0
  11. package/src/core/adapt/builder.js +215 -0
  12. package/src/core/adapt/index.js +31 -0
  13. package/src/core/config/default-error.html +56 -0
  14. package/src/core/config/index.js +110 -0
  15. package/src/core/config/options.js +504 -0
  16. package/src/core/config/types.d.ts +1 -0
  17. package/src/core/env.js +121 -0
  18. package/src/core/generate_manifest/index.js +94 -0
  19. package/src/core/prerender/crawl.js +198 -0
  20. package/src/core/prerender/entities.js +2252 -0
  21. package/src/core/prerender/prerender.js +458 -0
  22. package/src/core/prerender/queue.js +80 -0
  23. package/src/core/sync/create_manifest_data/conflict.js +0 -0
  24. package/src/core/sync/create_manifest_data/index.js +470 -0
  25. package/src/core/sync/create_manifest_data/sort.js +163 -0
  26. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  27. package/src/core/sync/sync.js +78 -0
  28. package/src/core/sync/utils.js +33 -0
  29. package/src/core/sync/write_ambient.js +53 -0
  30. package/src/core/sync/write_client_manifest.js +106 -0
  31. package/src/core/sync/write_matchers.js +25 -0
  32. package/src/core/sync/write_root.js +91 -0
  33. package/src/core/sync/write_tsconfig.js +195 -0
  34. package/src/core/sync/write_types/index.js +783 -0
  35. package/src/core/utils.js +70 -0
  36. package/src/exports/hooks/index.js +1 -0
  37. package/src/exports/hooks/sequence.js +44 -0
  38. package/src/exports/index.js +45 -0
  39. package/src/exports/node/index.js +161 -0
  40. package/src/exports/node/polyfills.js +28 -0
  41. package/src/exports/vite/build/build_server.js +378 -0
  42. package/src/exports/vite/build/build_service_worker.js +91 -0
  43. package/src/exports/vite/build/utils.js +181 -0
  44. package/src/exports/vite/dev/index.js +581 -0
  45. package/src/exports/vite/graph_analysis/index.js +277 -0
  46. package/src/exports/vite/graph_analysis/types.d.ts +5 -0
  47. package/src/exports/vite/graph_analysis/utils.js +30 -0
  48. package/src/exports/vite/index.js +603 -0
  49. package/src/exports/vite/preview/index.js +189 -0
  50. package/src/exports/vite/types.d.ts +3 -0
  51. package/src/exports/vite/utils.js +157 -0
  52. package/src/runtime/app/env.js +1 -0
  53. package/src/runtime/app/environment.js +11 -0
  54. package/src/runtime/app/forms.js +123 -0
  55. package/src/runtime/app/navigation.js +23 -0
  56. package/src/runtime/app/paths.js +1 -0
  57. package/src/runtime/app/stores.js +102 -0
  58. package/src/runtime/client/ambient.d.ts +30 -0
  59. package/src/runtime/client/client.js +1595 -0
  60. package/src/runtime/client/fetcher.js +107 -0
  61. package/src/runtime/client/parse.js +60 -0
  62. package/src/runtime/client/singletons.js +21 -0
  63. package/src/runtime/client/start.js +37 -0
  64. package/src/runtime/client/types.d.ts +84 -0
  65. package/src/runtime/client/utils.js +159 -0
  66. package/src/runtime/components/error.svelte +16 -0
  67. package/{assets → src/runtime}/components/layout.svelte +0 -0
  68. package/src/runtime/control.js +98 -0
  69. package/src/runtime/env/dynamic/private.js +1 -0
  70. package/src/runtime/env/dynamic/public.js +1 -0
  71. package/src/runtime/env-private.js +6 -0
  72. package/src/runtime/env-public.js +6 -0
  73. package/src/runtime/env.js +6 -0
  74. package/src/runtime/hash.js +20 -0
  75. package/src/runtime/paths.js +11 -0
  76. package/src/runtime/server/cookie.js +166 -0
  77. package/src/runtime/server/data/index.js +131 -0
  78. package/src/runtime/server/endpoint.js +92 -0
  79. package/src/runtime/server/fetch.js +174 -0
  80. package/src/runtime/server/index.js +355 -0
  81. package/src/runtime/server/page/actions.js +256 -0
  82. package/src/runtime/server/page/crypto.js +239 -0
  83. package/src/runtime/server/page/csp.js +250 -0
  84. package/src/runtime/server/page/index.js +304 -0
  85. package/src/runtime/server/page/load_data.js +215 -0
  86. package/src/runtime/server/page/render.js +346 -0
  87. package/src/runtime/server/page/respond_with_error.js +102 -0
  88. package/src/runtime/server/page/serialize_data.js +87 -0
  89. package/src/runtime/server/page/types.d.ts +35 -0
  90. package/src/runtime/server/utils.js +181 -0
  91. package/src/utils/array.js +9 -0
  92. package/src/utils/error.js +22 -0
  93. package/src/utils/escape.js +46 -0
  94. package/src/utils/filesystem.js +142 -0
  95. package/src/utils/functions.js +16 -0
  96. package/src/utils/http.js +72 -0
  97. package/src/utils/misc.js +1 -0
  98. package/src/utils/promises.js +17 -0
  99. package/src/utils/routing.js +130 -0
  100. package/src/utils/unit_test.js +11 -0
  101. package/src/utils/url.js +144 -0
  102. package/svelte-kit.js +1 -1
  103. package/types/ambient.d.ts +431 -0
  104. package/types/index.d.ts +477 -0
  105. package/types/internal.d.ts +380 -0
  106. package/types/private.d.ts +224 -0
  107. package/CHANGELOG.md +0 -496
  108. package/assets/components/error.svelte +0 -13
  109. package/assets/runtime/app/env.js +0 -5
  110. package/assets/runtime/app/navigation.js +0 -44
  111. package/assets/runtime/app/paths.js +0 -1
  112. package/assets/runtime/app/stores.js +0 -93
  113. package/assets/runtime/chunks/utils.js +0 -22
  114. package/assets/runtime/internal/singletons.js +0 -23
  115. package/assets/runtime/internal/start.js +0 -776
  116. package/assets/runtime/paths.js +0 -12
  117. package/dist/chunks/index.js +0 -3537
  118. package/dist/chunks/index2.js +0 -587
  119. package/dist/chunks/index3.js +0 -246
  120. package/dist/chunks/index4.js +0 -568
  121. package/dist/chunks/index5.js +0 -763
  122. package/dist/chunks/index6.js +0 -323
  123. package/dist/chunks/standard.js +0 -99
  124. package/dist/chunks/utils.js +0 -83
  125. package/dist/cli.js +0 -555
  126. package/dist/ssr.js +0 -2604
  127. package/types.d.ts +0 -73
  128. package/types.internal.d.ts +0 -222
@@ -0,0 +1,783 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import MagicString from 'magic-string';
4
+ import { posixify, rimraf, walk } from '../../../utils/filesystem.js';
5
+ import { compact } from '../../../utils/array.js';
6
+
7
+ /**
8
+ * @typedef {{
9
+ * file_name: string;
10
+ * modified: boolean;
11
+ * code: string;
12
+ * exports: any[];
13
+ * } | null} Proxy
14
+ *
15
+ * @typedef {{
16
+ * server: Proxy,
17
+ * shared: Proxy
18
+ * }} Proxies
19
+ *
20
+ * @typedef {Map<import('types').PageNode, {route: import('types').RouteData, proxies: Proxies}>} RoutesMap
21
+ */
22
+
23
+ /** @type {import('typescript')} */
24
+ // @ts-ignore
25
+ let ts = undefined;
26
+ try {
27
+ ts = (await import('typescript')).default;
28
+ } catch {}
29
+
30
+ const cwd = process.cwd();
31
+
32
+ /**
33
+ * Creates types for the whole manifest
34
+ * @param {import('types').ValidatedConfig} config
35
+ * @param {import('types').ManifestData} manifest_data
36
+ */
37
+ export async function write_all_types(config, manifest_data) {
38
+ if (!ts) return;
39
+
40
+ const types_dir = `${config.kit.outDir}/types`;
41
+
42
+ // empty out files that no longer need to exist
43
+ const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, '');
44
+ const expected_directories = new Set(
45
+ manifest_data.routes.map((route) => path.join(routes_dir, route.id))
46
+ );
47
+
48
+ if (fs.existsSync(types_dir)) {
49
+ for (const file of walk(types_dir)) {
50
+ const dir = path.dirname(file);
51
+ if (!expected_directories.has(dir)) {
52
+ rimraf(file);
53
+ }
54
+ }
55
+ }
56
+
57
+ // Read/write meta data on each invocation, not once per node process,
58
+ // it could be invoked by another process in the meantime.
59
+ const meta_data_file = `${types_dir}/route_meta_data.json`;
60
+ const has_meta_data = fs.existsSync(meta_data_file);
61
+ let meta_data = has_meta_data
62
+ ? /** @type {Record<string, string[]>} */ (JSON.parse(fs.readFileSync(meta_data_file, 'utf-8')))
63
+ : {};
64
+ const routes_map = create_routes_map(manifest_data);
65
+ // For each directory, write $types.d.ts
66
+ for (const route of manifest_data.routes) {
67
+ if (!route.leaf && !route.layout && !route.endpoint) continue; // nothing to do
68
+
69
+ const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id);
70
+
71
+ // check if the types are out of date
72
+ /** @type {string[]} */
73
+ const input_files = [];
74
+
75
+ /** @type {import('types').PageNode | null} */
76
+ let node = route.leaf;
77
+ while (node) {
78
+ if (node.shared) input_files.push(node.shared);
79
+ if (node.server) input_files.push(node.server);
80
+ node = node.parent ?? null;
81
+ }
82
+
83
+ /** @type {import('types').PageNode | null} */
84
+ node = route.layout;
85
+ while (node) {
86
+ if (node.shared) input_files.push(node.shared);
87
+ if (node.server) input_files.push(node.server);
88
+ node = node.parent ?? null;
89
+ }
90
+
91
+ if (route.endpoint) {
92
+ input_files.push(route.endpoint.file);
93
+ }
94
+
95
+ try {
96
+ fs.mkdirSync(outdir, { recursive: true });
97
+ } catch {}
98
+
99
+ const output_files = compact(
100
+ fs.readdirSync(outdir).map((name) => {
101
+ const stats = fs.statSync(path.join(outdir, name));
102
+ if (stats.isDirectory()) return;
103
+ return {
104
+ name,
105
+ updated: stats.mtimeMs
106
+ };
107
+ })
108
+ );
109
+
110
+ const source_last_updated = Math.max(
111
+ // ctimeMs includes move operations whereas mtimeMs does not
112
+ ...input_files.map((file) => fs.statSync(file).ctimeMs)
113
+ );
114
+ const types_last_updated = Math.max(...output_files.map((file) => file.updated));
115
+
116
+ const should_generate =
117
+ // source files were generated more recently than the types
118
+ source_last_updated > types_last_updated ||
119
+ // no meta data file exists yet
120
+ !has_meta_data ||
121
+ // some file was deleted
122
+ !meta_data[route.id]?.every((file) => input_files.includes(file));
123
+
124
+ if (should_generate) {
125
+ // track which old files end up being surplus to requirements
126
+ const to_delete = new Set(output_files.map((file) => file.name));
127
+ update_types(config, routes_map, route, to_delete);
128
+ meta_data[route.id] = input_files;
129
+ }
130
+ }
131
+
132
+ fs.writeFileSync(meta_data_file, JSON.stringify(meta_data, null, '\t'));
133
+ }
134
+
135
+ /**
136
+ * Creates types related to the given file. This should only be called
137
+ * if the file in question was edited, not if it was created/deleted/moved.
138
+ * @param {import('types').ValidatedConfig} config
139
+ * @param {import('types').ManifestData} manifest_data
140
+ * @param {string} file
141
+ */
142
+ export async function write_types(config, manifest_data, file) {
143
+ if (!ts) return;
144
+
145
+ if (!path.basename(file).startsWith('+')) {
146
+ // Not a route file
147
+ return;
148
+ }
149
+
150
+ const id = posixify(path.relative(config.kit.files.routes, path.dirname(file)));
151
+
152
+ const route = manifest_data.routes.find((route) => route.id === id);
153
+ if (!route) return; // this shouldn't ever happen
154
+ if (!route.leaf && !route.layout && !route.endpoint) return; // nothing to do
155
+
156
+ update_types(config, create_routes_map(manifest_data), route);
157
+ }
158
+
159
+ /**
160
+ * Collect all leafs into a leaf -> route map
161
+ * @param {import('types').ManifestData} manifest_data
162
+ */
163
+ function create_routes_map(manifest_data) {
164
+ /** @type {RoutesMap} */
165
+ const map = new Map();
166
+ for (const route of manifest_data.routes) {
167
+ if (route.leaf) {
168
+ map.set(route.leaf, { route, proxies: { server: null, shared: null } });
169
+ }
170
+ }
171
+ return map;
172
+ }
173
+
174
+ /**
175
+ * Update types for a specific route
176
+ * @param {import('types').ValidatedConfig} config
177
+ * @param {RoutesMap} routes
178
+ * @param {import('types').RouteData} route
179
+ * @param {Set<string>} [to_delete]
180
+ */
181
+ function update_types(config, routes, route, to_delete = new Set()) {
182
+ const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, '');
183
+ const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id);
184
+
185
+ // now generate new types
186
+ const imports = [`import type * as Kit from '@sveltejs/kit';`];
187
+
188
+ /** @type {string[]} */
189
+ const declarations = [];
190
+
191
+ /** @type {string[]} */
192
+ const exports = [];
193
+
194
+ // add 'Expand' helper
195
+ // Makes sure a type is "repackaged" and therefore more readable
196
+ declarations.push('type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;');
197
+ declarations.push(
198
+ `type RouteParams = { ${route.names.map((param) => `${param}: string`).join('; ')} }`
199
+ );
200
+
201
+ // These could also be placed in our public types, but it would bloat them unnecessarily and we may want to change these in the future
202
+ if (route.layout || route.leaf) {
203
+ // If T extends the empty object, void is also allowed as a return type
204
+ declarations.push(`type MaybeWithVoid<T> = {} extends T ? T | void : T;`);
205
+ // Returns the key of the object whose values are required.
206
+ declarations.push(
207
+ `export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];`
208
+ );
209
+ // Helper type to get the correct output type for load functions. It should be passed the parent type to check what types from App.PageData are still required.
210
+ // If none, void is also allowed as a return type.
211
+ declarations.push(
212
+ `type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>`
213
+ );
214
+ // null & {} == null, we need to prevent that in some situations
215
+ declarations.push(`type EnsureDefined<T> = T extends null | undefined ? {} : T;`);
216
+ }
217
+
218
+ if (route.leaf) {
219
+ let route_info = routes.get(route.leaf);
220
+ if (!route_info) {
221
+ // This should be defined, but belts and braces
222
+ route_info = { route, proxies: { server: null, shared: null } };
223
+ routes.set(route.leaf, route_info);
224
+ }
225
+
226
+ const {
227
+ declarations: d,
228
+ exports: e,
229
+ proxies
230
+ } = process_node(route.leaf, outdir, true, route_info.proxies);
231
+
232
+ exports.push(...e);
233
+ declarations.push(...d);
234
+
235
+ if (proxies.server) {
236
+ route_info.proxies.server = proxies.server;
237
+ if (proxies.server?.modified) to_delete.delete(proxies.server.file_name);
238
+ }
239
+ if (proxies.shared) {
240
+ route_info.proxies.shared = proxies.shared;
241
+ if (proxies.shared?.modified) to_delete.delete(proxies.shared.file_name);
242
+ }
243
+
244
+ if (route.leaf.server) {
245
+ exports.push(`export type Action = Kit.Action<RouteParams>`);
246
+ exports.push(`export type Actions = Kit.Actions<RouteParams>`);
247
+ }
248
+ }
249
+
250
+ if (route.layout) {
251
+ let all_pages_have_load = true;
252
+ const layout_params = new Set();
253
+ route.layout.child_pages?.forEach((page) => {
254
+ const leaf = routes.get(page);
255
+ if (leaf) {
256
+ for (const name of leaf.route.names) {
257
+ layout_params.add(name);
258
+ }
259
+
260
+ ensureProxies(page, leaf.proxies);
261
+
262
+ if (
263
+ // Be defensive - if a proxy doesn't exist (because it couldn't be created), assume a load function exists.
264
+ // If we didn't and it's a false negative, the user could wrongfully get a type error on layouts.
265
+ (leaf.proxies.server && !leaf.proxies.server.exports.includes('load')) ||
266
+ (leaf.proxies.shared && !leaf.proxies.shared.exports.includes('load'))
267
+ ) {
268
+ all_pages_have_load = false;
269
+ }
270
+ }
271
+ if (!page.server && !page.shared) {
272
+ all_pages_have_load = false;
273
+ }
274
+ });
275
+
276
+ declarations.push(
277
+ `type LayoutParams = RouteParams & { ${Array.from(layout_params).map(
278
+ (param) => `${param}?: string`
279
+ )} }`
280
+ );
281
+
282
+ const {
283
+ exports: e,
284
+ declarations: d,
285
+ proxies
286
+ } = process_node(
287
+ route.layout,
288
+ outdir,
289
+ false,
290
+ { server: null, shared: null },
291
+ all_pages_have_load
292
+ );
293
+
294
+ exports.push(...e);
295
+ declarations.push(...d);
296
+
297
+ if (proxies.server?.modified) to_delete.delete(proxies.server.file_name);
298
+ if (proxies.shared?.modified) to_delete.delete(proxies.shared.file_name);
299
+ }
300
+
301
+ if (route.endpoint) {
302
+ exports.push(`export type RequestHandler = Kit.RequestHandler<RouteParams>;`);
303
+ }
304
+
305
+ if (route.leaf?.server || route.layout?.server || route.endpoint) {
306
+ exports.push(`export type RequestEvent = Kit.RequestEvent<RouteParams>;`);
307
+ }
308
+
309
+ const output = [imports.join('\n'), declarations.join('\n'), exports.join('\n')]
310
+ .filter(Boolean)
311
+ .join('\n\n');
312
+
313
+ fs.writeFileSync(`${outdir}/$types.d.ts`, output);
314
+ to_delete.delete('$types.d.ts');
315
+
316
+ for (const file of to_delete) {
317
+ fs.unlinkSync(path.join(outdir, file));
318
+ }
319
+ }
320
+
321
+ /**
322
+ * @param {import('types').PageNode} node
323
+ * @param {string} outdir
324
+ * @param {boolean} is_page
325
+ * @param {Proxies} proxies
326
+ * @param {boolean} [all_pages_have_load]
327
+ */
328
+ function process_node(node, outdir, is_page, proxies, all_pages_have_load = true) {
329
+ const params = `${is_page ? 'Route' : 'Layout'}Params`;
330
+ const prefix = is_page ? 'Page' : 'Layout';
331
+
332
+ /** @type {string[]} */
333
+ const declarations = [];
334
+ /** @type {string[]} */
335
+ const exports = [];
336
+
337
+ /** @type {string} */
338
+ let server_data;
339
+ /** @type {string} */
340
+ let data;
341
+
342
+ ensureProxies(node, proxies);
343
+
344
+ if (node.server) {
345
+ const basename = path.basename(node.server);
346
+ const proxy = proxies.server;
347
+ if (proxy?.modified) {
348
+ fs.writeFileSync(`${outdir}/proxy${basename}`, proxy.code);
349
+ }
350
+
351
+ server_data = get_data_type(node.server, 'null', proxy, true);
352
+
353
+ const parent_type = `${prefix}ServerParentData`;
354
+
355
+ declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutServerData')};`);
356
+
357
+ // +page.js load present -> server can return all-optional data
358
+ const output_data_shape =
359
+ node.shared || (!is_page && all_pages_have_load)
360
+ ? `Partial<App.PageData> & Record<string, any> | void`
361
+ : `OutputDataShape<${parent_type}>`;
362
+ exports.push(
363
+ `export type ${prefix}ServerLoad<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.ServerLoad<${params}, ${parent_type}, OutputData>;`
364
+ );
365
+
366
+ exports.push(`export type ${prefix}ServerLoadEvent = Parameters<${prefix}ServerLoad>[0];`);
367
+
368
+ if (is_page) {
369
+ let type = 'unknown';
370
+ if (proxy) {
371
+ if (proxy.exports.includes('actions')) {
372
+ // If the file wasn't tweaked, we can use the return type of the original file.
373
+ // The advantage is that type updates are reflected without saving.
374
+ const from = proxy.modified
375
+ ? `./proxy${replace_ext_with_js(basename)}`
376
+ : path_to_original(outdir, node.server);
377
+
378
+ type = `Expand<Kit.AwaitedActions<typeof import('${from}').actions>> | undefined`;
379
+ }
380
+ }
381
+ exports.push(`export type ActionData = ${type};`);
382
+ }
383
+ } else {
384
+ server_data = 'null';
385
+ }
386
+ exports.push(`export type ${prefix}ServerData = ${server_data};`);
387
+
388
+ const parent_type = `${prefix}ParentData`;
389
+ declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutData')};`);
390
+
391
+ if (node.shared) {
392
+ const proxy = proxies.shared;
393
+ if (proxy?.modified) {
394
+ fs.writeFileSync(`${outdir}/proxy${path.basename(node.shared)}`, proxy.code);
395
+ }
396
+
397
+ const type = get_data_type(
398
+ node.shared,
399
+ `${parent_type} & EnsureDefined<${prefix}ServerData>`,
400
+ proxy
401
+ );
402
+
403
+ data = `Expand<Omit<${parent_type}, keyof ${type}> & EnsureDefined<${type}>>`;
404
+
405
+ const output_data_shape =
406
+ !is_page && all_pages_have_load
407
+ ? `Partial<App.PageData> & Record<string, any> | void`
408
+ : `OutputDataShape<${parent_type}>`;
409
+ exports.push(
410
+ `export type ${prefix}Load<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.Load<${params}, ${prefix}ServerData, ${parent_type}, OutputData>;`
411
+ );
412
+
413
+ exports.push(`export type ${prefix}LoadEvent = Parameters<${prefix}Load>[0];`);
414
+ } else if (server_data === 'null') {
415
+ data = `Expand<${parent_type}>`;
416
+ } else {
417
+ data = `Expand<Omit<${parent_type}, keyof ${prefix}ServerData> & EnsureDefined<${prefix}ServerData>>`;
418
+ }
419
+
420
+ exports.push(`export type ${prefix}Data = ${data};`);
421
+
422
+ return { declarations, exports, proxies };
423
+
424
+ /**
425
+ * @param {string} file_path
426
+ * @param {string} fallback
427
+ * @param {Proxy} proxy
428
+ * @param {boolean} expand
429
+ */
430
+ function get_data_type(file_path, fallback, proxy, expand = false) {
431
+ if (proxy) {
432
+ if (proxy.exports.includes('load')) {
433
+ // If the file wasn't tweaked, we can use the return type of the original file.
434
+ // The advantage is that type updates are reflected without saving.
435
+ const from = proxy.modified
436
+ ? `./proxy${replace_ext_with_js(path.basename(file_path))}`
437
+ : path_to_original(outdir, file_path);
438
+ const type = `Kit.AwaitedProperties<Awaited<ReturnType<typeof import('${from}').load>>>`;
439
+ return expand ? `Expand<${type}>` : type;
440
+ } else {
441
+ return fallback;
442
+ }
443
+ } else {
444
+ return 'unknown';
445
+ }
446
+ }
447
+ }
448
+
449
+ /**
450
+ * This function populates the proxies object, if necessary and not already done.
451
+ * Proxies are used to tweak the code of a file before it's typechecked.
452
+ * They are needed in two places - when generating the types for a page or layout.
453
+ * To not do the same work twice, we generate the proxies once and pass them around.
454
+ *
455
+ * @param {import('types').PageNode} node
456
+ * @param {Proxies} proxies
457
+ */
458
+ function ensureProxies(node, proxies) {
459
+ if (node.server && !proxies.server) {
460
+ proxies.server = createProxy(node.server, true);
461
+ }
462
+
463
+ if (node.shared && !proxies.shared) {
464
+ proxies.shared = createProxy(node.shared, false);
465
+ }
466
+ }
467
+
468
+ /**
469
+ * @param {string} file_path
470
+ * @param {boolean} is_server
471
+ * @returns {Proxy}
472
+ */
473
+ function createProxy(file_path, is_server) {
474
+ const proxy = tweak_types(fs.readFileSync(file_path, 'utf8'), is_server);
475
+ if (proxy) {
476
+ return {
477
+ ...proxy,
478
+ file_name: `proxy${path.basename(file_path)}`
479
+ };
480
+ } else {
481
+ return null;
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Get the parent type string by recursively looking up the parent layout and accumulate them to one type.
487
+ * @param {import('types').PageNode} node
488
+ * @param {string} type
489
+ */
490
+ function get_parent_type(node, type) {
491
+ const parent_imports = [];
492
+
493
+ let parent = node.parent;
494
+
495
+ while (parent) {
496
+ const d = node.depth - parent.depth;
497
+ // unshift because we need it the other way round for the import string
498
+ parent_imports.unshift(
499
+ `${d === 0 ? '' : `import('${'../'.repeat(d)}${'$types.js'}').`}${type}`
500
+ );
501
+ parent = parent.parent;
502
+ }
503
+
504
+ let parent_str = `EnsureDefined<${parent_imports[0] || '{}'}>`;
505
+ for (let i = 1; i < parent_imports.length; i++) {
506
+ // Omit is necessary because a parent could have a property with the same key which would
507
+ // cause a type conflict. At runtime the child overwrites the parent property in this case,
508
+ // so reflect that in the type definition.
509
+ // EnsureDefined is necessary because {something: string} & null becomes null.
510
+ // Output types of server loads can be null but when passed in through the `parent` parameter they are the empty object instead.
511
+ parent_str = `Omit<${parent_str}, keyof ${parent_imports[i]}> & EnsureDefined<${parent_imports[i]}>`;
512
+ }
513
+ return parent_str;
514
+ }
515
+
516
+ /**
517
+ * @param {string} outdir
518
+ * @param {string} file_path
519
+ */
520
+ function path_to_original(outdir, file_path) {
521
+ return posixify(path.relative(outdir, path.join(cwd, replace_ext_with_js(file_path))));
522
+ }
523
+
524
+ /**
525
+ * @param {string} file_path
526
+ */
527
+ function replace_ext_with_js(file_path) {
528
+ // Another extension than `.js` (or nothing, but that fails with node16 moduleResolution)
529
+ // will result in TS failing to lookup the file
530
+ const ext = path.extname(file_path);
531
+ return file_path.slice(0, -ext.length) + '.js';
532
+ }
533
+
534
+ /**
535
+ * @param {string} content
536
+ * @param {boolean} is_server
537
+ * @returns {Omit<NonNullable<Proxy>, 'file_name'> | null}
538
+ */
539
+ export function tweak_types(content, is_server) {
540
+ const names = new Set(is_server ? ['load', 'actions'] : ['load']);
541
+
542
+ try {
543
+ let modified = false;
544
+
545
+ const ast = ts.createSourceFile(
546
+ 'filename.ts',
547
+ content,
548
+ ts.ScriptTarget.Latest,
549
+ false,
550
+ ts.ScriptKind.TS
551
+ );
552
+
553
+ const code = new MagicString(content);
554
+
555
+ const exports = new Map();
556
+
557
+ ast.forEachChild((node) => {
558
+ if (
559
+ ts.isExportDeclaration(node) &&
560
+ node.exportClause &&
561
+ ts.isNamedExports(node.exportClause)
562
+ ) {
563
+ node.exportClause.elements.forEach((element) => {
564
+ const exported = element.name;
565
+ if (names.has(element.name.text)) {
566
+ const local = element.propertyName || element.name;
567
+ exports.set(exported.text, local.text);
568
+ }
569
+ });
570
+ }
571
+
572
+ if (node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
573
+ if (ts.isFunctionDeclaration(node) && node.name?.text && names.has(node.name?.text)) {
574
+ exports.set(node.name.text, node.name.text);
575
+ }
576
+
577
+ if (ts.isVariableStatement(node)) {
578
+ node.declarationList.declarations.forEach((declaration) => {
579
+ if (ts.isIdentifier(declaration.name) && names.has(declaration.name.text)) {
580
+ exports.set(declaration.name.text, declaration.name.text);
581
+ }
582
+ });
583
+ }
584
+ }
585
+ });
586
+
587
+ /**
588
+ * @param {import('typescript').Node} node
589
+ * @param {import('typescript').Node} value
590
+ */
591
+ function replace_jsdoc_type_tags(node, value) {
592
+ let _modified = false;
593
+ // @ts-ignore
594
+ if (node.jsDoc) {
595
+ // @ts-ignore
596
+ for (const comment of node.jsDoc) {
597
+ for (const tag of comment.tags ?? []) {
598
+ if (ts.isJSDocTypeTag(tag)) {
599
+ const is_fn =
600
+ ts.isFunctionDeclaration(value) ||
601
+ ts.isFunctionExpression(value) ||
602
+ ts.isArrowFunction(value);
603
+
604
+ if (is_fn && value.parameters?.length > 0) {
605
+ const name = ts.isIdentifier(value.parameters[0].name)
606
+ ? value.parameters[0].name.text
607
+ : 'event';
608
+ code.overwrite(tag.tagName.pos, tag.tagName.end, 'param');
609
+ code.prependRight(tag.typeExpression.pos + 1, 'Parameters<');
610
+ code.appendLeft(tag.typeExpression.end - 1, '>[0]');
611
+ code.appendLeft(tag.typeExpression.end, ` ${name}`);
612
+ } else {
613
+ code.overwrite(tag.pos, tag.end, '');
614
+ }
615
+ _modified = true;
616
+ }
617
+ }
618
+ }
619
+ }
620
+ modified = modified || _modified;
621
+ return _modified;
622
+ }
623
+
624
+ ast.forEachChild((node) => {
625
+ if (ts.isFunctionDeclaration(node) && node.name?.text && node.name?.text === 'load') {
626
+ // remove JSDoc comment above `export function load ...`
627
+ replace_jsdoc_type_tags(node, node);
628
+ }
629
+
630
+ if (ts.isVariableStatement(node)) {
631
+ // remove JSDoc comment above `export const load = ...`
632
+ if (
633
+ ts.isIdentifier(node.declarationList.declarations[0].name) &&
634
+ names.has(node.declarationList.declarations[0].name.text) &&
635
+ node.declarationList.declarations[0].initializer
636
+ ) {
637
+ replace_jsdoc_type_tags(node, node.declarationList.declarations[0].initializer);
638
+ }
639
+
640
+ for (const declaration of node.declarationList.declarations) {
641
+ if (
642
+ ts.isIdentifier(declaration.name) &&
643
+ declaration.name.text === 'load' &&
644
+ declaration.initializer
645
+ ) {
646
+ // edge case — remove JSDoc comment above individual export
647
+ replace_jsdoc_type_tags(declaration, declaration.initializer);
648
+
649
+ // remove type from `export const load: Load ...`
650
+ if (declaration.type) {
651
+ let a = declaration.type.pos;
652
+ let b = declaration.type.end;
653
+ while (/\s/.test(content[a])) a += 1;
654
+
655
+ const type = content.slice(a, b);
656
+ code.remove(declaration.name.end, declaration.type.end);
657
+
658
+ const rhs = declaration.initializer;
659
+
660
+ if (
661
+ rhs &&
662
+ (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
663
+ rhs.parameters.length
664
+ ) {
665
+ const arg = rhs.parameters[0];
666
+ const add_parens = content[arg.pos - 1] !== '(';
667
+
668
+ if (add_parens) code.prependRight(arg.pos, '(');
669
+
670
+ if (arg && !arg.type) {
671
+ code.appendLeft(
672
+ arg.name.end,
673
+ `: Parameters<${type}>[0]` + (add_parens ? ')' : '')
674
+ );
675
+ } else {
676
+ // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs
677
+ code.append(`;null as any as ${type};`);
678
+ }
679
+ } else {
680
+ // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs
681
+ code.append(`;null as any as ${type};`);
682
+ }
683
+
684
+ modified = true;
685
+ }
686
+ } else if (
687
+ is_server &&
688
+ ts.isIdentifier(declaration.name) &&
689
+ declaration.name?.text === 'actions' &&
690
+ declaration.initializer
691
+ ) {
692
+ // remove JSDoc comment from `export const actions = ..`
693
+ const removed = replace_jsdoc_type_tags(node, declaration.initializer);
694
+ // ... and move type to each individual action
695
+ if (removed) {
696
+ const rhs = declaration.initializer;
697
+ if (ts.isObjectLiteralExpression(rhs)) {
698
+ for (const prop of rhs.properties) {
699
+ if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
700
+ const rhs = prop.initializer;
701
+ const replaced = replace_jsdoc_type_tags(prop, rhs);
702
+ if (
703
+ !replaced &&
704
+ rhs &&
705
+ (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
706
+ rhs.parameters?.[0]
707
+ ) {
708
+ const name = ts.isIdentifier(rhs.parameters[0].name)
709
+ ? rhs.parameters[0].name.text
710
+ : 'event';
711
+ code.prependRight(
712
+ rhs.pos,
713
+ `/** @param {import('./$types').RequestEvent} ${name} */ `
714
+ );
715
+ }
716
+ }
717
+ }
718
+ }
719
+ }
720
+
721
+ // remove type from `export const actions: Actions ...`
722
+ if (declaration.type) {
723
+ let a = declaration.type.pos;
724
+ let b = declaration.type.end;
725
+ while (/\s/.test(content[a])) a += 1;
726
+
727
+ const type = content.slice(a, b);
728
+ code.remove(declaration.name.end, declaration.type.end);
729
+ code.append(`;null as any as ${type};`);
730
+ modified = true;
731
+
732
+ // ... and move type to each individual action
733
+ const rhs = declaration.initializer;
734
+ if (ts.isObjectLiteralExpression(rhs)) {
735
+ for (const prop of rhs.properties) {
736
+ if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
737
+ const rhs = prop.initializer;
738
+
739
+ if (
740
+ rhs &&
741
+ (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
742
+ rhs.parameters.length
743
+ ) {
744
+ const arg = rhs.parameters[0];
745
+ const add_parens = content[arg.pos - 1] !== '(';
746
+
747
+ if (add_parens) code.prependRight(arg.pos, '(');
748
+
749
+ if (arg && !arg.type) {
750
+ code.appendLeft(
751
+ arg.name.end,
752
+ `: import('./$types').RequestEvent` + (add_parens ? ')' : '')
753
+ );
754
+ }
755
+ }
756
+ }
757
+ }
758
+ }
759
+ }
760
+ }
761
+ }
762
+ }
763
+ });
764
+
765
+ if (modified) {
766
+ // Ignore all type errors so they don't show up twice when svelte-check runs
767
+ // Account for possible @ts-check which would overwrite @ts-nocheck
768
+ if (code.original.startsWith('// @ts-check')) {
769
+ code.prependLeft('// @ts-check'.length, '\n// @ts-nocheck\n');
770
+ } else {
771
+ code.prepend('// @ts-nocheck\n');
772
+ }
773
+ }
774
+
775
+ return {
776
+ modified,
777
+ code: code.toString(),
778
+ exports: Array.from(exports.keys())
779
+ };
780
+ } catch {
781
+ return null;
782
+ }
783
+ }