@sveltejs/kit 1.0.0-next.5 → 1.0.0-next.500

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 (138) hide show
  1. package/README.md +12 -9
  2. package/package.json +94 -52
  3. package/postinstall.js +38 -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 +206 -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 +93 -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 +431 -0
  22. package/src/core/prerender/queue.js +80 -0
  23. package/src/core/sync/create_manifest_data/index.js +488 -0
  24. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  25. package/src/core/sync/sync.js +70 -0
  26. package/src/core/sync/utils.js +33 -0
  27. package/src/core/sync/write_ambient.js +53 -0
  28. package/src/core/sync/write_client_manifest.js +106 -0
  29. package/src/core/sync/write_matchers.js +25 -0
  30. package/src/core/sync/write_root.js +91 -0
  31. package/src/core/sync/write_tsconfig.js +195 -0
  32. package/src/core/sync/write_types/index.js +678 -0
  33. package/src/core/utils.js +70 -0
  34. package/src/exports/hooks/index.js +1 -0
  35. package/src/exports/hooks/sequence.js +44 -0
  36. package/src/exports/index.js +45 -0
  37. package/src/exports/node/index.js +173 -0
  38. package/src/exports/node/polyfills.js +41 -0
  39. package/src/exports/vite/build/build_server.js +378 -0
  40. package/src/exports/vite/build/build_service_worker.js +90 -0
  41. package/src/exports/vite/build/utils.js +180 -0
  42. package/src/exports/vite/dev/index.js +577 -0
  43. package/src/exports/vite/graph_analysis/index.js +277 -0
  44. package/src/exports/vite/graph_analysis/types.d.ts +5 -0
  45. package/src/exports/vite/graph_analysis/utils.js +30 -0
  46. package/src/exports/vite/index.js +598 -0
  47. package/src/exports/vite/preview/index.js +189 -0
  48. package/src/exports/vite/types.d.ts +3 -0
  49. package/src/exports/vite/utils.js +157 -0
  50. package/src/runtime/app/env.js +1 -0
  51. package/src/runtime/app/environment.js +11 -0
  52. package/src/runtime/app/forms.js +114 -0
  53. package/src/runtime/app/navigation.js +23 -0
  54. package/src/runtime/app/paths.js +1 -0
  55. package/src/runtime/app/stores.js +102 -0
  56. package/src/runtime/client/ambient.d.ts +26 -0
  57. package/src/runtime/client/client.js +1583 -0
  58. package/src/runtime/client/fetcher.js +107 -0
  59. package/src/runtime/client/parse.js +60 -0
  60. package/src/runtime/client/singletons.js +21 -0
  61. package/src/runtime/client/start.js +37 -0
  62. package/src/runtime/client/types.d.ts +84 -0
  63. package/src/runtime/client/utils.js +159 -0
  64. package/src/runtime/components/error.svelte +16 -0
  65. package/{assets → src/runtime}/components/layout.svelte +0 -0
  66. package/src/runtime/control.js +98 -0
  67. package/src/runtime/env/dynamic/private.js +1 -0
  68. package/src/runtime/env/dynamic/public.js +1 -0
  69. package/src/runtime/env-private.js +6 -0
  70. package/src/runtime/env-public.js +6 -0
  71. package/src/runtime/env.js +6 -0
  72. package/src/runtime/hash.js +16 -0
  73. package/src/runtime/paths.js +11 -0
  74. package/src/runtime/server/cookie.js +127 -0
  75. package/src/runtime/server/data/index.js +136 -0
  76. package/src/runtime/server/endpoint.js +90 -0
  77. package/src/runtime/server/index.js +340 -0
  78. package/src/runtime/server/page/actions.js +243 -0
  79. package/src/runtime/server/page/crypto.js +239 -0
  80. package/src/runtime/server/page/csp.js +250 -0
  81. package/src/runtime/server/page/fetch.js +301 -0
  82. package/src/runtime/server/page/index.js +304 -0
  83. package/src/runtime/server/page/load_data.js +124 -0
  84. package/src/runtime/server/page/render.js +342 -0
  85. package/src/runtime/server/page/respond_with_error.js +104 -0
  86. package/src/runtime/server/page/serialize_data.js +87 -0
  87. package/src/runtime/server/page/types.d.ts +41 -0
  88. package/src/runtime/server/utils.js +179 -0
  89. package/src/utils/array.js +9 -0
  90. package/src/utils/error.js +22 -0
  91. package/src/utils/escape.js +46 -0
  92. package/src/utils/filesystem.js +137 -0
  93. package/src/utils/functions.js +16 -0
  94. package/src/utils/http.js +55 -0
  95. package/src/utils/misc.js +1 -0
  96. package/src/utils/routing.js +117 -0
  97. package/src/utils/unit_test.js +11 -0
  98. package/src/utils/url.js +142 -0
  99. package/svelte-kit.js +2 -0
  100. package/types/ambient.d.ts +426 -0
  101. package/types/index.d.ts +444 -0
  102. package/types/internal.d.ts +378 -0
  103. package/types/private.d.ts +224 -0
  104. package/CHANGELOG.md +0 -177
  105. package/assets/components/error.svelte +0 -13
  106. package/assets/runtime/app/navigation.js +0 -47
  107. package/assets/runtime/app/navigation.js.map +0 -1
  108. package/assets/runtime/app/stores.js +0 -78
  109. package/assets/runtime/app/stores.js.map +0 -1
  110. package/assets/runtime/internal/singletons.js +0 -10
  111. package/assets/runtime/internal/singletons.js.map +0 -1
  112. package/assets/runtime/internal/start.js +0 -517
  113. package/assets/runtime/internal/start.js.map +0 -1
  114. package/dist/api.js +0 -40
  115. package/dist/api.js.map +0 -1
  116. package/dist/cli.js +0 -128
  117. package/dist/cli.js.map +0 -1
  118. package/dist/create_app.js +0 -550
  119. package/dist/create_app.js.map +0 -1
  120. package/dist/index.js +0 -8331
  121. package/dist/index.js.map +0 -1
  122. package/dist/index2.js +0 -509
  123. package/dist/index2.js.map +0 -1
  124. package/dist/index3.js +0 -63
  125. package/dist/index3.js.map +0 -1
  126. package/dist/index4.js +0 -466
  127. package/dist/index4.js.map +0 -1
  128. package/dist/index5.js +0 -276
  129. package/dist/index5.js.map +0 -1
  130. package/dist/package.js +0 -235
  131. package/dist/package.js.map +0 -1
  132. package/dist/renderer.js +0 -2398
  133. package/dist/renderer.js.map +0 -1
  134. package/dist/standard.js +0 -101
  135. package/dist/standard.js.map +0 -1
  136. package/dist/utils.js +0 -58
  137. package/dist/utils.js.map +0 -1
  138. package/svelte-kit +0 -3
@@ -0,0 +1,179 @@
1
+ import { devalue } from 'devalue';
2
+ import { DATA_SUFFIX } from '../../constants.js';
3
+ import { negotiate } from '../../utils/http.js';
4
+ import { HttpError } from '../control.js';
5
+ import { add_cookies_to_headers } from './cookie.js';
6
+
7
+ /** @param {any} body */
8
+ export function is_pojo(body) {
9
+ if (typeof body !== 'object') return false;
10
+
11
+ if (body) {
12
+ if (body instanceof Uint8Array) return false;
13
+ if (body instanceof ReadableStream) return false;
14
+
15
+ // if body is a node Readable, throw an error
16
+ // TODO remove this for 1.0
17
+ if (body._readableState && typeof body.pipe === 'function') {
18
+ throw new Error('Node streams are no longer supported — use a ReadableStream instead');
19
+ }
20
+ }
21
+
22
+ return true;
23
+ }
24
+
25
+ // TODO: Remove for 1.0
26
+ /** @param {Record<string, any>} mod */
27
+ export function check_method_names(mod) {
28
+ ['get', 'post', 'put', 'patch', 'del'].forEach((m) => {
29
+ if (m in mod) {
30
+ const replacement = m === 'del' ? 'DELETE' : m.toUpperCase();
31
+ throw Error(
32
+ `Endpoint method "${m}" has changed to "${replacement}". See https://github.com/sveltejs/kit/discussions/5359 for more information.`
33
+ );
34
+ }
35
+ });
36
+ }
37
+
38
+ /** @type {import('types').SSRErrorPage} */
39
+ export const GENERIC_ERROR = {
40
+ id: '__error'
41
+ };
42
+
43
+ /**
44
+ * @param {Partial<Record<import('types').HttpMethod, any>>} mod
45
+ * @param {import('types').HttpMethod} method
46
+ */
47
+ export function method_not_allowed(mod, method) {
48
+ return new Response(`${method} method not allowed`, {
49
+ status: 405,
50
+ headers: {
51
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
52
+ // "The server must generate an Allow header field in a 405 status code response"
53
+ allow: allowed_methods(mod).join(', ')
54
+ }
55
+ });
56
+ }
57
+
58
+ /** @param {Partial<Record<import('types').HttpMethod, any>>} mod */
59
+ export function allowed_methods(mod) {
60
+ const allowed = [];
61
+
62
+ for (const method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) {
63
+ if (method in mod) allowed.push(method);
64
+ }
65
+
66
+ if (mod.GET || mod.HEAD) allowed.push('HEAD');
67
+
68
+ return allowed;
69
+ }
70
+
71
+ /** @param {any} data */
72
+ export function data_response(data) {
73
+ const headers = {
74
+ 'content-type': 'application/javascript',
75
+ 'cache-control': 'private, no-store'
76
+ };
77
+
78
+ try {
79
+ return new Response(`window.__sveltekit_data = ${devalue(data)}`, { headers });
80
+ } catch (e) {
81
+ const error = /** @type {any} */ (e);
82
+ const match = /\[(\d+)\]\.data\.(.+)/.exec(error.path);
83
+ const message = match ? `${error.message} (data.${match[2]})` : error.message;
84
+ return new Response(`throw new Error(${JSON.stringify(message)})`, { headers });
85
+ }
86
+ }
87
+
88
+ /**
89
+ * @template {'prerender' | 'ssr' | 'csr'} Option
90
+ * @template {Option extends 'prerender' ? import('types').PrerenderOption : boolean} Value
91
+ *
92
+ * @param {Array<import('types').SSRNode | undefined>} nodes
93
+ * @param {Option} option
94
+ *
95
+ * @returns {Value | undefined}
96
+ */
97
+ export function get_option(nodes, option) {
98
+ return nodes.reduce((value, node) => {
99
+ // TODO remove for 1.0
100
+ for (const thing of [node?.server, node?.shared]) {
101
+ if (thing && ('router' in thing || 'hydrate' in thing)) {
102
+ throw new Error(
103
+ '`export const hydrate` and `export const router` have been replaced with `export const csr`. See https://github.com/sveltejs/kit/pull/6446'
104
+ );
105
+ }
106
+ }
107
+
108
+ return /** @type {any} TypeScript's too dumb to understand this */ (
109
+ node?.shared?.[option] ?? node?.server?.[option] ?? value
110
+ );
111
+ }, /** @type {Value | undefined} */ (undefined));
112
+ }
113
+
114
+ /**
115
+ * Return as a response that renders the error.html
116
+ *
117
+ * @param {import('types').SSROptions} options
118
+ * @param {number} status
119
+ * @param {string} message
120
+ */
121
+ export function static_error_page(options, status, message) {
122
+ return new Response(options.error_template({ status, message }), {
123
+ headers: { 'content-type': 'text/html; charset=utf-8' },
124
+ status
125
+ });
126
+ }
127
+
128
+ /**
129
+ * @param {import('types').RequestEvent} event
130
+ * @param {import('types').SSROptions} options
131
+ * @param {Error | HttpError} error
132
+ */
133
+ export function handle_fatal_error(event, options, error) {
134
+ const status = error instanceof HttpError ? error.status : 500;
135
+ const body = handle_error_and_jsonify(event, options, error);
136
+
137
+ // ideally we'd use sec-fetch-dest instead, but Safari — quelle surprise — doesn't support it
138
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
139
+ 'application/json',
140
+ 'text/html'
141
+ ]);
142
+
143
+ if (event.url.pathname.endsWith(DATA_SUFFIX) || type === 'application/json') {
144
+ return new Response(JSON.stringify(body), {
145
+ status,
146
+ headers: { 'content-type': 'application/json; charset=utf-8' }
147
+ });
148
+ }
149
+
150
+ return static_error_page(options, status, body.message);
151
+ }
152
+
153
+ /**
154
+ * @param {import('types').RequestEvent} event
155
+ * @param {import('types').SSROptions} options
156
+ * @param {any} error
157
+ * @returns {App.Error}
158
+ */
159
+ export function handle_error_and_jsonify(event, options, error) {
160
+ if (error instanceof HttpError) {
161
+ return error.body;
162
+ } else {
163
+ return options.handle_error(error, event);
164
+ }
165
+ }
166
+
167
+ /**
168
+ * @param {number} status
169
+ * @param {string} location
170
+ * @param {import('./page/types.js').Cookie[]} [cookies]
171
+ */
172
+ export function redirect_response(status, location, cookies = []) {
173
+ const response = new Response(undefined, {
174
+ status,
175
+ headers: { location }
176
+ });
177
+ add_cookies_to_headers(response.headers, cookies);
178
+ return response;
179
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Removes nullish values from an array.
3
+ *
4
+ * @template T
5
+ * @param {Array<T>} arr
6
+ */
7
+ export function compact(arr) {
8
+ return arr.filter(/** @returns {val is NonNullable<T>} */ (val) => val != null);
9
+ }
@@ -0,0 +1,22 @@
1
+ import { HttpError, Redirect } from '../runtime/control.js';
2
+
3
+ /**
4
+ * @param {unknown} err
5
+ * @return {Error}
6
+ */
7
+ export function coalesce_to_error(err) {
8
+ return err instanceof Error ||
9
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
10
+ ? /** @type {Error} */ (err)
11
+ : new Error(JSON.stringify(err));
12
+ }
13
+
14
+ /**
15
+ * This is an identity function that exists to make TypeScript less
16
+ * paranoid about people throwing things that aren't errors, which
17
+ * frankly is not something we should care about
18
+ * @param {unknown} error
19
+ */
20
+ export function normalize_error(error) {
21
+ return /** @type {Redirect | HttpError | Error} */ (error);
22
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
3
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
4
+ * @type {Record<string, string>}
5
+ */
6
+ const escape_html_attr_dict = {
7
+ '&': '&amp;',
8
+ '"': '&quot;'
9
+ };
10
+
11
+ const escape_html_attr_regex = new RegExp(
12
+ // special characters
13
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
14
+ // high surrogate without paired low surrogate
15
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
16
+ // a valid surrogate pair, the only match with 2 code units
17
+ // we match it so that we can match unpaired low surrogates in the same pass
18
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
19
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
20
+ // unpaired low surrogate (see previous match)
21
+ '[\\udc00-\\udfff]',
22
+ 'g'
23
+ );
24
+
25
+ /**
26
+ * Formats a string to be used as an attribute's value in raw HTML.
27
+ *
28
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
29
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
30
+ *
31
+ * @param {string} str
32
+ * @returns {string} Escaped string surrounded by double-quotes.
33
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
34
+ */
35
+ export function escape_html_attr(str) {
36
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
37
+ if (match.length === 2) {
38
+ // valid surrogate pair
39
+ return match;
40
+ }
41
+
42
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
43
+ });
44
+
45
+ return `"${escaped_str}"`;
46
+ }
@@ -0,0 +1,137 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ /** @param {string} dir */
5
+ export function mkdirp(dir) {
6
+ try {
7
+ fs.mkdirSync(dir, { recursive: true });
8
+ } catch (/** @type {any} */ e) {
9
+ if (e.code === 'EEXIST') return;
10
+ throw e;
11
+ }
12
+ }
13
+
14
+ /** @param {string} path */
15
+ export function rimraf(path) {
16
+ fs.rmSync(path, { force: true, recursive: true });
17
+ }
18
+
19
+ /**
20
+ * @param {string} source
21
+ * @param {string} target
22
+ * @param {{
23
+ * filter?: (basename: string) => boolean;
24
+ * replace?: Record<string, string>;
25
+ * }} opts
26
+ */
27
+ export function copy(source, target, opts = {}) {
28
+ if (!fs.existsSync(source)) return [];
29
+
30
+ /** @type {string[]} */
31
+ const files = [];
32
+
33
+ const prefix = posixify(target) + '/';
34
+
35
+ const regex = opts.replace
36
+ ? new RegExp(`\\b(${Object.keys(opts.replace).join('|')})\\b`, 'g')
37
+ : null;
38
+
39
+ /**
40
+ * @param {string} from
41
+ * @param {string} to
42
+ */
43
+ function go(from, to) {
44
+ if (opts.filter && !opts.filter(path.basename(from))) return;
45
+
46
+ const stats = fs.statSync(from);
47
+
48
+ if (stats.isDirectory()) {
49
+ fs.readdirSync(from).forEach((file) => {
50
+ go(path.join(from, file), path.join(to, file));
51
+ });
52
+ } else {
53
+ mkdirp(path.dirname(to));
54
+
55
+ if (opts.replace) {
56
+ const data = fs.readFileSync(from, 'utf-8');
57
+ fs.writeFileSync(
58
+ to,
59
+ data.replace(
60
+ /** @type {RegExp} */ (regex),
61
+ (_match, key) => /** @type {Record<string, string>} */ (opts.replace)[key]
62
+ )
63
+ );
64
+ } else {
65
+ fs.copyFileSync(from, to);
66
+ }
67
+
68
+ files.push(to === target ? posixify(path.basename(to)) : posixify(to).replace(prefix, ''));
69
+ }
70
+ }
71
+
72
+ go(source, target);
73
+
74
+ return files;
75
+ }
76
+
77
+ /**
78
+ * Get a list of all files in a directory
79
+ * @param {string} cwd - the directory to walk
80
+ * @param {boolean} [dirs] - whether to include directories in the result
81
+ */
82
+ export function walk(cwd, dirs = false) {
83
+ /** @type {string[]} */
84
+ const all_files = [];
85
+
86
+ /** @param {string} dir */
87
+ function walk_dir(dir) {
88
+ const files = fs.readdirSync(path.join(cwd, dir));
89
+
90
+ for (const file of files) {
91
+ const joined = path.join(dir, file);
92
+ const stats = fs.statSync(path.join(cwd, joined));
93
+ if (stats.isDirectory()) {
94
+ if (dirs) all_files.push(joined);
95
+ walk_dir(joined);
96
+ } else {
97
+ all_files.push(joined);
98
+ }
99
+ }
100
+ }
101
+
102
+ return walk_dir(''), all_files;
103
+ }
104
+
105
+ /** @param {string} str */
106
+ export function posixify(str) {
107
+ return str.replace(/\\/g, '/');
108
+ }
109
+
110
+ /**
111
+ * Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js
112
+ * @param {string} entry
113
+ * @returns {string|null}
114
+ */
115
+ export function resolve_entry(entry) {
116
+ if (fs.existsSync(entry)) {
117
+ const stats = fs.statSync(entry);
118
+ if (stats.isDirectory()) {
119
+ return resolve_entry(path.join(entry, 'index'));
120
+ }
121
+
122
+ return entry;
123
+ } else {
124
+ const dir = path.dirname(entry);
125
+
126
+ if (fs.existsSync(dir)) {
127
+ const base = path.basename(entry);
128
+ const files = fs.readdirSync(dir);
129
+
130
+ const found = files.find((file) => file.replace(/\.[^.]+$/, '') === base);
131
+
132
+ if (found) return path.join(dir, found);
133
+ }
134
+ }
135
+
136
+ return null;
137
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @template T
3
+ * @param {() => T} fn
4
+ */
5
+ export function once(fn) {
6
+ let done = false;
7
+
8
+ /** @type T */
9
+ let result;
10
+
11
+ return () => {
12
+ if (done) return result;
13
+ done = true;
14
+ return (result = fn());
15
+ };
16
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Given an Accept header and a list of possible content types, pick
3
+ * the most suitable one to respond with
4
+ * @param {string} accept
5
+ * @param {string[]} types
6
+ */
7
+ export function negotiate(accept, types) {
8
+ /** @type {Array<{ type: string, subtype: string, q: number, i: number }>} */
9
+ const parts = [];
10
+
11
+ accept.split(',').forEach((str, i) => {
12
+ const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str);
13
+
14
+ // no match equals invalid header — ignore
15
+ if (match) {
16
+ const [, type, subtype, q = '1'] = match;
17
+ parts.push({ type, subtype, q: +q, i });
18
+ }
19
+ });
20
+
21
+ parts.sort((a, b) => {
22
+ if (a.q !== b.q) {
23
+ return b.q - a.q;
24
+ }
25
+
26
+ if ((a.subtype === '*') !== (b.subtype === '*')) {
27
+ return a.subtype === '*' ? 1 : -1;
28
+ }
29
+
30
+ if ((a.type === '*') !== (b.type === '*')) {
31
+ return a.type === '*' ? 1 : -1;
32
+ }
33
+
34
+ return a.i - b.i;
35
+ });
36
+
37
+ let accepted;
38
+ let min_priority = Infinity;
39
+
40
+ for (const mimetype of types) {
41
+ const [type, subtype] = mimetype.split('/');
42
+ const priority = parts.findIndex(
43
+ (part) =>
44
+ (part.type === type || part.type === '*') &&
45
+ (part.subtype === subtype || part.subtype === '*')
46
+ );
47
+
48
+ if (priority !== -1 && priority < min_priority) {
49
+ accepted = mimetype;
50
+ min_priority = priority;
51
+ }
52
+ }
53
+
54
+ return accepted;
55
+ }
@@ -0,0 +1 @@
1
+ export const s = JSON.stringify;
@@ -0,0 +1,117 @@
1
+ const param_pattern = /^(\.\.\.)?(\w+)(?:=(\w+))?$/;
2
+
3
+ /** @param {string} id */
4
+ export function parse_route_id(id) {
5
+ /** @type {string[]} */
6
+ const names = [];
7
+
8
+ /** @type {string[]} */
9
+ const types = [];
10
+
11
+ // `/foo` should get an optional trailing slash, `/foo.json` should not
12
+ // const add_trailing_slash = !/\.[a-z]+$/.test(key);
13
+ let add_trailing_slash = true;
14
+
15
+ const pattern =
16
+ id === ''
17
+ ? /^\/$/
18
+ : new RegExp(
19
+ `^${id
20
+ .split(/(?:\/|$)/)
21
+ .filter(affects_path)
22
+ .map((segment, i, segments) => {
23
+ const decoded_segment = decodeURIComponent(segment);
24
+ // special case — /[...rest]/ could contain zero segments
25
+ const match = /^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(decoded_segment);
26
+ if (match) {
27
+ names.push(match[1]);
28
+ types.push(match[2]);
29
+ return '(?:/(.*))?';
30
+ }
31
+
32
+ const is_last = i === segments.length - 1;
33
+
34
+ return (
35
+ decoded_segment &&
36
+ '/' +
37
+ decoded_segment
38
+ .split(/\[(.+?)\]/)
39
+ .map((content, i) => {
40
+ if (i % 2) {
41
+ const match = param_pattern.exec(content);
42
+ if (!match) {
43
+ throw new Error(
44
+ `Invalid param: ${content}. Params and matcher names can only have underscores and alphanumeric characters.`
45
+ );
46
+ }
47
+
48
+ const [, rest, name, type] = match;
49
+ names.push(name);
50
+ types.push(type);
51
+ return rest ? '(.*?)' : '([^/]+?)';
52
+ }
53
+
54
+ if (is_last && content.includes('.')) add_trailing_slash = false;
55
+
56
+ return (
57
+ content // allow users to specify characters on the file system in an encoded manner
58
+ .normalize()
59
+ // We use [ and ] to denote parameters, so users must encode these on the file
60
+ // system to match against them. We don't decode all characters since others
61
+ // can already be epressed and so that '%' can be easily used directly in filenames
62
+ .replace(/%5[Bb]/g, '[')
63
+ .replace(/%5[Dd]/g, ']')
64
+ // '#', '/', and '?' can only appear in URL path segments in an encoded manner.
65
+ // They will not be touched by decodeURI so need to be encoded here, so
66
+ // that we can match against them.
67
+ // We skip '/' since you can't create a file with it on any OS
68
+ .replace(/#/g, '%23')
69
+ .replace(/\?/g, '%3F')
70
+ // escape characters that have special meaning in regex
71
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
72
+ ); // TODO handle encoding
73
+ })
74
+ .join('')
75
+ );
76
+ })
77
+ .join('')}${add_trailing_slash ? '/?' : ''}$`
78
+ );
79
+
80
+ return { pattern, names, types };
81
+ }
82
+
83
+ /**
84
+ * Returns `false` for `(group)` segments
85
+ * @param {string} segment
86
+ */
87
+ export function affects_path(segment) {
88
+ return !/^\([^)]+\)$/.test(segment);
89
+ }
90
+
91
+ /**
92
+ * @param {RegExpMatchArray} match
93
+ * @param {string[]} names
94
+ * @param {string[]} types
95
+ * @param {Record<string, import('types').ParamMatcher>} matchers
96
+ */
97
+ export function exec(match, names, types, matchers) {
98
+ /** @type {Record<string, string>} */
99
+ const params = {};
100
+
101
+ for (let i = 0; i < names.length; i += 1) {
102
+ const name = names[i];
103
+ const type = types[i];
104
+ const value = match[i + 1] || '';
105
+
106
+ if (type) {
107
+ const matcher = matchers[type];
108
+ if (!matcher) throw new Error(`Missing "${type}" param matcher`); // TODO do this ahead of time?
109
+
110
+ if (!matcher(value)) return;
111
+ }
112
+
113
+ params[name] = value;
114
+ }
115
+
116
+ return params;
117
+ }
@@ -0,0 +1,11 @@
1
+ import { suite } from 'uvu';
2
+
3
+ /**
4
+ * @param {string} name
5
+ * @param {(suite: import('uvu').Test<import('uvu').Context>) => void} fn
6
+ */
7
+ export function describe(name, fn) {
8
+ const s = suite(name);
9
+ fn(s);
10
+ s.run();
11
+ }