brumate 0.2.0 → 0.4.0
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.
- package/README.md +2 -2
- package/check.d.ts +49 -0
- package/dist/{boot-D-IdPy7B.d.ts → boot-DLlRmD9z.d.ts} +11 -10
- package/dist/cli.js +275 -15
- package/dist/cli.js.map +1 -1
- package/dist/client-BvDsC6Qr.js +3463 -0
- package/dist/client-BvDsC6Qr.js.map +1 -0
- package/dist/client-DBwL2wKQ.d.ts +669 -0
- package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
- package/dist/client-routes-BtGpYCef.js.map +1 -0
- package/dist/{cookies-Av5WFmcf.js → cookies-Cnbf4w-S.js} +15 -7
- package/dist/cookies-Cnbf4w-S.js.map +1 -0
- package/dist/{defer-D0bo1Gqx.js → defer-CKWZLv2K.js} +8 -4
- package/dist/defer-CKWZLv2K.js.map +1 -0
- package/dist/devtools-4uTPwR_v.js +597 -0
- package/dist/devtools-4uTPwR_v.js.map +1 -0
- package/dist/devtools-panel-Be9pxYgv.js +1994 -0
- package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
- package/dist/events-LgLdp1R7.js +114 -0
- package/dist/events-LgLdp1R7.js.map +1 -0
- package/dist/features-CHY5Ekku.js +30 -0
- package/dist/features-CHY5Ekku.js.map +1 -0
- package/dist/files-WW4RlajL.js +506 -0
- package/dist/files-WW4RlajL.js.map +1 -0
- package/dist/forms-j1xPAR14.d.ts +281 -0
- package/dist/forms-nXK7-Lv_.js +440 -0
- package/dist/forms-nXK7-Lv_.js.map +1 -0
- package/dist/highlight.d.ts +17 -0
- package/dist/highlight.js +278 -0
- package/dist/highlight.js.map +1 -0
- package/dist/html-BtKRyi7g.js +305 -0
- package/dist/html-BtKRyi7g.js.map +1 -0
- package/dist/html-Bw9Qwu6F.d.ts +107 -0
- package/dist/index.d.ts +142 -11
- package/dist/index.js +641 -106
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BJtACnQp.js → inspect-Y6y4uNZp.js} +4333 -681
- package/dist/inspect-Y6y4uNZp.js.map +1 -0
- package/dist/{loader-B18i3_-T.js → loader-BjKGJzLN.js} +21 -14
- package/dist/loader-BjKGJzLN.js.map +1 -0
- package/dist/logo-DQ_OYhBi.js +10 -0
- package/dist/logo-DQ_OYhBi.js.map +1 -0
- package/dist/{navigate-BwuZveDF.js → navigate-CfOr-TRF.js} +130 -24
- package/dist/navigate-CfOr-TRF.js.map +1 -0
- package/dist/nesting-DA5vJw9X.js +265 -0
- package/dist/nesting-DA5vJw9X.js.map +1 -0
- package/dist/produce-B7X9ori9.js +402 -0
- package/dist/produce-B7X9ori9.js.map +1 -0
- package/dist/produce-DIgHBVwL.d.ts +148 -0
- package/dist/{rpc-B-Zkn6Ch.js → rpc-Q-XkLwFh.js} +28 -13
- package/dist/rpc-Q-XkLwFh.js.map +1 -0
- package/dist/runtime/batch.js +9 -7
- package/dist/runtime/batch.js.map +1 -1
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +4 -4
- package/dist/runtime/devtools.d.ts +172 -5
- package/dist/runtime/devtools.js +3 -1
- package/dist/runtime/env.js +14 -2
- package/dist/runtime/env.js.map +1 -1
- package/dist/runtime/events.d.ts +38 -1
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/forms.d.ts +2 -0
- package/dist/runtime/forms.js +1 -0
- package/dist/runtime/gather.d.ts +25 -0
- package/dist/runtime/gather.js +33 -0
- package/dist/runtime/gather.js.map +1 -0
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +5 -2
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.js +4 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +5 -4
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +75 -2
- package/dist/runtime/signals.js +44 -2
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +18 -3
- package/dist/runtime/testing.js +150 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/runtime/values.d.ts +2 -0
- package/dist/runtime/values.js +24 -0
- package/dist/runtime/values.js.map +1 -0
- package/dist/{server-BA9SJ2Vm.d.ts → server-BvPIg9pT.d.ts} +363 -32
- package/dist/{server-BqfM95r1.js → server-DjyOVJtJ.js} +1309 -220
- package/dist/server-DjyOVJtJ.js.map +1 -0
- package/dist/{static-loader-BzE9SRaj.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
- package/dist/static-loader-BZR17hSw.js +312 -0
- package/dist/static-loader-BZR17hSw.js.map +1 -0
- package/dist/{stream-JaMHMdBD.js → stream-BP5AVmg5.js} +182 -17
- package/dist/stream-BP5AVmg5.js.map +1 -0
- package/dist/values-B8C7CLvG.d.ts +63 -0
- package/dist/vite.d.ts +20 -20
- package/dist/vite.js +2031 -539
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +951 -0
- package/forms/forms.brm.ts +141 -0
- package/package.json +41 -3
- package/skills/brumate/SKILL.md +58 -0
- package/skills/brumate/references/errors.md +2078 -0
- package/skills/brumate/references/events.md +117 -0
- package/skills/brumate/references/signals.md +61 -0
- package/skills/brumate/references/state.md +235 -0
- package/skills/brumate/references/syntax.md +250 -0
- package/types.d.ts +4 -4
- package/dist/client-C0UCNL3J.js +0 -1643
- package/dist/client-C0UCNL3J.js.map +0 -1
- package/dist/client-MD0ZmcFR.d.ts +0 -354
- package/dist/client-routes-JTbGtukf.js.map +0 -1
- package/dist/cookies-Av5WFmcf.js.map +0 -1
- package/dist/defer-D0bo1Gqx.js.map +0 -1
- package/dist/devtools-C50VH8gZ.js +0 -113
- package/dist/devtools-C50VH8gZ.js.map +0 -1
- package/dist/devtools-panel-AYjfwPhj.js +0 -435
- package/dist/devtools-panel-AYjfwPhj.js.map +0 -1
- package/dist/events-BKWRqtMg.js +0 -52
- package/dist/events-BKWRqtMg.js.map +0 -1
- package/dist/files-Bnn1JqHx.js +0 -192
- package/dist/files-Bnn1JqHx.js.map +0 -1
- package/dist/html-bHZbkK-h.js +0 -170
- package/dist/html-bHZbkK-h.js.map +0 -1
- package/dist/html-y1q7-t7D.d.ts +0 -60
- package/dist/inspect-BJtACnQp.js.map +0 -1
- package/dist/loader-B18i3_-T.js.map +0 -1
- package/dist/navigate-BwuZveDF.js.map +0 -1
- package/dist/produce-CWfJ4byV.js +0 -167
- package/dist/produce-CWfJ4byV.js.map +0 -1
- package/dist/produce-D4K7qpaL.d.ts +0 -72
- package/dist/rpc-B-Zkn6Ch.js.map +0 -1
- package/dist/server-BqfM95r1.js.map +0 -1
- package/dist/static-loader-DOygOFj5.js +0 -216
- package/dist/static-loader-DOygOFj5.js.map +0 -1
- package/dist/stream-JaMHMdBD.js.map +0 -1
|
@@ -3,45 +3,73 @@
|
|
|
3
3
|
function readId(text) {
|
|
4
4
|
return /^-?\d+$/.test(text) ? Number(text) : text;
|
|
5
5
|
}
|
|
6
|
+
/** Reads a list of scope IDs from text. An empty item is left out when `skipEmpty` is set. */
|
|
7
|
+
function readIds(text, separator, skipEmpty) {
|
|
8
|
+
const ids = [];
|
|
9
|
+
for (const part of text.split(separator)) {
|
|
10
|
+
if (skipEmpty && !part) continue;
|
|
11
|
+
ids.push(readId(part));
|
|
12
|
+
}
|
|
13
|
+
return ids;
|
|
14
|
+
}
|
|
6
15
|
/** Adds a number to an ID, as `shiftId` in `shared.ts` does. */
|
|
7
16
|
function shiftId(id, by) {
|
|
8
17
|
if (typeof id === "number") return id + by;
|
|
9
18
|
const dot = id.indexOf(".");
|
|
10
19
|
return `${Number(id.slice(0, dot)) + by}${id.slice(dot)}`;
|
|
11
20
|
}
|
|
12
|
-
/**
|
|
13
|
-
function
|
|
14
|
-
const
|
|
21
|
+
/** Makes an object with the same keys and the values that `map` returns. */
|
|
22
|
+
function mapValues(object, map) {
|
|
23
|
+
const entries = [];
|
|
24
|
+
for (const [key, value] of Object.entries(object)) entries.push([key, map(value)]);
|
|
25
|
+
return Object.fromEntries(entries);
|
|
26
|
+
}
|
|
27
|
+
/** Adds a number to the scope IDs of a state record, in the places that the table names. */
|
|
28
|
+
function shiftState(ids, state, by) {
|
|
29
|
+
const { fields, references, holders } = ids;
|
|
15
30
|
const seen = /* @__PURE__ */ new Set();
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
31
|
+
function shiftValue(value) {
|
|
32
|
+
for (const type of references) if (value instanceof type) {
|
|
33
|
+
const moved = Object.assign(Object.create(Object.getPrototypeOf(value)), value, { scope: shiftId(value.scope, by) });
|
|
34
|
+
if (moved.at !== void 0) moved.at = shiftId(moved.at, by);
|
|
35
|
+
return moved;
|
|
36
|
+
}
|
|
37
|
+
for (const type of holders) if (value instanceof type) return Object.assign(Object.create(Object.getPrototypeOf(value)), mapValues(value, shiftValue));
|
|
19
38
|
if (value instanceof Promise) return value.then(shiftValue);
|
|
20
39
|
if (typeof value === "object" && value !== null && !seen.has(value)) {
|
|
21
40
|
seen.add(value);
|
|
22
|
-
if (Array.isArray(value)) value.
|
|
41
|
+
if (Array.isArray(value)) for (const [index, item] of value.entries()) {
|
|
42
|
+
if (!(index in value)) continue;
|
|
23
43
|
value[index] = shiftValue(item);
|
|
24
|
-
}
|
|
44
|
+
}
|
|
25
45
|
else if (Object.getPrototypeOf(value) === Object.prototype) for (const [key, item] of Object.entries(value)) value[key] = shiftValue(item);
|
|
26
46
|
}
|
|
27
47
|
return value;
|
|
28
|
-
}
|
|
48
|
+
}
|
|
49
|
+
function shiftField(field, kind) {
|
|
50
|
+
if (kind === "id") return shiftId(field, by);
|
|
51
|
+
if (kind === "ids") return mapValues(field, (id) => shiftId(id, by));
|
|
52
|
+
if (kind === "values") {
|
|
53
|
+
const moved = [];
|
|
54
|
+
for (const item of field) moved.push(shiftValue(item));
|
|
55
|
+
return moved;
|
|
56
|
+
}
|
|
57
|
+
return kind === "map" ? mapValues(field, shiftValue) : shiftValue(field);
|
|
58
|
+
}
|
|
29
59
|
const result = {};
|
|
30
|
-
for (const [key, record] of Object.entries(state))
|
|
31
|
-
...record
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
s: record.s?.map(shiftValue)
|
|
36
|
-
};
|
|
60
|
+
for (const [key, record] of Object.entries(state)) {
|
|
61
|
+
const moved = { ...record };
|
|
62
|
+
for (const [name, kind] of Object.entries(fields)) if (moved[name] !== void 0 && kind !== "none") moved[name] = shiftField(moved[name], kind);
|
|
63
|
+
result[shiftId(readId(key), by)] = moved;
|
|
64
|
+
}
|
|
37
65
|
return result;
|
|
38
66
|
}
|
|
39
67
|
/** Removes scopes and the scopes inside them, and runs their cleanups. */
|
|
40
68
|
function dropScopes(core, roots) {
|
|
41
|
-
|
|
69
|
+
function inside(scope) {
|
|
42
70
|
for (let current = scope; current; current = current.p ?? current.o) if (roots.has(current.id)) return true;
|
|
43
71
|
return false;
|
|
44
|
-
}
|
|
72
|
+
}
|
|
45
73
|
for (const scope of core.scopes.values()) if (inside(scope)) core.removeScope(scope);
|
|
46
74
|
}
|
|
47
75
|
/**
|
|
@@ -54,26 +82,29 @@ function dropScopes(core, roots) {
|
|
|
54
82
|
*/
|
|
55
83
|
function routeRecord(core, script, state) {
|
|
56
84
|
const offset = Number(script.getAttribute("b-offset") ?? 0);
|
|
57
|
-
const value = offset ? shiftState(core, state, offset) : state;
|
|
85
|
+
const value = offset ? shiftState(core.scopeIds, state, offset) : state;
|
|
58
86
|
const drop = script.getAttribute("b-drop");
|
|
59
|
-
if (drop) dropScopes(core, new Set(drop
|
|
87
|
+
if (drop) dropScopes(core, new Set(readIds(drop, ",", false)));
|
|
60
88
|
const list = script.getAttribute("b-roots");
|
|
61
89
|
if (list === null) return value;
|
|
62
|
-
const roots = new Set(list
|
|
90
|
+
const roots = new Set(readIds(list, ",", true));
|
|
63
91
|
const alias = /* @__PURE__ */ new Map();
|
|
64
|
-
for (const pair of (script.getAttribute("b-alias") ?? "").split(",")
|
|
65
|
-
|
|
92
|
+
for (const pair of (script.getAttribute("b-alias") ?? "").split(",")) {
|
|
93
|
+
if (!pair) continue;
|
|
94
|
+
const [from, to] = readIds(pair, ":", false);
|
|
66
95
|
alias.set(from, to);
|
|
67
96
|
}
|
|
68
|
-
|
|
97
|
+
function kept(id) {
|
|
69
98
|
for (let current = id; current !== void 0;) {
|
|
70
99
|
if (roots.has(current)) return true;
|
|
71
100
|
const record = value[current];
|
|
72
101
|
current = record?.p ?? record?.o;
|
|
73
102
|
}
|
|
74
103
|
return false;
|
|
75
|
-
}
|
|
76
|
-
|
|
104
|
+
}
|
|
105
|
+
function resolve(id) {
|
|
106
|
+
return id === void 0 ? void 0 : alias.get(id) ?? id;
|
|
107
|
+
}
|
|
77
108
|
const result = {};
|
|
78
109
|
for (const [key, record] of Object.entries(value)) {
|
|
79
110
|
const id = readId(key);
|
|
@@ -90,12 +121,11 @@ function routeRecord(core, script, state) {
|
|
|
90
121
|
* that forgets the page before navigation replaces it, or only stops reading
|
|
91
122
|
* when layouts stay.
|
|
92
123
|
*/
|
|
93
|
-
const ready = import("./runtime/client.js").then(({
|
|
124
|
+
const ready = import("./runtime/client.js").then(({ hooks, leavePage, leaveRoutes, removeScope, scopeIds, scopes }) => {
|
|
94
125
|
const core = {
|
|
95
|
-
ElementReference,
|
|
96
|
-
FunctionReference,
|
|
97
126
|
hooks,
|
|
98
127
|
removeScope,
|
|
128
|
+
scopeIds,
|
|
99
129
|
scopes
|
|
100
130
|
};
|
|
101
131
|
hooks.record = (script, state) => routeRecord(core, script, state);
|
|
@@ -104,4 +134,4 @@ const ready = import("./runtime/client.js").then(({ ElementReference, FunctionRe
|
|
|
104
134
|
//#endregion
|
|
105
135
|
export { ready };
|
|
106
136
|
|
|
107
|
-
//# sourceMappingURL=client-routes-
|
|
137
|
+
//# sourceMappingURL=client-routes-BtGpYCef.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-routes-BtGpYCef.js","names":[],"sources":["../src/runtime/client-routes.ts"],"sourcesContent":["// What the core needs to read the pages that client navigation adds. Only\n// `navigate.ts` writes the attributes that this module reads, so the loader\n// imports it when it navigates or finds such a record, and a page that never\n// navigates does not load it. Importing it sets the core's `record` hook.\n//\n// It reads the core with `import()`, as `rpc.ts` does, and imports nothing\n// else. A static import of the core would make the package build move the\n// core into a chunk behind a module that only re-exports it, and a static\n// import of `shared.ts` would split that module out of the core of a page.\n// The core is loaded already, or loads with this module.\n\nimport type * as Client from './client.ts';\nimport type { Scope } from './client.ts';\nimport type { FieldKind, PageState, ScopeId, ScopeState } from './shared.ts';\n\n/** The parts of the core that this module uses. */\ntype Core = Pick<typeof Client, 'hooks' | 'removeScope' | 'scopeIds' | 'scopes'>;\n\n/** Reads an ID, as `parseId` in `shared.ts` does. This module imports no code of its own. */\nfunction readId(text: string): ScopeId {\n return /^-?\\d+$/.test(text) ? Number(text) : text;\n}\n\n/** Reads a list of scope IDs from text. An empty item is left out when `skipEmpty` is set. */\nfunction readIds(text: string, separator: string, skipEmpty: boolean): ScopeId[] {\n const ids: ScopeId[] = [];\n for (const part of text.split(separator)) {\n if (skipEmpty && !part) {\n continue;\n }\n ids.push(readId(part));\n }\n return ids;\n}\n\n/** Adds a number to an ID, as `shiftId` in `shared.ts` does. */\nfunction shiftId(id: ScopeId, by: number): ScopeId {\n if (typeof id === 'number') {\n return id + by;\n }\n const dot = id.indexOf('.');\n return `${Number(id.slice(0, dot)) + by}${id.slice(dot)}`;\n}\n\n/** Makes an object with the same keys and the values that `map` returns. */\nfunction mapValues(object: object, map: (value: unknown) => unknown): object {\n const entries: [string, unknown][] = [];\n for (const [key, value] of Object.entries(object)) {\n entries.push([key, map(value)]);\n }\n return Object.fromEntries(entries);\n}\n\n/** Adds a number to the scope IDs of a state record, in the places that the table names. */\nexport function shiftState(ids: Core['scopeIds'], state: PageState, by: number): PageState {\n const { fields, references, holders } = ids;\n const seen = new Set<object>();\n function shiftValue(value: unknown): unknown {\n // A reference is copied with its own fields, and its scope moved.\n for (const type of references) {\n if (value instanceof type) {\n const moved = Object.assign(Object.create(Object.getPrototypeOf(value)), value, {\n scope: shiftId(value.scope, by),\n });\n // Children name the scope where the server rendered them too.\n if (moved.at !== undefined) {\n moved.at = shiftId(moved.at, by);\n }\n return moved;\n }\n }\n // A holder is copied with every field moved.\n for (const type of holders) {\n if (value instanceof type) {\n return Object.assign(\n Object.create(Object.getPrototypeOf(value)),\n mapValues(value, shiftValue),\n );\n }\n }\n // A later record settles it, with a value whose IDs move too.\n if (value instanceof Promise) {\n return value.then(shiftValue);\n }\n if (typeof value === 'object' && value !== null && !seen.has(value)) {\n seen.add(value);\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n // A hole stays a hole.\n if (!(index in value)) {\n continue;\n }\n value[index] = shiftValue(item);\n }\n } else if (Object.getPrototypeOf(value) === Object.prototype) {\n for (const [key, item] of Object.entries(value)) {\n (value as Record<string, unknown>)[key] = shiftValue(item);\n }\n }\n }\n return value;\n }\n function shiftField(field: unknown, kind: FieldKind): unknown {\n if (kind === 'id') {\n return shiftId(field as ScopeId, by);\n }\n if (kind === 'ids') {\n return mapValues(field as object, (id) => shiftId(id as ScopeId, by));\n }\n if (kind === 'values') {\n const moved: unknown[] = [];\n for (const item of field as unknown[]) {\n moved.push(shiftValue(item));\n }\n return moved;\n }\n return kind === 'map' ? mapValues(field as object, shiftValue) : shiftValue(field);\n }\n const result: PageState = {};\n for (const [key, record] of Object.entries(state)) {\n const moved: Record<string, unknown> = { ...record };\n for (const [name, kind] of Object.entries(fields)) {\n if (moved[name] !== undefined && kind !== 'none') {\n moved[name] = shiftField(moved[name], kind);\n }\n }\n result[shiftId(readId(key), by)] = moved as ScopeState;\n }\n return result;\n}\n\n/** Removes scopes and the scopes inside them, and runs their cleanups. */\nfunction dropScopes(core: Core, roots: Set<ScopeId>): void {\n function inside(scope: Scope): boolean {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (roots.has(current.id)) {\n return true;\n }\n }\n return false;\n }\n // Deleting from a map while iterating it is safe.\n for (const scope of core.scopes.values()) {\n if (inside(scope)) {\n core.removeScope(scope);\n }\n }\n}\n\n/**\n * Reads the attributes that navigation set on a state record. A page whose\n * IDs started at another number, such as a prerendered file, has them moved\n * with `b-offset`. A page that replaced only some routes of the one before\n * it drops the old routes with `b-drop`, and adds only the scopes inside\n * `b-roots`, with the scopes of the kept layouts in place of the new\n * page's copies of them, by `b-alias`.\n */\nfunction routeRecord(core: Core, script: Element, state: PageState): PageState {\n // Only records with scopes hold IDs. Later records settle promises, which `shiftState` wraps.\n const offset = Number(script.getAttribute('b-offset') ?? 0);\n const value = offset ? shiftState(core.scopeIds, state, offset) : state;\n const drop = script.getAttribute('b-drop');\n if (drop) {\n dropScopes(core, new Set(readIds(drop, ',', false)));\n }\n const list = script.getAttribute('b-roots');\n if (list === null) {\n return value;\n }\n const roots = new Set(readIds(list, ',', true));\n const alias = new Map<ScopeId, ScopeId>();\n for (const pair of (script.getAttribute('b-alias') ?? '').split(',')) {\n if (!pair) {\n continue;\n }\n const [from, to] = readIds(pair, ':', false) as [ScopeId, ScopeId];\n alias.set(from, to);\n }\n function kept(id: ScopeId): boolean {\n for (let current: ScopeId | undefined = id; current !== undefined;) {\n if (roots.has(current)) {\n return true;\n }\n const record: ScopeState | undefined = value[current];\n current = record?.p ?? record?.o;\n }\n return false;\n }\n function resolve(id: ScopeId | undefined): ScopeId | undefined {\n return id === undefined ? undefined : (alias.get(id) ?? id);\n }\n const result: PageState = {};\n for (const [key, record] of Object.entries(value)) {\n // The new page renders the kept layouts again. Their scopes are not added.\n const id = readId(key);\n if (kept(id)) {\n result[id] = { ...record, p: resolve(record.p), o: resolve(record.o) };\n }\n }\n return result;\n}\n\n/**\n * Settles once the core reads records with this module, with the function\n * that forgets the page before navigation replaces it, or only stops reading\n * when layouts stay.\n */\nexport const ready: Promise<(partial: boolean) => void> = import('./client.ts').then(\n ({ hooks, leavePage, leaveRoutes, removeScope, scopeIds, scopes }) => {\n const core = {\n hooks,\n removeScope,\n scopeIds,\n scopes,\n };\n hooks.record = (script, state) => routeRecord(core, script, state);\n return (partial) => (partial ? leaveRoutes() : leavePage());\n },\n);\n"],"mappings":";;AAmBA,SAAS,OAAO,MAAuB;CACrC,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,IAAI,IAAI;AAC/C;;AAGA,SAAS,QAAQ,MAAc,WAAmB,WAA+B;CAC/E,MAAM,MAAiB,CAAC;CACxB,KAAK,MAAM,QAAQ,KAAK,MAAM,SAAS,GAAG;EACxC,IAAI,aAAa,CAAC,MAChB;EAEF,IAAI,KAAK,OAAO,IAAI,CAAC;CACvB;CACA,OAAO;AACT;;AAGA,SAAS,QAAQ,IAAa,IAAqB;CACjD,IAAI,OAAO,OAAO,UAChB,OAAO,KAAK;CAEd,MAAM,MAAM,GAAG,QAAQ,GAAG;CAC1B,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,GAAG,CAAC,IAAI,KAAK,GAAG,MAAM,GAAG;AACxD;;AAGA,SAAS,UAAU,QAAgB,KAA0C;CAC3E,MAAM,UAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,QAAQ,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC;CAEhC,OAAO,OAAO,YAAY,OAAO;AACnC;;AAGA,SAAgB,WAAW,KAAuB,OAAkB,IAAuB;CACzF,MAAM,EAAE,QAAQ,YAAY,YAAY;CACxC,MAAM,uBAAO,IAAI,IAAY;CAC7B,SAAS,WAAW,OAAyB;EAE3C,KAAK,MAAM,QAAQ,YACjB,IAAI,iBAAiB,MAAM;GACzB,MAAM,QAAQ,OAAO,OAAO,OAAO,OAAO,OAAO,eAAe,KAAK,CAAC,GAAG,OAAO,EAC9E,OAAO,QAAQ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;GAC7C,UAAU,QAAQ,KAAK,QAAQ;EACjC;EACA,OAAO;CACT;CACA,SAAS,QAAQ,IAA8C;EAC7D,OAAO,OAAO,KAAA,IAAY,KAAA,IAAa,MAAM,IAAI,EAAE,KAAK;CAC1D;CACA,MAAM,SAAoB,CAAC;CAC3B,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,KAAK,GAAG;EAEjD,MAAM,KAAK,OAAO,GAAG;EACrB,IAAI,KAAK,EAAE,GACT,OAAO,MAAM;GAAE,GAAG;GAAQ,GAAG,QAAQ,OAAO,CAAC;GAAG,GAAG,QAAQ,OAAO,CAAC;EAAE;CAEzE;CACA,OAAO;AACT;;;;;;AAOA,MAAa,QAA6C,OAAO,sBAAc,CAAC,MAC7E,EAAE,OAAO,WAAW,aAAa,aAAa,UAAU,aAAa;CACpE,MAAM,OAAO;EACX;EACA;EACA;EACA;CACF;CACA,MAAM,UAAU,QAAQ,UAAU,YAAY,MAAM,QAAQ,KAAK;CACjE,QAAQ,YAAa,UAAU,YAAY,IAAI,UAAU;AAC3D,CACF"}
|
|
@@ -49,6 +49,7 @@ function getCookies(event) {
|
|
|
49
49
|
}
|
|
50
50
|
/** Sets a cookie on the response of an event. See `RequestEvent.setCookie`. */
|
|
51
51
|
function setCookie(event, name, value, options = {}) {
|
|
52
|
+
event.personal = true;
|
|
52
53
|
const secure = options.secure ?? new URL(event.request.url).protocol === "https:";
|
|
53
54
|
event.headers.append("set-cookie", serializeCookie(name, value, {
|
|
54
55
|
...options,
|
|
@@ -107,10 +108,15 @@ function fromBase64Url(text) {
|
|
|
107
108
|
*/
|
|
108
109
|
function createSession(options) {
|
|
109
110
|
const secrets = Array.isArray(options.secret) ? options.secret : [options.secret];
|
|
110
|
-
|
|
111
|
+
let tooShort = secrets.length === 0;
|
|
112
|
+
for (const secret of secrets) if (secret.length < 32) {
|
|
113
|
+
tooShort = true;
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
if (tooShort) throw new Error("A session secret needs at least 32 characters");
|
|
111
117
|
const name = options.name ?? "session";
|
|
112
118
|
const maxAge = options.maxAge ?? 604800;
|
|
113
|
-
|
|
119
|
+
async function read(event) {
|
|
114
120
|
const value = getCookies(event)[name];
|
|
115
121
|
const dot = value?.lastIndexOf(".") ?? -1;
|
|
116
122
|
if (!value || dot === -1) return;
|
|
@@ -121,15 +127,17 @@ function createSession(options) {
|
|
|
121
127
|
} catch {
|
|
122
128
|
return;
|
|
123
129
|
}
|
|
124
|
-
|
|
130
|
+
const pending = [];
|
|
131
|
+
for (const secret of secrets) pending.push((async () => crypto.subtle.verify("HMAC", await key(secret), signature, encoder.encode(payload)))());
|
|
132
|
+
if (!(await Promise.all(pending)).includes(true)) return;
|
|
125
133
|
try {
|
|
126
134
|
const { d: data, e: expires } = JSON.parse(decoder.decode(fromBase64Url(payload)));
|
|
127
135
|
return expires > Date.now() ? data : void 0;
|
|
128
136
|
} catch {
|
|
129
137
|
return;
|
|
130
138
|
}
|
|
131
|
-
}
|
|
132
|
-
|
|
139
|
+
}
|
|
140
|
+
async function write(event, data) {
|
|
133
141
|
const payload = toBase64Url(encoder.encode(JSON.stringify({
|
|
134
142
|
d: data,
|
|
135
143
|
e: Date.now() + maxAge * 1e3
|
|
@@ -140,7 +148,7 @@ function createSession(options) {
|
|
|
140
148
|
...options.cookie,
|
|
141
149
|
maxAge
|
|
142
150
|
});
|
|
143
|
-
}
|
|
151
|
+
}
|
|
144
152
|
return {
|
|
145
153
|
get: read,
|
|
146
154
|
set: write,
|
|
@@ -172,4 +180,4 @@ function toNodeHeaders(headers) {
|
|
|
172
180
|
//#endregion
|
|
173
181
|
export { serializeCookie as a, parseCookies as i, deleteCookie as n, setCookie as o, getCookies as r, toNodeHeaders as s, createSession as t };
|
|
174
182
|
|
|
175
|
-
//# sourceMappingURL=cookies-
|
|
183
|
+
//# sourceMappingURL=cookies-Cnbf4w-S.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cookies-Cnbf4w-S.js","names":[],"sources":["../src/runtime/cookies.ts"],"sourcesContent":["// Cookies and sessions, for server functions, rendering, middleware and\n// endpoints. They read the request of a `RequestEvent` and write `set-cookie`\n// headers on its response.\n\nimport type { RequestEvent } from './request.ts';\n\nexport interface CookieOptions {\n /** Seconds until the cookie expires. Without it, the cookie lasts until the browser closes. */\n maxAge?: number;\n expires?: Date;\n /** Defaults to `/`. */\n path?: string;\n domain?: string;\n /** Defaults to true when the request is HTTPS. */\n secure?: boolean;\n /** Keeps the cookie from browser code. Defaults to true. */\n httpOnly?: boolean;\n /** Defaults to `lax`. */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\n/** Reads the cookies of a `cookie` header. */\nexport function parseCookies(header: string | null): Record<string, string> {\n const result: Record<string, string> = {};\n for (const part of (header ?? '').split(';')) {\n const index = part.indexOf('=');\n if (index === -1) {\n continue;\n }\n const name = part.slice(0, index).trim();\n if (name && !(name in result)) {\n const value = part.slice(index + 1).trim();\n try {\n result[name] = decodeURIComponent(value);\n } catch {\n result[name] = value;\n }\n }\n }\n return result;\n}\n\n/** Writes a `set-cookie` header value. */\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n if (!/^[\\w!#$%&'*+.^`|~-]+$/.test(name)) {\n throw new Error(`\"${name}\" is not a valid cookie name`);\n }\n const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? '/'}`];\n if (options.maxAge !== undefined) {\n parts.push(`Max-Age=${Math.floor(options.maxAge)}`);\n }\n if (options.expires) {\n parts.push(`Expires=${options.expires.toUTCString()}`);\n }\n if (options.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n if (options.httpOnly !== false) {\n parts.push('HttpOnly');\n }\n if (options.secure) {\n parts.push('Secure');\n }\n parts.push(\n `SameSite=${(options.sameSite ?? 'lax').replace(/^./, (letter) => letter.toUpperCase())}`,\n );\n return parts.join('; ');\n}\n\n/** The parsed `cookie` header of each event, with the header it was parsed from. */\nconst parsed = new WeakMap<\n RequestEvent,\n { header: string | null; cookies: Record<string, string> }\n>();\n\n/** The cookies of the request, with the ones that this request set or deleted. */\nexport function getCookies(event: RequestEvent): Record<string, string> {\n const header = event.request.headers.get('cookie');\n let cached = parsed.get(event);\n if (cached?.header !== header) {\n cached = { header, cookies: parseCookies(header) };\n parsed.set(event, cached);\n }\n // A copy, so the caller cannot change the cache.\n const result = { ...cached.cookies };\n for (const [name, value] of event.cookies ?? []) {\n if (value === undefined) {\n delete result[name];\n } else {\n result[name] = value;\n }\n }\n return result;\n}\n\n/** Sets a cookie on the response of an event. See `RequestEvent.setCookie`. */\nexport function setCookie(\n event: RequestEvent,\n name: string,\n value: string,\n options: CookieOptions = {},\n): void {\n event.personal = true;\n const secure = options.secure ?? new URL(event.request.url).protocol === 'https:';\n event.headers.append('set-cookie', serializeCookie(name, value, { ...options, secure }));\n event.cookies ??= new Map();\n event.cookies.set(name, value);\n}\n\n/** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */\nexport function deleteCookie(\n event: RequestEvent,\n name: string,\n options: Pick<CookieOptions, 'path' | 'domain'> = {},\n): void {\n // `secure` follows the request, as for a cookie set without it.\n setCookie(event, name, '', { ...options, secure: undefined, maxAge: 0, expires: new Date(0) });\n event.cookies!.set(name, undefined);\n}\n\nexport interface SessionOptions {\n /**\n * Signs the cookie, so a browser cannot change it. Use a random string of\n * at least 32 characters, kept out of the code, such as in an environment\n * variable. A list signs with the first and accepts all, for changing it.\n */\n secret: string | string[];\n /** The name of the cookie. Defaults to `session`. */\n name?: string;\n /** Seconds until the session expires. Defaults to 7 days. */\n maxAge?: number;\n /** Other options of the cookie. */\n cookie?: Omit<CookieOptions, 'maxAge' | 'expires'>;\n}\n\nexport interface Session<T> {\n /** The data of the session, or undefined when there is none, it expired, or its signature does not match. */\n get(event: RequestEvent): Promise<T | undefined>;\n /** Replaces the data of the session, and starts its time again. */\n set(event: RequestEvent, data: T): Promise<void>;\n /** Changes some fields of the data, and returns the new data. */\n update(event: RequestEvent, change: Partial<T>): Promise<T>;\n /** Ends the session. */\n clear(event: RequestEvent): void;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst keys = new Map<string, Promise<CryptoKey>>();\n\nfunction key(secret: string): Promise<CryptoKey> {\n let promise = keys.get(secret);\n if (!promise) {\n promise = crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n );\n keys.set(secret, promise);\n }\n return promise;\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let text = '';\n for (const byte of bytes) {\n text += String.fromCharCode(byte);\n }\n return btoa(text).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array<ArrayBuffer> {\n const base64 = text.replace(/-/g, '+').replace(/_/g, '/');\n return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));\n}\n\n/**\n * A session in a signed cookie. The browser can read the data, but cannot\n * change it, so keep secrets out of it: store an ID, and look the rest up\n * on the server.\n *\n * ```ts\n * export const session = createSession<{ userId: string }>({ secret: process.env.SESSION_SECRET! });\n *\n * async function login(form: FormData) {\n * 'use server';\n * const event = getEvent();\n * await session.set(event, { userId: await checkPassword(form) });\n * }\n * ```\n */\nexport function createSession<T>(options: SessionOptions): Session<T> {\n const secrets = Array.isArray(options.secret) ? options.secret : [options.secret];\n let tooShort = secrets.length === 0;\n for (const secret of secrets) {\n if (secret.length < 32) {\n tooShort = true;\n break;\n }\n }\n if (tooShort) {\n throw new Error('A session secret needs at least 32 characters');\n }\n const name = options.name ?? 'session';\n const maxAge = options.maxAge ?? 7 * 24 * 60 * 60;\n\n async function read(event: RequestEvent): Promise<T | undefined> {\n const value = getCookies(event)[name];\n const dot = value?.lastIndexOf('.') ?? -1;\n if (!value || dot === -1) {\n return undefined;\n }\n const payload = value.slice(0, dot);\n let signature: Uint8Array<ArrayBuffer>;\n try {\n signature = fromBase64Url(value.slice(dot + 1));\n } catch {\n return undefined;\n }\n // Any of the secrets can have signed it, such as an older one while a secret changes.\n const pending: Promise<boolean>[] = [];\n for (const secret of secrets) {\n pending.push(\n (async () =>\n crypto.subtle.verify('HMAC', await key(secret), signature, encoder.encode(payload)))(),\n );\n }\n const checks = await Promise.all(pending);\n if (!checks.includes(true)) {\n return undefined;\n }\n try {\n const { d: data, e: expires } = JSON.parse(decoder.decode(fromBase64Url(payload))) as {\n d: T;\n e: number;\n };\n return expires > Date.now() ? data : undefined;\n } catch {\n return undefined;\n }\n }\n\n async function write(event: RequestEvent, data: T): Promise<void> {\n const payload = toBase64Url(\n encoder.encode(JSON.stringify({ d: data, e: Date.now() + maxAge * 1000 })),\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign('HMAC', await key(secrets[0]!), encoder.encode(payload)),\n );\n const value = `${payload}.${toBase64Url(signature)}`;\n // Browsers drop cookies over about 4 KB.\n if (value.length > 4000) {\n throw new Error(\n `The session is ${value.length} bytes, over the 4000 that a cookie can hold. Store an ID in it instead`,\n );\n }\n setCookie(event, name, value, { ...options.cookie, maxAge });\n }\n\n return {\n get: read,\n set: write,\n async update(event, change) {\n const data = { ...(await read(event)), ...change } as T;\n await write(event, data);\n return data;\n },\n clear: (event) =>\n deleteCookie(event, name, { path: options.cookie?.path, domain: options.cookie?.domain }),\n };\n}\n\n/**\n * The headers of a response for Node's `writeHead`, with each `set-cookie`\n * apart. `Object.fromEntries(headers)` joins them into one, which browsers\n * read as a single cookie.\n */\nexport function toNodeHeaders(headers: Headers): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = Object.fromEntries(headers);\n const cookies = headers.getSetCookie();\n if (cookies.length > 0) {\n result['set-cookie'] = cookies;\n }\n return result;\n}\n"],"mappings":";;AAsBA,SAAgB,aAAa,QAA+C;CAC1E,MAAM,SAAiC,CAAC;CACxC,KAAK,MAAM,SAAS,UAAU,GAAA,CAAI,MAAM,GAAG,GAAG;EAC5C,MAAM,QAAQ,KAAK,QAAQ,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GAIjF,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,KAAA;EACvC,QAAQ;GACN;EACF;CACF;CAEA,eAAe,MAAM,OAAqB,MAAwB;EAChE,MAAM,UAAU,YACd,QAAQ,OAAO,KAAK,UAAU;GAAE,GAAG;GAAM,GAAG,KAAK,IAAI,IAAI,SAAS;EAAK,CAAC,CAAC,CAC3E;EAIA,MAAM,QAAQ,GAAG,QAAQ,GAAG,YAAY,IAHlB,WACpB,MAAM,OAAO,OAAO,KAAK,QAAQ,MAAM,IAAI,QAAQ,EAAG,GAAG,QAAQ,OAAO,OAAO,CAAC,CAElC,CAAC;EAEjD,IAAI,MAAM,SAAS,KACjB,MAAM,IAAI,MACR,kBAAkB,MAAM,OAAO,wEACjC;EAEF,UAAU,OAAO,MAAM,OAAO;GAAE,GAAG,QAAQ;GAAQ;EAAO,CAAC;CAC7D;CAEA,OAAO;EACL,KAAK;EACL,KAAK;EACL,MAAM,OAAO,OAAO,QAAQ;GAC1B,MAAM,OAAO;IAAE,GAAI,MAAM,KAAK,KAAK;IAAI,GAAG;GAAO;GACjD,MAAM,MAAM,OAAO,IAAI;GACvB,OAAO;EACT;EACA,QAAQ,UACN,aAAa,OAAO,MAAM;GAAE,MAAM,QAAQ,QAAQ;GAAM,QAAQ,QAAQ,QAAQ;EAAO,CAAC;CAC5F;AACF;;;;;;AAOA,SAAgB,cAAc,SAAqD;CACjF,MAAM,SAA4C,OAAO,YAAY,OAAO;CAC5E,MAAM,UAAU,QAAQ,aAAa;CACrC,IAAI,QAAQ,SAAS,GACnB,OAAO,gBAAgB;CAEzB,OAAO;AACT"}
|
|
@@ -1,17 +1,19 @@
|
|
|
1
|
+
import { Jt as build, Qt as skew } from "./client-BvDsC6Qr.js";
|
|
1
2
|
import { n as trustedHTML, r as trustedScript } from "./skew-FRmAy9iy.js";
|
|
2
|
-
import { ct as skew, d as build } from "./client-C0UCNL3J.js";
|
|
3
3
|
//#region src/runtime/defer.ts
|
|
4
4
|
/** The nonce of a script. Browsers hide the attribute once the page loads, and keep the property. */
|
|
5
|
-
function
|
|
5
|
+
function readNonce(script) {
|
|
6
6
|
return script.nonce || script.getAttribute("nonce");
|
|
7
7
|
}
|
|
8
8
|
/** The Content Security Policy nonce of the page, which the scripts of the answer need to run. */
|
|
9
9
|
function pageNonce() {
|
|
10
10
|
for (const script of document.querySelectorAll("script")) {
|
|
11
|
-
const nonce =
|
|
11
|
+
const nonce = readNonce(script);
|
|
12
12
|
if (nonce) return nonce;
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
+
/** The templates whose bodies were asked for. */
|
|
16
|
+
const requested = /* @__PURE__ */ new WeakSet();
|
|
15
17
|
/**
|
|
16
18
|
* Asks the server for the body of the `#defer` block of a `<template
|
|
17
19
|
* b-defer>`, and puts it in place of the fallback. When the server cannot
|
|
@@ -19,6 +21,8 @@ function pageNonce() {
|
|
|
19
21
|
* that answers with the whole page, the fallback stays.
|
|
20
22
|
*/
|
|
21
23
|
async function loadDeferred(template) {
|
|
24
|
+
if (requested.has(template)) return;
|
|
25
|
+
requested.add(template);
|
|
22
26
|
const [, boundary, base] = template.getAttribute("b-defer").split(":");
|
|
23
27
|
const response = await fetch(location.href, { headers: {
|
|
24
28
|
"x-brumate-defer": `${boundary} ${template.getAttribute("b-b")}`,
|
|
@@ -49,4 +53,4 @@ async function loadDeferred(template) {
|
|
|
49
53
|
//#endregion
|
|
50
54
|
export { loadDeferred };
|
|
51
55
|
|
|
52
|
-
//# sourceMappingURL=defer-
|
|
56
|
+
//# sourceMappingURL=defer-CKWZLv2K.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"defer-CKWZLv2K.js","names":[],"sources":["../src/runtime/defer.ts"],"sourcesContent":["// Loads the body of a `#defer` block. The loader imports this module when\n// the block's trigger fires, so a page without `#defer` does not load it.\n//\n// The server renders the route again for the request and answers with what\n// it streams for a `#loading` body that is ready: the body in a\n// `<template b-l>`, the script that swaps it in, and its state records.\n// This module adds that markup to the page and runs its scripts, in order.\n\nimport { build, skew } from './client.ts';\nimport { trustedHTML, trustedScript } from './trusted.ts';\n/** The nonce of a script. Browsers hide the attribute once the page loads, and keep the property. */\nfunction readNonce(script: HTMLScriptElement): string | null {\n return script.nonce || script.getAttribute('nonce');\n}\n\n/** The Content Security Policy nonce of the page, which the scripts of the answer need to run. */\nfunction pageNonce(): string | undefined {\n for (const script of document.querySelectorAll('script')) {\n const nonce = readNonce(script);\n if (nonce) {\n return nonce;\n }\n }\n return undefined;\n}\n\n/** The templates whose bodies were asked for. */\nconst requested = new WeakSet<Element>();\n\n/**\n * Asks the server for the body of the `#defer` block of a `<template\n * b-defer>`, and puts it in place of the fallback. When the server cannot\n * render it, such as a page that changed since it loaded, or a static host\n * that answers with the whole page, the fallback stays.\n */\nexport async function loadDeferred(template: Element): Promise<void> {\n // Once, so the devtools can fire the trigger before the loader does.\n if (requested.has(template)) {\n return;\n }\n requested.add(template);\n const [, boundary, base] = template.getAttribute('b-defer')!.split(':') as [\n string,\n string,\n string,\n ];\n const response = await fetch(location.href, {\n headers: {\n 'x-brumate-defer': `${boundary} ${template.getAttribute('b-b')}`,\n 'x-brumate-base': base,\n ...(build === undefined ? {} : { 'x-brumate-build': build }),\n },\n });\n if (response.status === 409 && response.headers.get('x-brumate-build')) {\n // The site changed since the page loaded. The fallback stays, and the next page loads in full.\n skew('defer');\n return;\n }\n if (!response.ok || response.headers.get('x-brumate-defer') !== boundary) {\n return;\n }\n const parsed = document.createElement('template');\n parsed.innerHTML = trustedHTML(await response.text());\n const nonce = pageNonce();\n // A copy, because appending moves nodes out of the live list.\n for (const node of Array.from(parsed.content.childNodes)) {\n if (node.nodeName !== 'SCRIPT') {\n document.body.append(node);\n continue;\n }\n // A script from `innerHTML` does not run, so a copy goes in its place.\n const script = node as HTMLScriptElement;\n const copy = document.createElement('script');\n for (const attribute of script.attributes) {\n if (attribute.name !== 'nonce') {\n copy.setAttribute(attribute.name, attribute.value);\n }\n }\n if (nonce) {\n cop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