@sveltejs/kit 1.0.0-next.47 → 1.0.0-next.470

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 (115) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -64
  3. package/scripts/special-types/$env+dynamic+private.md +8 -0
  4. package/scripts/special-types/$env+dynamic+public.md +8 -0
  5. package/scripts/special-types/$env+static+private.md +19 -0
  6. package/scripts/special-types/$env+static+public.md +7 -0
  7. package/scripts/special-types/$lib.md +1 -0
  8. package/src/cli.js +112 -0
  9. package/src/constants.js +7 -0
  10. package/src/core/adapt/builder.js +207 -0
  11. package/src/core/adapt/index.js +31 -0
  12. package/src/core/config/default-error.html +56 -0
  13. package/src/core/config/index.js +105 -0
  14. package/src/core/config/options.js +502 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +121 -0
  17. package/src/core/generate_manifest/index.js +92 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +425 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +472 -0
  22. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  23. package/src/core/sync/sync.js +59 -0
  24. package/src/core/sync/utils.js +33 -0
  25. package/src/core/sync/write_ambient.js +53 -0
  26. package/src/core/sync/write_client_manifest.js +94 -0
  27. package/src/core/sync/write_matchers.js +25 -0
  28. package/src/core/sync/write_root.js +91 -0
  29. package/src/core/sync/write_tsconfig.js +195 -0
  30. package/src/core/sync/write_types/index.js +595 -0
  31. package/src/core/utils.js +70 -0
  32. package/src/exports/hooks/index.js +1 -0
  33. package/src/exports/hooks/sequence.js +44 -0
  34. package/src/exports/index.js +45 -0
  35. package/src/exports/node/index.js +145 -0
  36. package/src/exports/node/polyfills.js +40 -0
  37. package/src/exports/vite/build/build_server.js +358 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +162 -0
  40. package/src/exports/vite/dev/index.js +547 -0
  41. package/src/exports/vite/index.js +601 -0
  42. package/src/exports/vite/preview/index.js +186 -0
  43. package/src/exports/vite/types.d.ts +3 -0
  44. package/src/exports/vite/utils.js +345 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/navigation.js +23 -0
  48. package/src/runtime/app/paths.js +1 -0
  49. package/src/runtime/app/stores.js +102 -0
  50. package/src/runtime/client/ambient.d.ts +24 -0
  51. package/src/runtime/client/client.js +1494 -0
  52. package/src/runtime/client/fetcher.js +107 -0
  53. package/src/runtime/client/parse.js +60 -0
  54. package/src/runtime/client/singletons.js +21 -0
  55. package/src/runtime/client/start.js +45 -0
  56. package/src/runtime/client/types.d.ts +91 -0
  57. package/src/runtime/client/utils.js +159 -0
  58. package/src/runtime/components/error.svelte +16 -0
  59. package/{assets → src/runtime}/components/layout.svelte +0 -0
  60. package/src/runtime/control.js +33 -0
  61. package/src/runtime/env/dynamic/private.js +1 -0
  62. package/src/runtime/env/dynamic/public.js +1 -0
  63. package/src/runtime/env-private.js +6 -0
  64. package/src/runtime/env-public.js +6 -0
  65. package/src/runtime/env.js +6 -0
  66. package/src/runtime/hash.js +16 -0
  67. package/src/runtime/paths.js +11 -0
  68. package/src/runtime/server/data/index.js +146 -0
  69. package/src/runtime/server/endpoint.js +63 -0
  70. package/src/runtime/server/index.js +354 -0
  71. package/src/runtime/server/page/cookie.js +25 -0
  72. package/src/runtime/server/page/crypto.js +239 -0
  73. package/src/runtime/server/page/csp.js +249 -0
  74. package/src/runtime/server/page/fetch.js +282 -0
  75. package/src/runtime/server/page/index.js +404 -0
  76. package/src/runtime/server/page/load_data.js +124 -0
  77. package/src/runtime/server/page/render.js +358 -0
  78. package/src/runtime/server/page/respond_with_error.js +92 -0
  79. package/src/runtime/server/page/serialize_data.js +72 -0
  80. package/src/runtime/server/page/types.d.ts +45 -0
  81. package/src/runtime/server/utils.js +209 -0
  82. package/src/utils/array.js +9 -0
  83. package/src/utils/error.js +22 -0
  84. package/src/utils/escape.js +46 -0
  85. package/src/utils/filesystem.js +108 -0
  86. package/src/utils/functions.js +16 -0
  87. package/src/utils/http.js +55 -0
  88. package/src/utils/misc.js +1 -0
  89. package/src/utils/routing.js +117 -0
  90. package/src/utils/url.js +142 -0
  91. package/svelte-kit.js +1 -1
  92. package/types/ambient.d.ts +356 -0
  93. package/types/index.d.ts +356 -0
  94. package/types/internal.d.ts +386 -0
  95. package/types/private.d.ts +213 -0
  96. package/CHANGELOG.md +0 -463
  97. package/assets/components/error.svelte +0 -13
  98. package/assets/runtime/app/env.js +0 -5
  99. package/assets/runtime/app/navigation.js +0 -44
  100. package/assets/runtime/app/paths.js +0 -1
  101. package/assets/runtime/app/stores.js +0 -93
  102. package/assets/runtime/chunks/utils.js +0 -22
  103. package/assets/runtime/internal/singletons.js +0 -23
  104. package/assets/runtime/internal/start.js +0 -773
  105. package/assets/runtime/paths.js +0 -12
  106. package/dist/chunks/index.js +0 -3517
  107. package/dist/chunks/index2.js +0 -587
  108. package/dist/chunks/index3.js +0 -246
  109. package/dist/chunks/index4.js +0 -530
  110. package/dist/chunks/index5.js +0 -763
  111. package/dist/chunks/index6.js +0 -322
  112. package/dist/chunks/standard.js +0 -99
  113. package/dist/chunks/utils.js +0 -83
  114. package/dist/cli.js +0 -553
  115. package/dist/ssr.js +0 -2581
@@ -0,0 +1,105 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import * as url from 'url';
4
+ import options from './options.js';
5
+
6
+ /**
7
+ * Loads the template (src/app.html by default) and validates that it has the
8
+ * required content.
9
+ * @param {string} cwd
10
+ * @param {import('types').ValidatedConfig} config
11
+ */
12
+ export function load_template(cwd, config) {
13
+ const { appTemplate } = config.kit.files;
14
+ const relative = path.relative(cwd, appTemplate);
15
+
16
+ if (fs.existsSync(appTemplate)) {
17
+ const contents = fs.readFileSync(appTemplate, 'utf8');
18
+
19
+ // TODO remove this for 1.0
20
+ const match = /%svelte\.([a-z]+)%/.exec(contents);
21
+ if (match) {
22
+ throw new Error(
23
+ `%svelte.${match[1]}% in ${relative} should be replaced with %sveltekit.${match[1]}%`
24
+ );
25
+ }
26
+
27
+ const expected_tags = ['%sveltekit.head%', '%sveltekit.body%'];
28
+ expected_tags.forEach((tag) => {
29
+ if (contents.indexOf(tag) === -1) {
30
+ throw new Error(`${relative} is missing ${tag}`);
31
+ }
32
+ });
33
+ } else {
34
+ throw new Error(`${relative} does not exist`);
35
+ }
36
+
37
+ return fs.readFileSync(appTemplate, 'utf-8');
38
+ }
39
+
40
+ /**
41
+ * Loads the error page (src/error.html by default) if it exists.
42
+ * Falls back to a generic error page content.
43
+ * @param {import('types').ValidatedConfig} config
44
+ */
45
+ export function load_error_page(config) {
46
+ const { errorTemplate } = config.kit.files;
47
+ return fs.readFileSync(errorTemplate, 'utf-8');
48
+ }
49
+
50
+ /**
51
+ * Loads and validates svelte.config.js
52
+ * @param {{ cwd?: string }} options
53
+ * @returns {Promise<import('types').ValidatedConfig>}
54
+ */
55
+ export async function load_config({ cwd = process.cwd() } = {}) {
56
+ const config_file = path.join(cwd, 'svelte.config.js');
57
+
58
+ if (!fs.existsSync(config_file)) {
59
+ return process_config({}, { cwd });
60
+ }
61
+
62
+ const config = await import(`${url.pathToFileURL(config_file).href}?ts=${Date.now()}`);
63
+
64
+ return process_config(config.default, { cwd });
65
+ }
66
+
67
+ /**
68
+ * @param {import('types').Config} config
69
+ * @returns {import('types').ValidatedConfig}
70
+ */
71
+ function process_config(config, { cwd = process.cwd() } = {}) {
72
+ const validated = validate_config(config);
73
+
74
+ validated.kit.outDir = path.resolve(cwd, validated.kit.outDir);
75
+
76
+ for (const key in validated.kit.files) {
77
+ // TODO remove for 1.0
78
+ if (key === 'template') continue;
79
+
80
+ // @ts-expect-error this is typescript at its stupidest
81
+ validated.kit.files[key] = path.resolve(cwd, validated.kit.files[key]);
82
+ }
83
+
84
+ if (!fs.existsSync(validated.kit.files.errorTemplate)) {
85
+ validated.kit.files.errorTemplate = url.fileURLToPath(
86
+ new URL('./default-error.html', import.meta.url)
87
+ );
88
+ }
89
+
90
+ return validated;
91
+ }
92
+
93
+ /**
94
+ * @param {import('types').Config} config
95
+ * @returns {import('types').ValidatedConfig}
96
+ */
97
+ export function validate_config(config) {
98
+ if (typeof config !== 'object') {
99
+ throw new Error(
100
+ 'svelte.config.js must have a configuration object as its default export. See https://kit.svelte.dev/docs/configuration'
101
+ );
102
+ }
103
+
104
+ return options(config, 'config');
105
+ }
@@ -0,0 +1,502 @@
1
+ import { join } from 'path';
2
+
3
+ /** @typedef {import('./types').Validator} Validator */
4
+
5
+ const directives = object({
6
+ 'child-src': string_array(),
7
+ 'default-src': string_array(),
8
+ 'frame-src': string_array(),
9
+ 'worker-src': string_array(),
10
+ 'connect-src': string_array(),
11
+ 'font-src': string_array(),
12
+ 'img-src': string_array(),
13
+ 'manifest-src': string_array(),
14
+ 'media-src': string_array(),
15
+ 'object-src': string_array(),
16
+ 'prefetch-src': string_array(),
17
+ 'script-src': string_array(),
18
+ 'script-src-elem': string_array(),
19
+ 'script-src-attr': string_array(),
20
+ 'style-src': string_array(),
21
+ 'style-src-elem': string_array(),
22
+ 'style-src-attr': string_array(),
23
+ 'base-uri': string_array(),
24
+ sandbox: string_array(),
25
+ 'form-action': string_array(),
26
+ 'frame-ancestors': string_array(),
27
+ 'navigate-to': string_array(),
28
+ 'report-uri': string_array(),
29
+ 'report-to': string_array(),
30
+ 'require-trusted-types-for': string_array(),
31
+ 'trusted-types': string_array(),
32
+ 'upgrade-insecure-requests': boolean(false),
33
+ 'require-sri-for': string_array(),
34
+ 'block-all-mixed-content': boolean(false),
35
+ 'plugin-types': string_array(),
36
+ referrer: string_array()
37
+ });
38
+
39
+ /** @type {Validator} */
40
+ const options = object(
41
+ {
42
+ extensions: validate(['.svelte'], (input, keypath) => {
43
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
44
+ throw new Error(`${keypath} must be an array of strings`);
45
+ }
46
+
47
+ input.forEach((extension) => {
48
+ if (extension[0] !== '.') {
49
+ throw new Error(`Each member of ${keypath} must start with '.' — saw '${extension}'`);
50
+ }
51
+
52
+ if (!/^(\.[a-z0-9]+)+$/i.test(extension)) {
53
+ throw new Error(`File extensions must be alphanumeric — saw '${extension}'`);
54
+ }
55
+ });
56
+
57
+ return input;
58
+ }),
59
+
60
+ kit: object({
61
+ adapter: validate(null, (input, keypath) => {
62
+ if (typeof input !== 'object' || !input.adapt) {
63
+ let message = `${keypath} should be an object with an "adapt" method`;
64
+
65
+ if (Array.isArray(input) || typeof input === 'string') {
66
+ // for the early adapter adopters
67
+ message += ', rather than the name of an adapter';
68
+ }
69
+
70
+ throw new Error(`${message}. See https://kit.svelte.dev/docs/adapters`);
71
+ }
72
+
73
+ return input;
74
+ }),
75
+
76
+ alias: validate({}, (input, keypath) => {
77
+ if (typeof input !== 'object') {
78
+ throw new Error(`${keypath} should be an object`);
79
+ }
80
+
81
+ for (const key in input) {
82
+ assert_string(input[key], `${keypath}.${key}`);
83
+ }
84
+
85
+ return input;
86
+ }),
87
+
88
+ // TODO: remove this for the 1.0 release
89
+ amp: error(
90
+ (keypath) =>
91
+ `${keypath} has been removed. See https://kit.svelte.dev/docs/seo#amp for details on how to support AMP`
92
+ ),
93
+
94
+ appDir: validate('_app', (input, keypath) => {
95
+ assert_string(input, keypath);
96
+
97
+ if (input) {
98
+ if (input.startsWith('/') || input.endsWith('/')) {
99
+ throw new Error(
100
+ "config.kit.appDir cannot start or end with '/'. See https://kit.svelte.dev/docs/configuration"
101
+ );
102
+ }
103
+ } else {
104
+ throw new Error(`${keypath} cannot be empty`);
105
+ }
106
+
107
+ return input;
108
+ }),
109
+
110
+ // TODO: remove this for the 1.0 release
111
+ browser: object({
112
+ hydrate: error(
113
+ (keypath) =>
114
+ `${keypath} has been removed. You can set it inside the top level +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197`
115
+ ),
116
+ router: error(
117
+ (keypath) =>
118
+ `${keypath} has been removed. You can set it inside the top level +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197`
119
+ )
120
+ }),
121
+
122
+ csp: object({
123
+ mode: list(['auto', 'hash', 'nonce']),
124
+ directives,
125
+ reportOnly: directives
126
+ }),
127
+
128
+ csrf: object({
129
+ checkOrigin: boolean(true)
130
+ }),
131
+
132
+ // TODO: remove this for the 1.0 release
133
+ endpointExtensions: error(
134
+ (keypath) => `${keypath} has been renamed to config.kit.moduleExtensions`
135
+ ),
136
+
137
+ env: object({
138
+ dir: string(process.cwd()),
139
+ publicPrefix: string('PUBLIC_')
140
+ }),
141
+
142
+ files: object({
143
+ assets: string('static'),
144
+ hooks: string(join('src', 'hooks')),
145
+ lib: string(join('src', 'lib')),
146
+ params: string(join('src', 'params')),
147
+ routes: string(join('src', 'routes')),
148
+ serviceWorker: string(join('src', 'service-worker')),
149
+ appTemplate: string(join('src', 'app.html')),
150
+ errorTemplate: string(join('src', 'error.html')),
151
+ // TODO: remove this for the 1.0 release
152
+ template: error(
153
+ () => 'config.kit.files.template has been renamed to config.kit.files.appTemplate'
154
+ )
155
+ }),
156
+
157
+ // TODO: remove this for the 1.0 release
158
+ headers: error(
159
+ (keypath) =>
160
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
161
+ ),
162
+
163
+ // TODO: remove this for the 1.0 release
164
+ host: error(
165
+ (keypath) =>
166
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
167
+ ),
168
+
169
+ // TODO remove for 1.0
170
+ hydrate: error((keypath) => `${keypath} has been moved to config.kit.browser.hydrate`),
171
+
172
+ inlineStyleThreshold: number(0),
173
+
174
+ methodOverride: object({
175
+ parameter: string('_method'),
176
+ allowed: validate([], (input, keypath) => {
177
+ if (!Array.isArray(input) || !input.every((method) => typeof method === 'string')) {
178
+ throw new Error(`${keypath} must be an array of strings`);
179
+ }
180
+
181
+ if (input.map((i) => i.toUpperCase()).includes('GET')) {
182
+ throw new Error(`${keypath} cannot contain "GET"`);
183
+ }
184
+
185
+ return input;
186
+ })
187
+ }),
188
+
189
+ moduleExtensions: string_array(['.js', '.ts']),
190
+
191
+ outDir: string('.svelte-kit'),
192
+
193
+ package: error((keypath) => `${keypath} has been removed — use @sveltejs/package instead`),
194
+
195
+ paths: object({
196
+ base: validate('', (input, keypath) => {
197
+ assert_string(input, keypath);
198
+
199
+ if (input !== '' && (input.endsWith('/') || !input.startsWith('/'))) {
200
+ throw new Error(
201
+ `${keypath} option must either be the empty string or a root-relative path that starts but doesn't end with '/'. See https://kit.svelte.dev/docs/configuration#paths`
202
+ );
203
+ }
204
+
205
+ return input;
206
+ }),
207
+ assets: validate('', (input, keypath) => {
208
+ assert_string(input, keypath);
209
+
210
+ if (input) {
211
+ if (!/^[a-z]+:\/\//.test(input)) {
212
+ throw new Error(
213
+ `${keypath} option must be an absolute path, if specified. See https://kit.svelte.dev/docs/configuration#paths`
214
+ );
215
+ }
216
+
217
+ if (input.endsWith('/')) {
218
+ throw new Error(
219
+ `${keypath} option must not end with '/'. See https://kit.svelte.dev/docs/configuration#paths`
220
+ );
221
+ }
222
+ }
223
+
224
+ return input;
225
+ })
226
+ }),
227
+
228
+ prerender: object({
229
+ concurrency: number(1),
230
+ crawl: boolean(true),
231
+ createIndexFiles: error(
232
+ (keypath) =>
233
+ `${keypath} has been removed — it is now controlled by the trailingSlash option. See https://kit.svelte.dev/docs/configuration#trailingslash`
234
+ ),
235
+ default: error(
236
+ (keypath) =>
237
+ `${keypath} has been removed. You can set it inside the top level +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197`
238
+ ),
239
+ enabled: boolean(true),
240
+ entries: validate(['*'], (input, keypath) => {
241
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
242
+ throw new Error(`${keypath} must be an array of strings`);
243
+ }
244
+
245
+ input.forEach((page) => {
246
+ if (page !== '*' && page[0] !== '/') {
247
+ throw new Error(
248
+ `Each member of ${keypath} must be either '*' or an absolute path beginning with '/' — saw '${page}'`
249
+ );
250
+ }
251
+ });
252
+
253
+ return input;
254
+ }),
255
+
256
+ // TODO: remove this for the 1.0 release
257
+ force: validate(undefined, (input, keypath) => {
258
+ if (typeof input !== 'undefined') {
259
+ const newSetting = input ? 'continue' : 'fail';
260
+ const needsSetting = newSetting === 'continue';
261
+ throw new Error(
262
+ `${keypath} has been removed in favor of \`onError\`. In your case, set \`onError\` to "${newSetting}"${
263
+ needsSetting ? '' : ' (or leave it undefined)'
264
+ } to get the same behavior as you would with \`force: ${JSON.stringify(input)}\``
265
+ );
266
+ }
267
+ }),
268
+
269
+ onError: validate('fail', (input, keypath) => {
270
+ if (typeof input === 'function') return input;
271
+ if (['continue', 'fail'].includes(input)) return input;
272
+ throw new Error(
273
+ `${keypath} should be either a custom function or one of "continue" or "fail"`
274
+ );
275
+ }),
276
+
277
+ origin: validate('http://sveltekit-prerender', (input, keypath) => {
278
+ assert_string(input, keypath);
279
+
280
+ let origin;
281
+
282
+ try {
283
+ origin = new URL(input).origin;
284
+ } catch (e) {
285
+ throw new Error(`${keypath} must be a valid origin`);
286
+ }
287
+
288
+ if (input !== origin) {
289
+ throw new Error(`${keypath} must be a valid origin (${origin} rather than ${input})`);
290
+ }
291
+
292
+ return origin;
293
+ }),
294
+
295
+ // TODO: remove this for the 1.0 release
296
+ pages: error((keypath) => `${keypath} has been renamed to \`entries\`.`)
297
+ }),
298
+
299
+ // TODO: remove this for the 1.0 release
300
+ protocol: error(
301
+ (keypath) =>
302
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
303
+ ),
304
+
305
+ // TODO remove for 1.0
306
+ router: error((keypath) => `${keypath} has been moved to config.kit.browser.router`),
307
+
308
+ // TODO remove for 1.0
309
+ routes: error(
310
+ (keypath) =>
311
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/discussions/5774 for details`
312
+ ),
313
+
314
+ serviceWorker: object({
315
+ register: boolean(true),
316
+ files: fun((filename) => !/\.DS_Store/.test(filename))
317
+ }),
318
+
319
+ // TODO remove this for 1.0
320
+ ssr: error(
321
+ (keypath) =>
322
+ `${keypath} has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle`
323
+ ),
324
+
325
+ // TODO remove this for 1.0
326
+ target: error((keypath) => `${keypath} is no longer required, and should be removed`),
327
+
328
+ trailingSlash: list(['never', 'always', 'ignore']),
329
+
330
+ version: object({
331
+ name: string(Date.now().toString()),
332
+ pollInterval: number(0)
333
+ }),
334
+
335
+ // TODO remove this for 1.0
336
+ vite: error((keypath) => `${keypath} has been removed — use vite.config.js instead`)
337
+ })
338
+ },
339
+ true
340
+ );
341
+
342
+ /**
343
+ * @param {Record<string, Validator>} children
344
+ * @param {boolean} [allow_unknown]
345
+ * @returns {Validator}
346
+ */
347
+ function object(children, allow_unknown = false) {
348
+ return (input, keypath) => {
349
+ /** @type {Record<string, any>} */
350
+ const output = {};
351
+
352
+ if ((input && typeof input !== 'object') || Array.isArray(input)) {
353
+ throw new Error(`${keypath} should be an object`);
354
+ }
355
+
356
+ for (const key in input) {
357
+ if (!(key in children)) {
358
+ if (allow_unknown) {
359
+ output[key] = input[key];
360
+ } else {
361
+ let message = `Unexpected option ${keypath}.${key}`;
362
+
363
+ // special case
364
+ if (keypath === 'config.kit' && key in options) {
365
+ message += ` (did you mean config.${key}?)`;
366
+ }
367
+
368
+ throw new Error(message);
369
+ }
370
+ }
371
+ }
372
+
373
+ for (const key in children) {
374
+ const validator = children[key];
375
+ output[key] = validator(input && input[key], `${keypath}.${key}`);
376
+ }
377
+
378
+ return output;
379
+ };
380
+ }
381
+
382
+ /**
383
+ * @param {any} fallback
384
+ * @param {(value: any, keypath: string) => any} fn
385
+ * @returns {Validator}
386
+ */
387
+ function validate(fallback, fn) {
388
+ return (input, keypath) => {
389
+ return input === undefined ? fallback : fn(input, keypath);
390
+ };
391
+ }
392
+
393
+ /**
394
+ * @param {string | null} fallback
395
+ * @param {boolean} allow_empty
396
+ * @returns {Validator}
397
+ */
398
+ function string(fallback, allow_empty = true) {
399
+ return validate(fallback, (input, keypath) => {
400
+ assert_string(input, keypath);
401
+
402
+ if (!allow_empty && input === '') {
403
+ throw new Error(`${keypath} cannot be empty`);
404
+ }
405
+
406
+ return input;
407
+ });
408
+ }
409
+
410
+ /**
411
+ * @param {string[] | undefined} [fallback]
412
+ * @returns {Validator}
413
+ */
414
+ function string_array(fallback) {
415
+ return validate(fallback, (input, keypath) => {
416
+ if (input === undefined) return input;
417
+
418
+ if (!Array.isArray(input) || input.some((value) => typeof value !== 'string')) {
419
+ throw new Error(`${keypath} must be an array of strings, if specified`);
420
+ }
421
+
422
+ return input;
423
+ });
424
+ }
425
+
426
+ /**
427
+ * @param {number} fallback
428
+ * @returns {Validator}
429
+ */
430
+ function number(fallback) {
431
+ return validate(fallback, (input, keypath) => {
432
+ if (typeof input !== 'number') {
433
+ throw new Error(`${keypath} should be a number, if specified`);
434
+ }
435
+ return input;
436
+ });
437
+ }
438
+
439
+ /**
440
+ * @param {boolean} fallback
441
+ * @returns {Validator}
442
+ */
443
+ function boolean(fallback) {
444
+ return validate(fallback, (input, keypath) => {
445
+ if (typeof input !== 'boolean') {
446
+ throw new Error(`${keypath} should be true or false, if specified`);
447
+ }
448
+ return input;
449
+ });
450
+ }
451
+
452
+ /**
453
+ * @param {string[]} options
454
+ * @returns {Validator}
455
+ */
456
+ function list(options, fallback = options[0]) {
457
+ return validate(fallback, (input, keypath) => {
458
+ if (!options.includes(input)) {
459
+ // prettier-ignore
460
+ const msg = options.length > 2
461
+ ? `${keypath} should be one of ${options.slice(0, -1).map(input => `"${input}"`).join(', ')} or "${options[options.length - 1]}"`
462
+ : `${keypath} should be either "${options[0]}" or "${options[1]}"`;
463
+
464
+ throw new Error(msg);
465
+ }
466
+ return input;
467
+ });
468
+ }
469
+
470
+ /**
471
+ * @param {(filename: string) => boolean} fallback
472
+ * @returns {Validator}
473
+ */
474
+ function fun(fallback) {
475
+ return validate(fallback, (input, keypath) => {
476
+ if (typeof input !== 'function') {
477
+ throw new Error(`${keypath} should be a function, if specified`);
478
+ }
479
+ return input;
480
+ });
481
+ }
482
+
483
+ /**
484
+ * @param {string} input
485
+ * @param {string} keypath
486
+ */
487
+ function assert_string(input, keypath) {
488
+ if (typeof input !== 'string') {
489
+ throw new Error(`${keypath} should be a string, if specified`);
490
+ }
491
+ }
492
+
493
+ /** @param {(keypath?: string) => string} fn */
494
+ function error(fn) {
495
+ return validate(undefined, (input, keypath) => {
496
+ if (input !== undefined) {
497
+ throw new Error(fn(keypath));
498
+ }
499
+ });
500
+ }
501
+
502
+ export default options;
@@ -0,0 +1 @@
1
+ export type Validator<T = any> = (input: T, keypath: string) => T;