@sveltejs/kit 1.0.0-next.45 → 1.0.0-next.450

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 (108) hide show
  1. package/README.md +12 -9
  2. package/package.json +92 -63
  3. package/src/cli.js +112 -0
  4. package/src/constants.js +7 -0
  5. package/src/core/adapt/builder.js +223 -0
  6. package/src/core/adapt/index.js +19 -0
  7. package/src/core/config/index.js +86 -0
  8. package/src/core/config/options.js +488 -0
  9. package/src/core/config/types.d.ts +1 -0
  10. package/src/core/env.js +97 -0
  11. package/src/core/generate_manifest/index.js +78 -0
  12. package/src/core/prerender/crawl.js +194 -0
  13. package/src/core/prerender/prerender.js +380 -0
  14. package/src/core/prerender/queue.js +80 -0
  15. package/src/core/sync/create_manifest_data/index.js +452 -0
  16. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  17. package/src/core/sync/sync.js +59 -0
  18. package/src/core/sync/utils.js +33 -0
  19. package/src/core/sync/write_ambient.js +27 -0
  20. package/src/core/sync/write_client_manifest.js +94 -0
  21. package/src/core/sync/write_matchers.js +25 -0
  22. package/src/core/sync/write_root.js +91 -0
  23. package/src/core/sync/write_tsconfig.js +195 -0
  24. package/src/core/sync/write_types/index.js +596 -0
  25. package/src/core/utils.js +70 -0
  26. package/src/exports/hooks/index.js +1 -0
  27. package/src/exports/hooks/sequence.js +26 -0
  28. package/src/exports/index.js +45 -0
  29. package/src/exports/node/index.js +145 -0
  30. package/src/exports/node/polyfills.js +40 -0
  31. package/src/exports/vite/build/build_server.js +348 -0
  32. package/src/exports/vite/build/build_service_worker.js +90 -0
  33. package/src/exports/vite/build/utils.js +160 -0
  34. package/src/exports/vite/dev/index.js +543 -0
  35. package/src/exports/vite/index.js +588 -0
  36. package/src/exports/vite/preview/index.js +186 -0
  37. package/src/exports/vite/types.d.ts +3 -0
  38. package/src/exports/vite/utils.js +345 -0
  39. package/src/runtime/app/env.js +1 -0
  40. package/src/runtime/app/environment.js +11 -0
  41. package/src/runtime/app/navigation.js +22 -0
  42. package/src/runtime/app/paths.js +1 -0
  43. package/src/runtime/app/stores.js +102 -0
  44. package/src/runtime/client/ambient.d.ts +24 -0
  45. package/src/runtime/client/client.js +1394 -0
  46. package/src/runtime/client/fetcher.js +60 -0
  47. package/src/runtime/client/parse.js +60 -0
  48. package/src/runtime/client/singletons.js +21 -0
  49. package/src/runtime/client/start.js +48 -0
  50. package/src/runtime/client/types.d.ts +88 -0
  51. package/src/runtime/client/utils.js +113 -0
  52. package/src/runtime/components/error.svelte +16 -0
  53. package/{assets → src/runtime}/components/layout.svelte +0 -0
  54. package/src/runtime/control.js +33 -0
  55. package/src/runtime/env/dynamic/private.js +1 -0
  56. package/src/runtime/env/dynamic/public.js +1 -0
  57. package/src/runtime/env-private.js +7 -0
  58. package/src/runtime/env-public.js +7 -0
  59. package/src/runtime/env.js +6 -0
  60. package/src/runtime/hash.js +16 -0
  61. package/src/runtime/paths.js +11 -0
  62. package/src/runtime/server/data/index.js +146 -0
  63. package/src/runtime/server/endpoint.js +50 -0
  64. package/src/runtime/server/index.js +369 -0
  65. package/src/runtime/server/page/cookie.js +25 -0
  66. package/src/runtime/server/page/crypto.js +239 -0
  67. package/src/runtime/server/page/csp.js +249 -0
  68. package/src/runtime/server/page/fetch.js +266 -0
  69. package/src/runtime/server/page/index.js +413 -0
  70. package/src/runtime/server/page/load_data.js +124 -0
  71. package/src/runtime/server/page/render.js +379 -0
  72. package/src/runtime/server/page/respond_with_error.js +94 -0
  73. package/src/runtime/server/page/types.d.ts +44 -0
  74. package/src/runtime/server/utils.js +137 -0
  75. package/src/utils/array.js +9 -0
  76. package/src/utils/error.js +22 -0
  77. package/src/utils/escape.js +104 -0
  78. package/src/utils/filesystem.js +108 -0
  79. package/src/utils/functions.js +16 -0
  80. package/src/utils/http.js +55 -0
  81. package/src/utils/misc.js +1 -0
  82. package/src/utils/routing.js +146 -0
  83. package/src/utils/url.js +142 -0
  84. package/svelte-kit.js +1 -1
  85. package/types/ambient.d.ts +366 -0
  86. package/types/index.d.ts +345 -0
  87. package/types/internal.d.ts +379 -0
  88. package/types/private.d.ts +209 -0
  89. package/CHANGELOG.md +0 -450
  90. package/assets/components/error.svelte +0 -13
  91. package/assets/runtime/app/env.js +0 -5
  92. package/assets/runtime/app/navigation.js +0 -41
  93. package/assets/runtime/app/paths.js +0 -1
  94. package/assets/runtime/app/stores.js +0 -93
  95. package/assets/runtime/chunks/utils.js +0 -19
  96. package/assets/runtime/internal/singletons.js +0 -23
  97. package/assets/runtime/internal/start.js +0 -770
  98. package/assets/runtime/paths.js +0 -12
  99. package/dist/chunks/index.js +0 -3521
  100. package/dist/chunks/index2.js +0 -587
  101. package/dist/chunks/index3.js +0 -246
  102. package/dist/chunks/index4.js +0 -536
  103. package/dist/chunks/index5.js +0 -761
  104. package/dist/chunks/index6.js +0 -322
  105. package/dist/chunks/standard.js +0 -99
  106. package/dist/chunks/utils.js +0 -83
  107. package/dist/cli.js +0 -546
  108. package/dist/ssr.js +0 -2580
@@ -0,0 +1,50 @@
1
+ import { HttpError, 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
+ * @returns {Promise<Response>}
8
+ */
9
+ export async function render_endpoint(event, mod) {
10
+ const method = /** @type {import('types').HttpMethod} */ (event.request.method);
11
+
12
+ // TODO: Remove for 1.0
13
+ check_method_names(mod);
14
+
15
+ let handler = mod[method];
16
+
17
+ if (!handler && method === 'HEAD') {
18
+ handler = mod.GET;
19
+ }
20
+
21
+ if (!handler) {
22
+ return method_not_allowed(mod, method);
23
+ }
24
+
25
+ try {
26
+ const response = await handler(
27
+ /** @type {import('types').RequestEvent<Record<string, any>>} */ (event)
28
+ );
29
+
30
+ if (!(response instanceof Response)) {
31
+ return new Response(
32
+ `Invalid response from route ${event.url.pathname}: handler should return a Response object`,
33
+ { status: 500 }
34
+ );
35
+ }
36
+
37
+ return response;
38
+ } catch (error) {
39
+ if (error instanceof HttpError) {
40
+ return new Response(error.message, { status: error.status });
41
+ } else if (error instanceof Redirect) {
42
+ return new Response(undefined, {
43
+ status: error.status,
44
+ headers: { Location: error.location }
45
+ });
46
+ } else {
47
+ throw error;
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,369 @@
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 { serialize_error, GENERIC_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 { negotiate } from '../../utils/http.js';
10
+ import { render_data } from './data/index.js';
11
+ import { DATA_SUFFIX } from '../../constants.js';
12
+
13
+ /* global __SVELTEKIT_ADAPTER_NAME__ */
14
+
15
+ /** @param {{ html: string }} opts */
16
+ const default_transform = ({ html }) => html;
17
+
18
+ /** @type {import('types').Respond} */
19
+ export async function respond(request, options, state) {
20
+ let url = new URL(request.url);
21
+
22
+ const { parameter, allowed } = options.method_override;
23
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
24
+
25
+ if (method_override) {
26
+ if (request.method === 'POST') {
27
+ if (allowed.includes(method_override)) {
28
+ request = new Proxy(request, {
29
+ get: (target, property, _receiver) => {
30
+ if (property === 'method') return method_override;
31
+ return Reflect.get(target, property, target);
32
+ }
33
+ });
34
+ } else {
35
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
36
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs/configuration#methodoverride`;
37
+
38
+ return new Response(body, {
39
+ status: 400
40
+ });
41
+ }
42
+ } else {
43
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
44
+ }
45
+ }
46
+
47
+ let decoded;
48
+ try {
49
+ decoded = decodeURI(url.pathname);
50
+ } catch {
51
+ return new Response('Malformed URI', { status: 400 });
52
+ }
53
+
54
+ /** @type {import('types').SSRRoute | null} */
55
+ let route = null;
56
+
57
+ /** @type {Record<string, string>} */
58
+ let params = {};
59
+
60
+ if (options.paths.base && !state.prerendering?.fallback) {
61
+ if (!decoded.startsWith(options.paths.base)) {
62
+ return new Response('Not found', { status: 404 });
63
+ }
64
+ decoded = decoded.slice(options.paths.base.length) || '/';
65
+ }
66
+
67
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
68
+ if (is_data_request) decoded = decoded.slice(0, -DATA_SUFFIX.length);
69
+
70
+ if (!state.prerendering?.fallback) {
71
+ const matchers = await options.manifest._.matchers();
72
+
73
+ for (const candidate of options.manifest._.routes) {
74
+ const match = candidate.pattern.exec(decoded);
75
+ if (!match) continue;
76
+
77
+ const matched = exec(match, candidate.names, candidate.types, matchers);
78
+ if (matched) {
79
+ route = candidate;
80
+ params = decode_params(matched);
81
+ break;
82
+ }
83
+ }
84
+ }
85
+
86
+ if (route?.page && !is_data_request) {
87
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
88
+
89
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
90
+ return new Response(undefined, {
91
+ status: 301,
92
+ headers: {
93
+ 'x-sveltekit-normalize': '1',
94
+ location:
95
+ // ensure paths starting with '//' are not treated as protocol-relative
96
+ (normalized.startsWith('//') ? url.origin + normalized : normalized) +
97
+ (url.search === '?' ? '' : url.search)
98
+ }
99
+ });
100
+ }
101
+ }
102
+
103
+ /** @type {import('types').ResponseHeaders} */
104
+ const headers = {};
105
+
106
+ /** @type {string[]} */
107
+ const cookies = [];
108
+
109
+ if (state.prerendering) disable_search(url);
110
+
111
+ /** @type {import('types').RequestEvent} */
112
+ const event = {
113
+ getClientAddress:
114
+ state.getClientAddress ||
115
+ (() => {
116
+ throw new Error(
117
+ `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue`
118
+ );
119
+ }),
120
+ locals: {},
121
+ params,
122
+ platform: state.platform,
123
+ request,
124
+ routeId: route && route.id,
125
+ setHeaders: (new_headers) => {
126
+ for (const key in new_headers) {
127
+ const lower = key.toLowerCase();
128
+ const value = new_headers[key];
129
+
130
+ if (lower === 'set-cookie') {
131
+ const new_cookies = /** @type {string[]} */ (Array.isArray(value) ? value : [value]);
132
+
133
+ for (const cookie of new_cookies) {
134
+ if (cookies.includes(cookie)) {
135
+ throw new Error(`"${key}" header already has cookie with same value`);
136
+ }
137
+
138
+ cookies.push(cookie);
139
+ }
140
+ } else if (lower in headers) {
141
+ throw new Error(`"${key}" header is already set`);
142
+ } else {
143
+ headers[lower] = value;
144
+
145
+ if (state.prerendering && lower === 'cache-control') {
146
+ state.prerendering.cache = /** @type {string} */ (value);
147
+ }
148
+ }
149
+ }
150
+ },
151
+ url
152
+ };
153
+
154
+ // TODO remove this for 1.0
155
+ /**
156
+ * @param {string} property
157
+ * @param {string} replacement
158
+ * @param {string} suffix
159
+ */
160
+ const removed = (property, replacement, suffix = '') => ({
161
+ get: () => {
162
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
163
+ }
164
+ });
165
+
166
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
167
+
168
+ const body_getter = {
169
+ get: () => {
170
+ throw new Error(
171
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
172
+ details
173
+ );
174
+ }
175
+ };
176
+
177
+ Object.defineProperties(event, {
178
+ clientAddress: removed('clientAddress', 'getClientAddress'),
179
+ method: removed('method', 'request.method', details),
180
+ headers: removed('headers', 'request.headers', details),
181
+ origin: removed('origin', 'url.origin'),
182
+ path: removed('path', 'url.pathname'),
183
+ query: removed('query', 'url.searchParams'),
184
+ body: body_getter,
185
+ rawBody: body_getter
186
+ });
187
+
188
+ /** @type {import('types').RequiredResolveOptions} */
189
+ let resolve_opts = {
190
+ ssr: true,
191
+ transformPageChunk: default_transform
192
+ };
193
+
194
+ // TODO match route before calling handle?
195
+
196
+ try {
197
+ const response = await options.hooks.handle({
198
+ event,
199
+ resolve: async (event, opts) => {
200
+ if (opts) {
201
+ // TODO remove for 1.0
202
+ // @ts-expect-error
203
+ if (opts.transformPage) {
204
+ throw new Error(
205
+ 'transformPage has been replaced by transformPageChunk — see https://github.com/sveltejs/kit/pull/5657 for more information'
206
+ );
207
+ }
208
+
209
+ resolve_opts = {
210
+ ssr: opts.ssr !== false,
211
+ transformPageChunk: opts.transformPageChunk || default_transform
212
+ };
213
+ }
214
+
215
+ if (state.prerendering?.fallback) {
216
+ return await render_response({
217
+ event,
218
+ options,
219
+ state,
220
+ page_config: { router: true, hydrate: true },
221
+ status: 200,
222
+ error: null,
223
+ branch: [],
224
+ fetched: [],
225
+ validation_errors: undefined,
226
+ cookies: [],
227
+ resolve_opts: {
228
+ ...resolve_opts,
229
+ ssr: false
230
+ }
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());
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
+ },
320
+
321
+ // TODO remove for 1.0
322
+ // @ts-expect-error
323
+ get request() {
324
+ throw new Error('request in handle has been replaced with event' + details);
325
+ }
326
+ });
327
+
328
+ // TODO for 1.0, change the error message to point to docs rather than PR
329
+ if (response && !(response instanceof Response)) {
330
+ throw new Error('handle must return a Response object' + details);
331
+ }
332
+
333
+ return response;
334
+ } catch (/** @type {unknown} */ e) {
335
+ const error = coalesce_to_error(e);
336
+
337
+ options.handle_error(error, event);
338
+
339
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
340
+ 'text/html',
341
+ 'application/json'
342
+ ]);
343
+
344
+ if (is_data_request || type === 'application/json') {
345
+ return new Response(serialize_error(error, options.get_stack), {
346
+ status: 500,
347
+ headers: { 'content-type': 'application/json; charset=utf-8' }
348
+ });
349
+ }
350
+
351
+ // TODO is this necessary? should we just return a plain 500 at this point?
352
+ try {
353
+ return await respond_with_error({
354
+ event,
355
+ options,
356
+ state,
357
+ status: 500,
358
+ error,
359
+ resolve_opts
360
+ });
361
+ } catch (/** @type {unknown} */ e) {
362
+ const error = coalesce_to_error(e);
363
+
364
+ return new Response(options.dev ? error.stack : error.message, {
365
+ status: 500
366
+ });
367
+ }
368
+ }
369
+ }
@@ -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
+ }