@sveltejs/kit 1.0.0-next.46 → 1.0.0-next.460

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 -65
  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 +498 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +112 -0
  17. package/src/core/generate_manifest/index.js +78 -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 +452 -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 +349 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +160 -0
  40. package/src/exports/vite/dev/index.js +543 -0
  41. package/src/exports/vite/index.js +595 -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 +22 -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 +1387 -0
  52. package/src/runtime/client/fetcher.js +60 -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 +88 -0
  57. package/src/runtime/client/utils.js +140 -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 +339 -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 +269 -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 +58 -0
  80. package/src/runtime/server/page/types.d.ts +44 -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 +137 -0
  90. package/src/utils/url.js +142 -0
  91. package/svelte-kit.js +1 -1
  92. package/types/ambient.d.ts +332 -0
  93. package/types/index.d.ts +343 -0
  94. package/types/internal.d.ts +383 -0
  95. package/types/private.d.ts +213 -0
  96. package/CHANGELOG.md +0 -456
  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 -771
  105. package/assets/runtime/paths.js +0 -12
  106. package/dist/chunks/index.js +0 -3522
  107. package/dist/chunks/index2.js +0 -587
  108. package/dist/chunks/index3.js +0 -246
  109. package/dist/chunks/index4.js +0 -539
  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 -546
  115. package/dist/ssr.js +0 -2581
@@ -0,0 +1,63 @@
1
+ import { Redirect } from '../control.js';
2
+ import { check_method_names, method_not_allowed } from './utils.js';
3
+
4
+ /**
5
+ * @param {import('types').RequestEvent} event
6
+ * @param {import('types').SSREndpoint} mod
7
+ * @param {import('types').SSRState} state
8
+ * @returns {Promise<Response>}
9
+ */
10
+ export async function render_endpoint(event, mod, state) {
11
+ const method = /** @type {import('types').HttpMethod} */ (event.request.method);
12
+
13
+ // TODO: Remove for 1.0
14
+ check_method_names(mod);
15
+
16
+ let handler = mod[method];
17
+
18
+ if (!handler && method === 'HEAD') {
19
+ handler = mod.GET;
20
+ }
21
+
22
+ if (!handler) {
23
+ return method_not_allowed(mod, method);
24
+ }
25
+
26
+ const prerender = mod.prerender ?? state.prerender_default;
27
+
28
+ if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) {
29
+ throw new Error('Cannot prerender endpoints that have mutative methods');
30
+ }
31
+
32
+ if (state.prerendering && !prerender) {
33
+ throw new Error(`${event.routeId} is not prerenderable`);
34
+ }
35
+
36
+ try {
37
+ const response = await handler(
38
+ /** @type {import('types').RequestEvent<Record<string, any>>} */ (event)
39
+ );
40
+
41
+ if (!(response instanceof Response)) {
42
+ throw new Error(
43
+ `Invalid response from route ${event.url.pathname}: handler should return a Response object`
44
+ );
45
+ }
46
+
47
+ if (state.prerendering) {
48
+ response.headers.set('x-sveltekit-routeid', /** @type {string} */ (event.routeId));
49
+ response.headers.set('x-sveltekit-prerender', String(prerender));
50
+ }
51
+
52
+ return response;
53
+ } catch (error) {
54
+ if (error instanceof Redirect) {
55
+ return new Response(undefined, {
56
+ status: error.status,
57
+ headers: { location: error.location }
58
+ });
59
+ }
60
+
61
+ throw error;
62
+ }
63
+ }
@@ -0,0 +1,339 @@
1
+ import { render_endpoint } from './endpoint.js';
2
+ import { render_page } from './page/index.js';
3
+ import { render_response } from './page/render.js';
4
+ import { respond_with_error } from './page/respond_with_error.js';
5
+ import { coalesce_to_error } from '../../utils/error.js';
6
+ import { GENERIC_ERROR, handle_fatal_error } from './utils.js';
7
+ import { decode_params, disable_search, normalize_path } from '../../utils/url.js';
8
+ import { exec } from '../../utils/routing.js';
9
+ import { render_data } from './data/index.js';
10
+ import { DATA_SUFFIX } from '../../constants.js';
11
+
12
+ /* global __SVELTEKIT_ADAPTER_NAME__ */
13
+
14
+ /** @param {{ html: string }} opts */
15
+ const default_transform = ({ html }) => html;
16
+
17
+ /** @type {import('types').Respond} */
18
+ export async function respond(request, options, state) {
19
+ let url = new URL(request.url);
20
+
21
+ const { parameter, allowed } = options.method_override;
22
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
23
+
24
+ if (method_override) {
25
+ if (request.method === 'POST') {
26
+ if (allowed.includes(method_override)) {
27
+ request = new Proxy(request, {
28
+ get: (target, property, _receiver) => {
29
+ if (property === 'method') return method_override;
30
+ return Reflect.get(target, property, target);
31
+ }
32
+ });
33
+ } else {
34
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
35
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs/configuration#methodoverride`;
36
+
37
+ return new Response(body, {
38
+ status: 400
39
+ });
40
+ }
41
+ } else {
42
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
43
+ }
44
+ }
45
+
46
+ let decoded;
47
+ try {
48
+ decoded = decodeURI(url.pathname);
49
+ } catch {
50
+ return new Response('Malformed URI', { status: 400 });
51
+ }
52
+
53
+ /** @type {import('types').SSRRoute | null} */
54
+ let route = null;
55
+
56
+ /** @type {Record<string, string>} */
57
+ let params = {};
58
+
59
+ if (options.paths.base && !state.prerendering?.fallback) {
60
+ if (!decoded.startsWith(options.paths.base)) {
61
+ return new Response('Not found', { status: 404 });
62
+ }
63
+ decoded = decoded.slice(options.paths.base.length) || '/';
64
+ }
65
+
66
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
67
+ if (is_data_request) decoded = decoded.slice(0, -DATA_SUFFIX.length) || '/';
68
+
69
+ if (!state.prerendering?.fallback) {
70
+ const matchers = await options.manifest._.matchers();
71
+
72
+ for (const candidate of options.manifest._.routes) {
73
+ const match = candidate.pattern.exec(decoded);
74
+ if (!match) continue;
75
+
76
+ const matched = exec(match, candidate.names, candidate.types, matchers);
77
+ if (matched) {
78
+ route = candidate;
79
+ params = decode_params(matched);
80
+ break;
81
+ }
82
+ }
83
+ }
84
+
85
+ if (route?.page && !is_data_request) {
86
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
87
+
88
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
89
+ return new Response(undefined, {
90
+ status: 301,
91
+ headers: {
92
+ 'x-sveltekit-normalize': '1',
93
+ location:
94
+ // ensure paths starting with '//' are not treated as protocol-relative
95
+ (normalized.startsWith('//') ? url.origin + normalized : normalized) +
96
+ (url.search === '?' ? '' : url.search)
97
+ }
98
+ });
99
+ }
100
+ }
101
+
102
+ /** @type {import('types').ResponseHeaders} */
103
+ const headers = {};
104
+
105
+ /** @type {string[]} */
106
+ const cookies = [];
107
+
108
+ if (state.prerendering) disable_search(url);
109
+
110
+ /** @type {import('types').RequestEvent} */
111
+ const event = {
112
+ getClientAddress:
113
+ state.getClientAddress ||
114
+ (() => {
115
+ throw new Error(
116
+ `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue`
117
+ );
118
+ }),
119
+ locals: {},
120
+ params,
121
+ platform: state.platform,
122
+ request,
123
+ routeId: route && route.id,
124
+ setHeaders: (new_headers) => {
125
+ for (const key in new_headers) {
126
+ const lower = key.toLowerCase();
127
+ const value = new_headers[key];
128
+
129
+ if (lower === 'set-cookie') {
130
+ const new_cookies = /** @type {string[]} */ (Array.isArray(value) ? value : [value]);
131
+
132
+ for (const cookie of new_cookies) {
133
+ if (cookies.includes(cookie)) {
134
+ throw new Error(`"${key}" header already has cookie with same value`);
135
+ }
136
+
137
+ cookies.push(cookie);
138
+ }
139
+ } else if (lower in headers) {
140
+ throw new Error(`"${key}" header is already set`);
141
+ } else {
142
+ headers[lower] = value;
143
+
144
+ if (state.prerendering && lower === 'cache-control') {
145
+ state.prerendering.cache = /** @type {string} */ (value);
146
+ }
147
+ }
148
+ }
149
+ },
150
+ url
151
+ };
152
+
153
+ // TODO remove this for 1.0
154
+ /**
155
+ * @param {string} property
156
+ * @param {string} replacement
157
+ * @param {string} suffix
158
+ */
159
+ const removed = (property, replacement, suffix = '') => ({
160
+ get: () => {
161
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
162
+ }
163
+ });
164
+
165
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
166
+
167
+ const body_getter = {
168
+ get: () => {
169
+ throw new Error(
170
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
171
+ details
172
+ );
173
+ }
174
+ };
175
+
176
+ Object.defineProperties(event, {
177
+ clientAddress: removed('clientAddress', 'getClientAddress'),
178
+ method: removed('method', 'request.method', details),
179
+ headers: removed('headers', 'request.headers', details),
180
+ origin: removed('origin', 'url.origin'),
181
+ path: removed('path', 'url.pathname'),
182
+ query: removed('query', 'url.searchParams'),
183
+ body: body_getter,
184
+ rawBody: body_getter
185
+ });
186
+
187
+ /** @type {import('types').RequiredResolveOptions} */
188
+ let resolve_opts = {
189
+ transformPageChunk: default_transform
190
+ };
191
+
192
+ /**
193
+ *
194
+ * @param {import('types').RequestEvent} event
195
+ * @param {import('types').ResolveOptions} [opts]
196
+ */
197
+ async function resolve(event, opts) {
198
+ try {
199
+ if (opts) {
200
+ // TODO remove for 1.0
201
+ if ('transformPage' in opts) {
202
+ throw new Error(
203
+ 'transformPage has been replaced by transformPageChunk — see https://github.com/sveltejs/kit/pull/5657 for more information'
204
+ );
205
+ }
206
+
207
+ if ('ssr' in opts) {
208
+ throw new Error(
209
+ 'ssr has been removed, set it in the appropriate +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197'
210
+ );
211
+ }
212
+
213
+ resolve_opts = {
214
+ transformPageChunk: opts.transformPageChunk || default_transform
215
+ };
216
+ }
217
+
218
+ if (state.prerendering?.fallback) {
219
+ return await render_response({
220
+ event,
221
+ options,
222
+ state,
223
+ page_config: { ssr: false, csr: true },
224
+ status: 200,
225
+ error: null,
226
+ branch: [],
227
+ fetched: [],
228
+ validation_errors: undefined,
229
+ cookies: [],
230
+ resolve_opts
231
+ });
232
+ }
233
+
234
+ if (route) {
235
+ /** @type {Response} */
236
+ let response;
237
+
238
+ if (is_data_request) {
239
+ response = await render_data(event, route, options, state);
240
+ } else if (route.page) {
241
+ response = await render_page(event, route, route.page, options, state, resolve_opts);
242
+ } else if (route.endpoint) {
243
+ response = await render_endpoint(event, await route.endpoint(), state);
244
+ } else {
245
+ // a route will always have a page or an endpoint, but TypeScript
246
+ // doesn't know that
247
+ throw new Error('This should never happen');
248
+ }
249
+
250
+ if (!is_data_request) {
251
+ // we only want to set cookies on __data.js requests, we don't
252
+ // want to cache stuff erroneously etc
253
+ for (const key in headers) {
254
+ const value = headers[key];
255
+ response.headers.set(key, /** @type {string} */ (value));
256
+ }
257
+ }
258
+
259
+ for (const cookie of cookies) {
260
+ response.headers.append('set-cookie', cookie);
261
+ }
262
+
263
+ // respond with 304 if etag matches
264
+ if (response.status === 200 && response.headers.has('etag')) {
265
+ let if_none_match_value = request.headers.get('if-none-match');
266
+
267
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
268
+ if (if_none_match_value?.startsWith('W/"')) {
269
+ if_none_match_value = if_none_match_value.substring(2);
270
+ }
271
+
272
+ const etag = /** @type {string} */ (response.headers.get('etag'));
273
+
274
+ if (if_none_match_value === etag) {
275
+ const headers = new Headers({ etag });
276
+
277
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
278
+ for (const key of ['cache-control', 'content-location', 'date', 'expires', 'vary']) {
279
+ const value = response.headers.get(key);
280
+ if (value) headers.set(key, value);
281
+ }
282
+
283
+ return new Response(undefined, {
284
+ status: 304,
285
+ headers
286
+ });
287
+ }
288
+ }
289
+
290
+ return response;
291
+ }
292
+
293
+ if (state.initiator === GENERIC_ERROR) {
294
+ return new Response('Internal Server Error', {
295
+ status: 500
296
+ });
297
+ }
298
+
299
+ // if this request came direct from the user, rather than
300
+ // via a `fetch` in a `load`, render a 404 page
301
+ if (!state.initiator) {
302
+ return await respond_with_error({
303
+ event,
304
+ options,
305
+ state,
306
+ status: 404,
307
+ error: new Error(`Not found: ${event.url.pathname}`),
308
+ resolve_opts
309
+ });
310
+ }
311
+
312
+ if (state.prerendering) {
313
+ return new Response('not found', { status: 404 });
314
+ }
315
+
316
+ // we can't load the endpoint from our own manifest,
317
+ // so we need to make an actual HTTP request
318
+ return await fetch(request);
319
+ } catch (e) {
320
+ const error = coalesce_to_error(e);
321
+ return handle_fatal_error(event, options, error);
322
+ }
323
+ }
324
+
325
+ try {
326
+ return await options.hooks.handle({
327
+ event,
328
+ resolve,
329
+ // TODO remove for 1.0
330
+ // @ts-expect-error
331
+ get request() {
332
+ throw new Error('request in handle has been replaced with event' + details);
333
+ }
334
+ });
335
+ } catch (/** @type {unknown} */ e) {
336
+ const error = coalesce_to_error(e);
337
+ return handle_fatal_error(event, options, error);
338
+ }
339
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @param {string} hostname
3
+ * @param {string} [constraint]
4
+ */
5
+ export function domain_matches(hostname, constraint) {
6
+ if (!constraint) return true;
7
+
8
+ const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;
9
+
10
+ if (hostname === normalized) return true;
11
+ return hostname.endsWith('.' + normalized);
12
+ }
13
+
14
+ /**
15
+ * @param {string} path
16
+ * @param {string} [constraint]
17
+ */
18
+ export function path_matches(path, constraint) {
19
+ if (!constraint) return true;
20
+
21
+ const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;
22
+
23
+ if (path === normalized) return true;
24
+ return path.startsWith(normalized + '/');
25
+ }
@@ -0,0 +1,239 @@
1
+ const encoder = new TextEncoder();
2
+
3
+ /**
4
+ * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl
5
+ * modified and redistributed under BSD license
6
+ * @param {string} data
7
+ */
8
+ export function sha256(data) {
9
+ if (!key[0]) precompute();
10
+
11
+ const out = init.slice(0);
12
+ const array = encode(data);
13
+
14
+ for (let i = 0; i < array.length; i += 16) {
15
+ const w = array.subarray(i, i + 16);
16
+
17
+ let tmp;
18
+ let a;
19
+ let b;
20
+
21
+ let out0 = out[0];
22
+ let out1 = out[1];
23
+ let out2 = out[2];
24
+ let out3 = out[3];
25
+ let out4 = out[4];
26
+ let out5 = out[5];
27
+ let out6 = out[6];
28
+ let out7 = out[7];
29
+
30
+ /* Rationale for placement of |0 :
31
+ * If a value can overflow is original 32 bits by a factor of more than a few
32
+ * million (2^23 ish), there is a possibility that it might overflow the
33
+ * 53-bit mantissa and lose precision.
34
+ *
35
+ * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
36
+ * propagates around the loop, and on the hash state out[]. I don't believe
37
+ * that the clamps on out4 and on out0 are strictly necessary, but it's close
38
+ * (for out4 anyway), and better safe than sorry.
39
+ *
40
+ * The clamps on out[] are necessary for the output to be correct even in the
41
+ * common case and for short inputs.
42
+ */
43
+
44
+ for (let i = 0; i < 64; i++) {
45
+ // load up the input word for this round
46
+
47
+ if (i < 16) {
48
+ tmp = w[i];
49
+ } else {
50
+ a = w[(i + 1) & 15];
51
+
52
+ b = w[(i + 14) & 15];
53
+
54
+ tmp = w[i & 15] =
55
+ (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) +
56
+ ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) +
57
+ w[i & 15] +
58
+ w[(i + 9) & 15]) |
59
+ 0;
60
+ }
61
+
62
+ tmp =
63
+ tmp +
64
+ out7 +
65
+ ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) +
66
+ (out6 ^ (out4 & (out5 ^ out6))) +
67
+ key[i]; // | 0;
68
+
69
+ // shift register
70
+ out7 = out6;
71
+ out6 = out5;
72
+ out5 = out4;
73
+
74
+ out4 = (out3 + tmp) | 0;
75
+
76
+ out3 = out2;
77
+ out2 = out1;
78
+ out1 = out0;
79
+
80
+ out0 =
81
+ (tmp +
82
+ ((out1 & out2) ^ (out3 & (out1 ^ out2))) +
83
+ ((out1 >>> 2) ^
84
+ (out1 >>> 13) ^
85
+ (out1 >>> 22) ^
86
+ (out1 << 30) ^
87
+ (out1 << 19) ^
88
+ (out1 << 10))) |
89
+ 0;
90
+ }
91
+
92
+ out[0] = (out[0] + out0) | 0;
93
+ out[1] = (out[1] + out1) | 0;
94
+ out[2] = (out[2] + out2) | 0;
95
+ out[3] = (out[3] + out3) | 0;
96
+ out[4] = (out[4] + out4) | 0;
97
+ out[5] = (out[5] + out5) | 0;
98
+ out[6] = (out[6] + out6) | 0;
99
+ out[7] = (out[7] + out7) | 0;
100
+ }
101
+
102
+ const bytes = new Uint8Array(out.buffer);
103
+ reverse_endianness(bytes);
104
+
105
+ return base64(bytes);
106
+ }
107
+
108
+ /** The SHA-256 initialization vector */
109
+ const init = new Uint32Array(8);
110
+
111
+ /** The SHA-256 hash key */
112
+ const key = new Uint32Array(64);
113
+
114
+ /** Function to precompute init and key. */
115
+ function precompute() {
116
+ /** @param {number} x */
117
+ function frac(x) {
118
+ return (x - Math.floor(x)) * 0x100000000;
119
+ }
120
+
121
+ let prime = 2;
122
+
123
+ for (let i = 0; i < 64; prime++) {
124
+ let is_prime = true;
125
+
126
+ for (let factor = 2; factor * factor <= prime; factor++) {
127
+ if (prime % factor === 0) {
128
+ is_prime = false;
129
+
130
+ break;
131
+ }
132
+ }
133
+
134
+ if (is_prime) {
135
+ if (i < 8) {
136
+ init[i] = frac(prime ** (1 / 2));
137
+ }
138
+
139
+ key[i] = frac(prime ** (1 / 3));
140
+
141
+ i++;
142
+ }
143
+ }
144
+ }
145
+
146
+ /** @param {Uint8Array} bytes */
147
+ function reverse_endianness(bytes) {
148
+ for (let i = 0; i < bytes.length; i += 4) {
149
+ const a = bytes[i + 0];
150
+ const b = bytes[i + 1];
151
+ const c = bytes[i + 2];
152
+ const d = bytes[i + 3];
153
+
154
+ bytes[i + 0] = d;
155
+ bytes[i + 1] = c;
156
+ bytes[i + 2] = b;
157
+ bytes[i + 3] = a;
158
+ }
159
+ }
160
+
161
+ /** @param {string} str */
162
+ function encode(str) {
163
+ const encoded = encoder.encode(str);
164
+ const length = encoded.length * 8;
165
+
166
+ // result should be a multiple of 512 bits in length,
167
+ // with room for a 1 (after the data) and two 32-bit
168
+ // words containing the original input bit length
169
+ const size = 512 * Math.ceil((length + 65) / 512);
170
+ const bytes = new Uint8Array(size / 8);
171
+ bytes.set(encoded);
172
+
173
+ // append a 1
174
+ bytes[encoded.length] = 0b10000000;
175
+
176
+ reverse_endianness(bytes);
177
+
178
+ // add the input bit length
179
+ const words = new Uint32Array(bytes.buffer);
180
+ words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us
181
+ words[words.length - 1] = length;
182
+
183
+ return words;
184
+ }
185
+
186
+ /*
187
+ Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
188
+
189
+ MIT License
190
+ Copyright (c) 2020 Egor Nepomnyaschih
191
+ Permission is hereby granted, free of charge, to any person obtaining a copy
192
+ of this software and associated documentation files (the "Software"), to deal
193
+ in the Software without restriction, including without limitation the rights
194
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
195
+ copies of the Software, and to permit persons to whom the Software is
196
+ furnished to do so, subject to the following conditions:
197
+ The above copyright notice and this permission notice shall be included in all
198
+ copies or substantial portions of the Software.
199
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
200
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
201
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
202
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
203
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
204
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
205
+ SOFTWARE.
206
+ */
207
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
208
+
209
+ /** @param {Uint8Array} bytes */
210
+ export function base64(bytes) {
211
+ const l = bytes.length;
212
+
213
+ let result = '';
214
+ let i;
215
+
216
+ for (i = 2; i < l; i += 3) {
217
+ result += chars[bytes[i - 2] >> 2];
218
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
219
+ result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)];
220
+ result += chars[bytes[i] & 0x3f];
221
+ }
222
+
223
+ if (i === l + 1) {
224
+ // 1 octet yet to write
225
+ result += chars[bytes[i - 2] >> 2];
226
+ result += chars[(bytes[i - 2] & 0x03) << 4];
227
+ result += '==';
228
+ }
229
+
230
+ if (i === l) {
231
+ // 2 octets yet to write
232
+ result += chars[bytes[i - 2] >> 2];
233
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
234
+ result += chars[(bytes[i - 1] & 0x0f) << 2];
235
+ result += '=';
236
+ }
237
+
238
+ return result;
239
+ }