brumate 0.3.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.
Files changed (122) hide show
  1. package/README.md +2 -2
  2. package/check.d.ts +49 -0
  3. package/dist/{boot-C25Sa6vq.d.ts → boot-DLlRmD9z.d.ts} +8 -10
  4. package/dist/cli.js +275 -15
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-BvDsC6Qr.js +3463 -0
  7. package/dist/client-BvDsC6Qr.js.map +1 -0
  8. package/dist/{client-D0CqSxoO.d.ts → client-DBwL2wKQ.d.ts} +390 -181
  9. package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
  10. package/dist/client-routes-BtGpYCef.js.map +1 -0
  11. package/dist/{cookies-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
  12. package/dist/cookies-Cnbf4w-S.js.map +1 -0
  13. package/dist/{defer-BbD7JQhj.js → defer-CKWZLv2K.js} +4 -4
  14. package/dist/defer-CKWZLv2K.js.map +1 -0
  15. package/dist/{devtools-CQgD7NPB.js → devtools-4uTPwR_v.js} +56 -82
  16. package/dist/devtools-4uTPwR_v.js.map +1 -0
  17. package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-Be9pxYgv.js} +397 -333
  18. package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
  19. package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
  20. package/dist/events-LgLdp1R7.js.map +1 -0
  21. package/dist/features-CHY5Ekku.js +30 -0
  22. package/dist/features-CHY5Ekku.js.map +1 -0
  23. package/dist/files-WW4RlajL.js +506 -0
  24. package/dist/files-WW4RlajL.js.map +1 -0
  25. package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
  26. package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
  27. package/dist/forms-nXK7-Lv_.js.map +1 -0
  28. package/dist/highlight.js +31 -22
  29. package/dist/highlight.js.map +1 -1
  30. package/dist/{html-mNTKzaDD.js → html-BtKRyi7g.js} +86 -22
  31. package/dist/html-BtKRyi7g.js.map +1 -0
  32. package/dist/{html-Bq1rFxX_.d.ts → html-Bw9Qwu6F.d.ts} +20 -5
  33. package/dist/index.d.ts +96 -10
  34. package/dist/index.js +639 -104
  35. package/dist/index.js.map +1 -1
  36. package/dist/{inspect-BHpOw1LF.js → inspect-Y6y4uNZp.js} +3751 -676
  37. package/dist/inspect-Y6y4uNZp.js.map +1 -0
  38. package/dist/{loader-Dos_3NP0.js → loader-BjKGJzLN.js} +20 -14
  39. package/dist/loader-BjKGJzLN.js.map +1 -0
  40. package/dist/logo-DQ_OYhBi.js +10 -0
  41. package/dist/logo-DQ_OYhBi.js.map +1 -0
  42. package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
  43. package/dist/navigate-CfOr-TRF.js.map +1 -0
  44. package/dist/nesting-DA5vJw9X.js +265 -0
  45. package/dist/nesting-DA5vJw9X.js.map +1 -0
  46. package/dist/{produce-Doc91GkX.js → produce-B7X9ori9.js} +137 -9
  47. package/dist/produce-B7X9ori9.js.map +1 -0
  48. package/dist/{produce-D0V0ICkz.d.ts → produce-DIgHBVwL.d.ts} +39 -5
  49. package/dist/{rpc-ygMRPmN4.js → rpc-Q-XkLwFh.js} +11 -6
  50. package/dist/rpc-Q-XkLwFh.js.map +1 -0
  51. package/dist/runtime/batch.js +9 -7
  52. package/dist/runtime/batch.js.map +1 -1
  53. package/dist/runtime/client.d.ts +4 -4
  54. package/dist/runtime/client.js +4 -4
  55. package/dist/runtime/devtools.d.ts +11 -29
  56. package/dist/runtime/devtools.js +3 -1
  57. package/dist/runtime/env.js +14 -2
  58. package/dist/runtime/env.js.map +1 -1
  59. package/dist/runtime/events.d.ts +23 -1
  60. package/dist/runtime/events.js +1 -1
  61. package/dist/runtime/forms.d.ts +2 -2
  62. package/dist/runtime/forms.js +1 -1
  63. package/dist/runtime/hot.d.ts +1 -1
  64. package/dist/runtime/hot.js +5 -2
  65. package/dist/runtime/hot.js.map +1 -1
  66. package/dist/runtime/html.d.ts +2 -2
  67. package/dist/runtime/html.js +1 -1
  68. package/dist/runtime/loader.d.ts +2 -2
  69. package/dist/runtime/loader.js +2 -2
  70. package/dist/runtime/routes.js +4 -1
  71. package/dist/runtime/routes.js.map +1 -1
  72. package/dist/runtime/server.d.ts +5 -5
  73. package/dist/runtime/server.js +5 -5
  74. package/dist/runtime/signals.d.ts +38 -1
  75. package/dist/runtime/signals.js +33 -1
  76. package/dist/runtime/signals.js.map +1 -1
  77. package/dist/runtime/static-loader.d.ts +2 -2
  78. package/dist/runtime/static-loader.js +1 -1
  79. package/dist/runtime/testing.d.ts +18 -3
  80. package/dist/runtime/testing.js +150 -33
  81. package/dist/runtime/testing.js.map +1 -1
  82. package/dist/{server-DuFYRXrd.d.ts → server-BvPIg9pT.d.ts} +84 -22
  83. package/dist/{server-CxVDYE_V.js → server-DjyOVJtJ.js} +598 -164
  84. package/dist/server-DjyOVJtJ.js.map +1 -0
  85. package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
  86. package/dist/{static-loader-nZssh66R.js → static-loader-BZR17hSw.js} +78 -99
  87. package/dist/static-loader-BZR17hSw.js.map +1 -0
  88. package/dist/{stream-DCYZO4IF.js → stream-BP5AVmg5.js} +102 -16
  89. package/dist/stream-BP5AVmg5.js.map +1 -0
  90. package/dist/vite.d.ts +13 -20
  91. package/dist/vite.js +1890 -548
  92. package/dist/vite.js.map +1 -1
  93. package/elements.d.ts +951 -0
  94. package/forms/forms.brm.ts +3 -3
  95. package/package.json +12 -3
  96. package/skills/brumate/SKILL.md +58 -0
  97. package/skills/brumate/references/errors.md +2078 -0
  98. package/skills/brumate/references/events.md +117 -0
  99. package/skills/brumate/references/signals.md +61 -0
  100. package/skills/brumate/references/state.md +235 -0
  101. package/skills/brumate/references/syntax.md +250 -0
  102. package/types.d.ts +4 -4
  103. package/dist/client-BD6XT-s5.js +0 -1968
  104. package/dist/client-BD6XT-s5.js.map +0 -1
  105. package/dist/client-routes-JTbGtukf.js.map +0 -1
  106. package/dist/cookies-BzllthiF.js.map +0 -1
  107. package/dist/defer-BbD7JQhj.js.map +0 -1
  108. package/dist/devtools-CQgD7NPB.js.map +0 -1
  109. package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
  110. package/dist/events-CSs7OwIC.js.map +0 -1
  111. package/dist/files-BXSSrQgc.js +0 -205
  112. package/dist/files-BXSSrQgc.js.map +0 -1
  113. package/dist/forms-Bg-CwGqX.js.map +0 -1
  114. package/dist/html-mNTKzaDD.js.map +0 -1
  115. package/dist/inspect-BHpOw1LF.js.map +0 -1
  116. package/dist/loader-Dos_3NP0.js.map +0 -1
  117. package/dist/navigate-O78d_zGN.js.map +0 -1
  118. package/dist/produce-Doc91GkX.js.map +0 -1
  119. package/dist/rpc-ygMRPmN4.js.map +0 -1
  120. package/dist/server-CxVDYE_V.js.map +0 -1
  121. package/dist/static-loader-nZssh66R.js.map +0 -1
  122. package/dist/stream-DCYZO4IF.js.map +0 -1
@@ -1,205 +0,0 @@
1
- import { _ as functionId } from "./inspect-BHpOw1LF.js";
2
- import { parseSync } from "oxc-parser";
3
- import { readFile, readdir } from "node:fs/promises";
4
- import path from "node:path";
5
- //#region src/server-files.ts
6
- /** The import of the stubs, which call server functions with `rpc` of the core. */
7
- const CLIENT = "brumate/client";
8
- /** True for a file whose first statement is `'use server'`, after comments. */
9
- function hasUseServer(source) {
10
- return /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(['"])use server\1/.test(source);
11
- }
12
- /** True for a path that can be a file of server functions. */
13
- function isScriptFile(path) {
14
- return /\.[cm]?[jt]sx?$/.test(path) && !path.endsWith(".d.ts") && !/\.brm\.[cm]?[jt]s$/.test(path);
15
- }
16
- /**
17
- * Tells a value that the file exports as a function: a function expression,
18
- * or a call of `cached` or `idempotent` of `brumate/server`, which return a function.
19
- */
20
- function functionTest(program) {
21
- const wrappers = /* @__PURE__ */ new Set();
22
- for (const statement of program.body) if (statement.type === "ImportDeclaration" && statement.source.value === "brumate/server") {
23
- for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && (specifier.imported.name === "cached" || specifier.imported.name === "idempotent")) wrappers.add(specifier.local.name);
24
- }
25
- return (node) => {
26
- if (node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression") return true;
27
- const callee = node?.type === "CallExpression" ? node.callee : void 0;
28
- return callee?.type === "Identifier" && wrappers.has(callee.name);
29
- };
30
- }
31
- /**
32
- * The names of the functions that a file of server functions exports.
33
- * Throws for an export that is not a function, because the browser can only
34
- * call a server function through its stub.
35
- */
36
- function serverExports(source, filename) {
37
- const { program, errors } = parseSync(filename, source, { lang: "ts" });
38
- if (errors[0]) throw new Error(`${errors[0].message} (${filename})`);
39
- const functions = /* @__PURE__ */ new Set();
40
- const values = /* @__PURE__ */ new Set();
41
- const local = /* @__PURE__ */ new Map();
42
- const isFunction = functionTest(program);
43
- for (const statement of program.body) {
44
- const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
45
- if (declaration?.type === "FunctionDeclaration" && declaration.id) local.set(declaration.id.name, "function");
46
- else if (declaration?.type === "VariableDeclaration") {
47
- for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier") local.set(declarator.id.name, isFunction(declarator.init) ? "function" : "value");
48
- }
49
- }
50
- for (const statement of program.body) if (statement.type === "ExportDefaultDeclaration") {
51
- const value = statement.declaration;
52
- if (value.type === "FunctionDeclaration" || isFunction(value)) functions.add("default");
53
- else values.add("default");
54
- } else if (statement.type === "ExportNamedDeclaration") {
55
- if (statement.exportKind === "type") continue;
56
- const declaration = statement.declaration;
57
- if (declaration?.type === "FunctionDeclaration" && declaration.id) functions.add(declaration.id.name);
58
- else if (declaration?.type === "VariableDeclaration") {
59
- for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier") (isFunction(declarator.init) ? functions : values).add(declarator.id.name);
60
- } else if (declaration && !declaration.type.startsWith("TS")) values.add("a class");
61
- for (const specifier of statement.specifiers) {
62
- if (specifier.exportKind === "type") continue;
63
- const name = specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value;
64
- const from = specifier.local.type === "Identifier" ? specifier.local.name : "";
65
- (local.get(from) === "function" && !statement.source ? functions : values).add(name);
66
- }
67
- } else if (statement.type === "ExportAllDeclaration") values.add("*");
68
- if (values.size > 0) throw new Error(`A 'use server' file exports only functions, because the browser calls them on the server. ${[...values].join(", ")} of ${filename} is not one`);
69
- functions.delete(MIDDLEWARE);
70
- return [...functions];
71
- }
72
- /** The export of a file of server functions that runs before each of them. */
73
- const MIDDLEWARE = "middleware";
74
- /** True if a file of server functions exports `middleware`. */
75
- function hasServerMiddleware(source, filename) {
76
- const { program } = parseSync(filename, source, { lang: "ts" });
77
- for (const statement of program.body) {
78
- if (statement.type !== "ExportNamedDeclaration" || statement.exportKind === "type") continue;
79
- const declaration = statement.declaration;
80
- if (declaration?.type === "FunctionDeclaration" && declaration.id?.name === "middleware") return true;
81
- if (declaration?.type === "VariableDeclaration" && declaration.declarations.some((declarator) => declarator.id.type === "Identifier" && declarator.id.name === "middleware")) return true;
82
- if (statement.specifiers.some((specifier) => specifier.exportKind !== "type" && (specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === "middleware")) return true;
83
- }
84
- return false;
85
- }
86
- /** The module that the browser gets in place of a file of server functions. */
87
- function serverStubs(source, filename, id, hideNames = false) {
88
- const lines = [`import { rpc } from ${JSON.stringify(CLIENT)};`];
89
- for (const name of serverExports(source, filename)) {
90
- const call = `(...args) => rpc(${JSON.stringify(functionId(id, name, hideNames))}, args)`;
91
- lines.push(name === "default" ? `export default ${call};` : `export const ${name} = ${call};`);
92
- }
93
- return `${lines.join("\n")}\n`;
94
- }
95
- /**
96
- * The module that the server runs for a file of server functions: the file,
97
- * with each exported function wrapped, so its calls while a page renders
98
- * share a result when their arguments are the same. Offsets stay the same.
99
- */
100
- function serverModule(source, filename, id) {
101
- const { program } = parseSync(filename, source, { lang: "ts" });
102
- const isFunction = functionTest(program);
103
- const wrapped = /* @__PURE__ */ new Map();
104
- const declarations = /* @__PURE__ */ new Map();
105
- let code = source;
106
- for (const statement of program.body) {
107
- const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
108
- if (declaration?.type === "FunctionDeclaration" && declaration.id) declarations.set(declaration.id.name, "function");
109
- else if (declaration?.type === "VariableDeclaration") {
110
- for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier" && isFunction(declarator.init)) declarations.set(declarator.id.name, "const");
111
- }
112
- }
113
- const letOf = (declaration) => {
114
- if (declaration.kind === "const") code = `${code.slice(0, declaration.start)}let ${code.slice(declaration.start + 5)}`;
115
- };
116
- for (const statement of program.body) {
117
- if (statement.type !== "ExportNamedDeclaration" || statement.source || statement.exportKind === "type") continue;
118
- const declaration = statement.declaration;
119
- if (declaration?.type === "FunctionDeclaration" && declaration.id) wrapped.set(declaration.id.name, declaration.id.name);
120
- else if (declaration?.type === "VariableDeclaration") {
121
- for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier" && isFunction(declarator.init)) {
122
- wrapped.set(declarator.id.name, declarator.id.name);
123
- letOf(declaration);
124
- }
125
- }
126
- for (const specifier of statement.specifiers) {
127
- const local = specifier.local.type === "Identifier" ? specifier.local.name : "";
128
- const exported = specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value;
129
- if (declarations.has(local)) wrapped.set(local, exported);
130
- }
131
- }
132
- for (const statement of program.body) if (statement.type === "VariableDeclaration") {
133
- for (const declarator of statement.declarations) if (declarator.id.type === "Identifier" && wrapped.has(declarator.id.name)) letOf(statement);
134
- }
135
- if (wrapped.size === 0) return source;
136
- const lines = ["import { dedupe as __brumateDedupe } from 'brumate/server';"];
137
- for (const [local, exported] of wrapped) lines.push(`${local} = __brumateDedupe(${local}, ${JSON.stringify(`${id}#${exported}`)});`);
138
- return `${code}\n${lines.join("\n")}\n`;
139
- }
140
- //#endregion
141
- //#region src/files.ts
142
- /** Skips `node_modules`, `dist` and hidden directories when looking for `.brm` files. */
143
- function defaultExclude(directory) {
144
- return directory === "node_modules" || directory === "dist" || directory.startsWith(".");
145
- }
146
- /** Finds every `.brm` file under a directory, as absolute paths with forward slashes. */
147
- async function findFiles(root, exclude) {
148
- const result = [];
149
- const visit = async (directory) => {
150
- const directories = [];
151
- for (const entry of await readdir(directory, { withFileTypes: true })) {
152
- const file = path.join(directory, entry.name);
153
- if (entry.isDirectory()) {
154
- if (!exclude(entry.name)) directories.push(visit(file));
155
- } else if (entry.name.endsWith(".brm")) result.push(file.split(path.sep).join("/"));
156
- }
157
- await Promise.all(directories);
158
- };
159
- await visit(root);
160
- return result.toSorted();
161
- }
162
- /**
163
- * Finds every file of server functions under a directory: a script whose
164
- * first statement is `'use server'`.
165
- */
166
- async function findServerFiles(root, exclude) {
167
- const result = [];
168
- const visit = async (directory) => {
169
- const pending = [];
170
- for (const entry of await readdir(directory, { withFileTypes: true })) {
171
- const file = path.join(directory, entry.name);
172
- if (entry.isDirectory()) {
173
- if (!exclude(entry.name)) pending.push(visit(file));
174
- } else if (isScriptFile(entry.name)) pending.push(readFile(file, "utf8").then((source) => {
175
- if (hasUseServer(source)) result.push(file.split(path.sep).join("/"));
176
- }));
177
- }
178
- await Promise.all(pending);
179
- };
180
- await visit(root);
181
- return result.toSorted();
182
- }
183
- /**
184
- * Finds every script under a directory, such as `.ts` and `.brm.ts` files, as
185
- * absolute paths with forward slashes, without reading them.
186
- */
187
- async function findScripts(root, exclude) {
188
- const result = [];
189
- const visit = async (directory) => {
190
- const directories = [];
191
- for (const entry of await readdir(directory, { withFileTypes: true })) {
192
- const file = path.join(directory, entry.name);
193
- if (entry.isDirectory()) {
194
- if (!exclude(entry.name)) directories.push(visit(file));
195
- } else if (/\.[cm]?[jt]sx?$/.test(entry.name) && !entry.name.endsWith(".d.ts")) result.push(file.split(path.sep).join("/"));
196
- }
197
- await Promise.all(directories);
198
- };
199
- await visit(root);
200
- return result.toSorted();
201
- }
202
- //#endregion
203
- export { hasServerMiddleware as a, serverExports as c, findServerFiles as i, serverModule as l, findFiles as n, hasUseServer as o, findScripts as r, isScriptFile as s, defaultExclude as t, serverStubs as u };
204
-
205
- //# sourceMappingURL=files-BXSSrQgc.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"files-BXSSrQgc.js","names":[],"sources":["../src/server-files.ts","../src/files.ts"],"sourcesContent":["// Files of server functions. A `.ts` or `.js` file whose first statement is\n// `'use server'` holds functions that only run on the server. Its exports are\n// server functions: the browser gets a stub for each one, which calls the\n// server, and the code of the file never ships.\n\nimport { parseSync } from 'oxc-parser';\nimport { functionId } from './plan.ts';\n\n/** The import of the stubs, which call server functions with `rpc` of the core. */\nconst CLIENT = 'brumate/client';\n\n/** True for a file whose first statement is `'use server'`, after comments. */\nexport function hasUseServer(source: string): boolean {\n return /^(?:\\s|\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/)*(['\"])use server\\1/.test(source);\n}\n\n/** True for a path that can be a file of server functions. */\nexport function isScriptFile(path: string): boolean {\n return (\n /\\.[cm]?[jt]sx?$/.test(path) && !path.endsWith('.d.ts') && !/\\.brm\\.[cm]?[jt]s$/.test(path)\n );\n}\n\n/** True for a function expression or an arrow. */\ntype Program = ReturnType<typeof parseSync>['program'];\ntype Node = Program['body'][number] | { type: string; callee?: unknown } | null | undefined;\n\n/**\n * Tells a value that the file exports as a function: a function expression,\n * or a call of `cached` or `idempotent` of `brumate/server`, which return a function.\n */\nfunction functionTest(program: Program): (node: Node) => boolean {\n const wrappers = new Set<string>();\n for (const statement of program.body) {\n if (statement.type === 'ImportDeclaration' && statement.source.value === 'brumate/server') {\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n specifier.imported.type === 'Identifier' &&\n (specifier.imported.name === 'cached' || specifier.imported.name === 'idempotent')\n ) {\n wrappers.add(specifier.local.name);\n }\n }\n }\n }\n return (node) => {\n if (node?.type === 'ArrowFunctionExpression' || node?.type === 'FunctionExpression') {\n return true;\n }\n const callee =\n node?.type === 'CallExpression'\n ? (node.callee as { type: string; name?: string })\n : undefined;\n return callee?.type === 'Identifier' && wrappers.has(callee.name!);\n };\n}\n\n/**\n * The names of the functions that a file of server functions exports.\n * Throws for an export that is not a function, because the browser can only\n * call a server function through its stub.\n */\nexport function serverExports(source: string, filename: string): string[] {\n const { program, errors } = parseSync(filename, source, { lang: 'ts' });\n if (errors[0]) {\n throw new Error(`${errors[0].message} (${filename})`);\n }\n const functions = new Set<string>();\n const values = new Set<string>();\n const local = new Map<string, 'function' | 'value'>();\n const isFunction = functionTest(program);\n for (const statement of program.body) {\n const declaration =\n statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n local.set(declaration.id.name, 'function');\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier') {\n local.set(declarator.id.name, isFunction(declarator.init) ? 'function' : 'value');\n }\n }\n }\n }\n for (const statement of program.body) {\n if (statement.type === 'ExportDefaultDeclaration') {\n const value = statement.declaration;\n if (value.type === 'FunctionDeclaration' || isFunction(value)) {\n functions.add('default');\n } else {\n values.add('default');\n }\n } else if (statement.type === 'ExportNamedDeclaration') {\n if (statement.exportKind === 'type') {\n continue;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n functions.add(declaration.id.name);\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier') {\n (isFunction(declarator.init) ? functions : values).add(declarator.id.name);\n }\n }\n } else if (declaration && !declaration.type.startsWith('TS')) {\n values.add('a class');\n }\n for (const specifier of statement.specifiers) {\n if (specifier.exportKind === 'type') {\n continue;\n }\n const name =\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value;\n const from = specifier.local.type === 'Identifier' ? specifier.local.name : '';\n (local.get(from) === 'function' && !statement.source ? functions : values).add(name);\n }\n } else if (statement.type === 'ExportAllDeclaration') {\n values.add('*');\n }\n }\n if (values.size > 0) {\n throw new Error(\n `A 'use server' file exports only functions, because the browser calls them on the server. ${[...values].join(', ')} of ${filename} is not one`,\n );\n }\n // The middleware of the file runs before its functions. The browser cannot call it.\n functions.delete(MIDDLEWARE);\n return [...functions];\n}\n\n/** The export of a file of server functions that runs before each of them. */\nexport const MIDDLEWARE = 'middleware';\n\n/** True if a file of server functions exports `middleware`. */\nexport function hasServerMiddleware(source: string, filename: string): boolean {\n const { program } = parseSync(filename, source, { lang: 'ts' });\n for (const statement of program.body) {\n if (statement.type !== 'ExportNamedDeclaration' || statement.exportKind === 'type') {\n continue;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id?.name === MIDDLEWARE) {\n return true;\n }\n if (\n declaration?.type === 'VariableDeclaration' &&\n declaration.declarations.some(\n (declarator) => declarator.id.type === 'Identifier' && declarator.id.name === MIDDLEWARE,\n )\n ) {\n return true;\n }\n if (\n statement.specifiers.some(\n (specifier) =>\n specifier.exportKind !== 'type' &&\n (specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value) === MIDDLEWARE,\n )\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** The module that the browser gets in place of a file of server functions. */\nexport function serverStubs(\n source: string,\n filename: string,\n id: string,\n hideNames = false,\n): string {\n const lines = [`import { rpc } from ${JSON.stringify(CLIENT)};`];\n for (const name of serverExports(source, filename)) {\n const call = `(...args) => rpc(${JSON.stringify(functionId(id, name, hideNames))}, args)`;\n lines.push(name === 'default' ? `export default ${call};` : `export const ${name} = ${call};`);\n }\n return `${lines.join('\\n')}\\n`;\n}\n\n/**\n * The module that the server runs for a file of server functions: the file,\n * with each exported function wrapped, so its calls while a page renders\n * share a result when their arguments are the same. Offsets stay the same.\n */\nexport function serverModule(source: string, filename: string, id: string): string {\n const { program } = parseSync(filename, source, { lang: 'ts' });\n const isFunction = functionTest(program);\n // Local names of exported functions, with the name that each is exported as.\n const wrapped = new Map<string, string>();\n const declarations = new Map<string, 'function' | 'const'>();\n let code = source;\n for (const statement of program.body) {\n const declaration =\n statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n declarations.set(declaration.id.name, 'function');\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier' && isFunction(declarator.init)) {\n declarations.set(declarator.id.name, 'const');\n }\n }\n }\n }\n const letOf = (declaration: { start: number; kind: string }): void => {\n // `const` becomes `let `, so the function can be wrapped and offsets stay the same.\n if (declaration.kind === 'const') {\n code = `${code.slice(0, declaration.start)}let ${code.slice(declaration.start + 5)}`;\n }\n };\n for (const statement of program.body) {\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.source ||\n statement.exportKind === 'type'\n ) {\n continue;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'FunctionDeclaration' && declaration.id) {\n wrapped.set(declaration.id.name, declaration.id.name);\n } else if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === 'Identifier' && isFunction(declarator.init)) {\n wrapped.set(declarator.id.name, declarator.id.name);\n letOf(declaration);\n }\n }\n }\n for (const specifier of statement.specifiers) {\n const local = specifier.local.type === 'Identifier' ? specifier.local.name : '';\n const exported =\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value;\n if (declarations.has(local)) {\n wrapped.set(local, exported);\n }\n }\n }\n // A `const` arrow that `export { name }` exports is declared with `let` too.\n for (const statement of program.body) {\n if (statement.type === 'VariableDeclaration') {\n for (const declarator of statement.declarations) {\n if (declarator.id.type === 'Identifier' && wrapped.has(declarator.id.name)) {\n letOf(statement);\n }\n }\n }\n }\n if (wrapped.size === 0) {\n return source;\n }\n const lines = [\"import { dedupe as __brumateDedupe } from 'brumate/server';\"];\n for (const [local, exported] of wrapped) {\n lines.push(`${local} = __brumateDedupe(${local}, ${JSON.stringify(`${id}#${exported}`)});`);\n }\n return `${code}\\n${lines.join('\\n')}\\n`;\n}\n","import { readFile, readdir } from 'node:fs/promises';\nimport path from 'node:path';\nimport { hasUseServer, isScriptFile } from './server-files.ts';\n\n/** Skips `node_modules`, `dist` and hidden directories when looking for `.brm` files. */\nexport function defaultExclude(directory: string): boolean {\n return directory === 'node_modules' || directory === 'dist' || directory.startsWith('.');\n}\n\n/** Finds every `.brm` file under a directory, as absolute paths with forward slashes. */\nexport async function findFiles(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const directories: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n directories.push(visit(file));\n }\n } else if (entry.name.endsWith('.brm')) {\n result.push(file.split(path.sep).join('/'));\n }\n }\n await Promise.all(directories);\n };\n await visit(root);\n return result.toSorted();\n}\n\n/**\n * Finds every file of server functions under a directory: a script whose\n * first statement is `'use server'`.\n */\nexport async function findServerFiles(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const pending: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n pending.push(visit(file));\n }\n } else if (isScriptFile(entry.name)) {\n pending.push(\n readFile(file, 'utf8').then((source) => {\n if (hasUseServer(source)) {\n result.push(file.split(path.sep).join('/'));\n }\n }),\n );\n }\n }\n await Promise.all(pending);\n };\n await visit(root);\n return result.toSorted();\n}\n\n/**\n * Finds every script under a directory, such as `.ts` and `.brm.ts` files, as\n * absolute paths with forward slashes, without reading them.\n */\nexport async function findScripts(\n root: string,\n exclude: (directory: string) => boolean,\n): Promise<string[]> {\n const result: string[] = [];\n const visit = async (directory: string): Promise<void> => {\n const directories: Promise<void>[] = [];\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const file = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n if (!exclude(entry.name)) {\n directories.push(visit(file));\n }\n } else if (/\\.[cm]?[jt]sx?$/.test(entry.name) && !entry.name.endsWith('.d.ts')) {\n result.push(file.split(path.sep).join('/'));\n }\n }\n await Promise.all(directories);\n };\n await visit(root);\n return result.toSorted();\n}\n"],"mappings":";;;;;;AASA,MAAM,SAAS;;AAGf,SAAgB,aAAa,QAAyB;CACpD,OAAO,2DAA2D,KAAK,MAAM;AAC/E;;AAGA,SAAgB,aAAa,MAAuB;CAClD,OACE,kBAAkB,KAAK,IAAI,KAAK,CAAC,KAAK,SAAS,OAAO,KAAK,CAAC,qBAAqB,KAAK,IAAI;AAE9F;;;;;AAUA,SAAS,aAAa,SAA2C;CAC/D,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,aAAa,QAAQ,MAC9B,IAAI,UAAU,SAAS,uBAAuB,UAAU,OAAO,UAAU,kBAClE;OAAA,MAAM,aAAa,UAAU,YAChC,IACE,UAAU,SAAS,qBACnB,UAAU,SAAS,SAAS,iBAC3B,UAAU,SAAS,SAAS,YAAY,UAAU,SAAS,SAAS,eAErE,SAAS,IAAI,UAAU,MAAM,IAAI;CAAA;CAKzC,QAAQ,SAAS;EACf,IAAI,MAAM,SAAS,6BAA6B,MAAM,SAAS,sBAC7D,OAAO;EAET,MAAM,SACJ,MAAM,SAAS,mBACV,KAAK,SACN,KAAA;EACN,OAAO,QAAQ,SAAS,gBAAgB,SAAS,IAAI,OAAO,IAAK;CACnE;AACF;;;;;;AAOA,SAAgB,cAAc,QAAgB,UAA4B;CACxE,MAAM,EAAE,SAAS,WAAW,UAAU,UAAU,QAAQ,EAAE,MAAM,KAAK,CAAC;CACtE,IAAI,OAA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M,KAAK,SAAS,OAAO,GAC3E,OAAO,KAAK,KAAK,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;EAE9C;EACA,MAAM,QAAQ,IAAI,WAAW;CAC/B;CACA,MAAM,MAAM,IAAI;CAChB,OAAO,OAAO,SAAS;AACzB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"forms-Bg-CwGqX.js","names":[],"sources":["../src/runtime/forms.ts"],"sourcesContent":["// The parts of progressive forms that the server and the browser share: the\n// paths of field names, intents, the reply of a submission, and the state of\n// the fields that `createForm` shows. Nothing here reads the server, so the\n// code of `brumate/forms` can run it in the browser.\n\n/** A part of the path of a field: a key of an object, or an index of a list. */\nexport type PathSegment = string | number;\n\n/** The name of the submit button that holds an intent. */\nexport const INTENT = '__intent';\n\n/** The largest index of a list item in a field name, so a form cannot make a huge array. */\nexport const MAX_INDEX = 999;\n\n/** Names that would change the prototype of an object, or reach the one of its constructor. */\nexport const FORBIDDEN: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * The path of a field name: `items[0].name` is `['items', 0, 'name']`.\n * Dots separate keys, and `[n]` is the index of a list item. A number\n * between dots stays a key. Undefined for a name that is not a path, such\n * as one with an empty key, an index above `MAX_INDEX`, or a key such as\n * `__proto__`.\n */\nexport function parsePath(name: string): PathSegment[] | undefined {\n const path: PathSegment[] = [];\n for (const part of name.split('.')) {\n const match = /^([^[\\]]+)((?:\\[\\d+\\])*)$/.exec(part);\n if (!match || FORBIDDEN.has(match[1]!)) {\n return undefined;\n }\n path.push(match[1]!);\n for (const index of match[2]!.matchAll(/\\[(\\d+)\\]/g)) {\n const value = Number(index[1]);\n if (value > MAX_INDEX || (index[1]!.length > 1 && index[1]!.startsWith('0'))) {\n return undefined;\n }\n path.push(value);\n }\n }\n return path;\n}\n\n/** The field name of a path: `['items', 0, 'name']` is `items[0].name`. */\nexport function formatPath(path: readonly PathSegment[]): string {\n let name = '';\n for (const segment of path) {\n if (typeof segment === 'number') {\n name += `[${segment}]`;\n } else {\n name += name ? `.${segment}` : segment;\n }\n }\n return name;\n}\n\n/** The value at a path, or undefined when a part of the path is missing. */\nexport function getAt(value: unknown, path: readonly PathSegment[]): unknown {\n let current = value;\n for (const segment of path) {\n if (typeof current !== 'object' || current === null || !Object.hasOwn(current, segment)) {\n return undefined;\n }\n current = (current as Record<PathSegment, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * A copy of `value` with `next` at the path. The objects and lists along the\n * path are copied, and the others are shared. A missing part becomes a list\n * for an index and an object for a key.\n */\nexport function setAt(value: unknown, path: readonly PathSegment[], next: unknown): unknown {\n if (path.length === 0) {\n return next;\n }\n const [segment, ...rest] = path as [PathSegment, ...PathSegment[]];\n let copy: Record<PathSegment, unknown> | unknown[];\n if (Array.isArray(value)) {\n copy = [...(value as unknown[])];\n } else if (typeof value === 'object' && value !== null) {\n copy = { ...value };\n } else {\n copy = typeof segment === 'number' ? [] : {};\n }\n const child = Object.hasOwn(copy, segment)\n ? (copy as Record<PathSegment, unknown>)[segment]\n : undefined;\n (copy as Record<PathSegment, unknown>)[segment] = setAt(child, rest, next);\n return copy;\n}\n\n/** A problem that a schema found in the values of a form. */\nexport interface FormIssue {\n message: string;\n path?: PathSegment[];\n}\n\n/** The errors of a form: those of each field by field name, and those of the whole form. */\nexport interface FormErrors {\n errors: Record<string, string[]>;\n formErrors: string[];\n}\n\n/**\n * Turns the entries of a form into a plain object:\n *\n * - A name that appears once holds its value.\n * - A name that appears more than once holds an array of its values.\n * - A name that ends with `[]` always holds an array, under the name without `[]`.\n * - Dots nest objects: `address.city` is `{ address: { city } }`.\n * - An index in brackets makes a list: `items[0].name` is `{ items: [{ name }] }`.\n * - Values stay strings and files.\n *\n * A name with an empty part, a part such as `__proto__`, an index above\n * 999, or one that needs an object where another field holds a value, is\n * an issue, and the schema does not run.\n */\nexport function formValues(\n form: FormData,\n skip?: (name: string) => boolean,\n):\n | { value: Record<string, unknown>; issues?: undefined }\n | { value?: undefined; issues: FormIssue[] } {\n const root: Record<string, unknown> = {};\n // The objects and lists of items that this function made, so a field value is never taken for one.\n const containers = new Set<unknown>([root]);\n // The arrays of the values of a repeated name.\n const repeated = new Set<unknown>();\n const issues: FormIssue[] = [];\n for (const [name, value] of form) {\n if (skip?.(name)) {\n continue;\n }\n const list = name.endsWith('[]');\n const parts = parsePath(list ? name.slice(0, -2) : name);\n if (!parts) {\n issues.push({ message: 'The form has a field name that is not allowed' });\n continue;\n }\n let target = root as Record<PathSegment, unknown>;\n let conflict = false;\n for (const [index, part] of parts.slice(0, -1).entries()) {\n const next = Object.hasOwn(target, part) ? target[part] : undefined;\n // A list takes only indexes, and an object only keys.\n if (Array.isArray(target) !== (typeof part === 'number')) {\n conflict = true;\n break;\n }\n if (next === undefined) {\n const child = typeof parts[index + 1] === 'number' ? [] : {};\n containers.add(child);\n target[part] = child;\n target = child as Record<PathSegment, unknown>;\n } else if (containers.has(next)) {\n target = next as Record<PathSegment, unknown>;\n } else {\n conflict = true;\n break;\n }\n }\n const last = parts.at(-1)!;\n const current = Object.hasOwn(target, last) ? target[last] : undefined;\n if (\n conflict ||\n containers.has(current) ||\n Array.isArray(target) !== (typeof last === 'number')\n ) {\n issues.push({ message: `Field \"${name}\" conflicts with another field`, path: parts });\n } else if (repeated.has(current)) {\n (current as unknown[]).push(value);\n } else if (current !== undefined || list) {\n const values = current === undefined ? [value] : [current, value];\n repeated.add(values);\n target[last] = values;\n } else {\n target[last] = value;\n }\n }\n return issues.length > 0 ? { issues } : { value: root };\n}\n\n/** The errors of issues by field name, such as `items[0].name`, and those of the whole form. */\nexport function groupIssues(issues: readonly FormIssue[]): FormErrors {\n const errors: Record<string, string[]> = {};\n const formErrors: string[] = [];\n for (const issue of issues) {\n const path = issue.path ?? [];\n const name = path.length > 0 && typeof path[0] === 'string' ? formatPath(path) : '';\n if (name === '' || !parsePath(name)) {\n formErrors.push(issue.message);\n } else {\n (Object.hasOwn(errors, name) ? errors[name]! : (errors[name] = [])).push(issue.message);\n }\n }\n return { errors, formErrors };\n}\n\n/** The schema of a form, as `createForm` reads it: a Standard Schema of version 1. */\ninterface FormSchema {\n readonly '~standard': {\n readonly validate: (value: unknown) => unknown;\n };\n}\n\n/**\n * Validates the fields of a form in the browser, with the schema that the\n * server uses, and groups the errors as `reply` does.\n */\nexport async function validateForm(schema: FormSchema, form: FormData): Promise<FormErrors> {\n const values = formValues(form, (name) => name === INTENT);\n return values.issues ? groupIssues(values.issues) : validateValues(schema, values.value);\n}\n\n/** Validates the values of a form in the browser, and groups the errors as `reply` does. */\nexport async function validateValues(schema: FormSchema, value: unknown): Promise<FormErrors> {\n const result = (await schema['~standard'].validate(value)) as {\n issues?: readonly { message: string; path?: readonly (PathSegment | { key: PropertyKey })[] }[];\n };\n return groupIssues(\n (result.issues ?? []).map((issue) => ({\n message: String(issue.message),\n path: issue.path?.map((segment) => {\n const key = typeof segment === 'object' ? segment.key : segment;\n return typeof key === 'number' ? key : String(key);\n }),\n })),\n );\n}\n\n/**\n * The errors that the browser found since the last reply: the fields that\n * the user left or changed, and the errors of the form at that time.\n */\nexport interface CheckedErrors extends FormErrors {\n /** The ID of the reply that the check came after, or undefined before the first submit. */\n reply: string | undefined;\n /** The names of the fields that the user left, whose errors show. */\n touched: string[];\n /** True when the errors of every field show, as after a submit. */\n all: boolean;\n}\n\n/**\n * A change that a submit button asks for, instead of a submit. The server\n * applies it to the posted values, and answers with them.\n *\n * - `insert` adds an item to a list, at `index` or at its end.\n * - `remove` removes the item at `index`.\n * - `reorder` moves the item at `from` to `to`.\n * - `reset` sets a field, or the whole form, back to its default value.\n * - `validate` answers with the errors of one field.\n */\nexport type Intent =\n | { type: 'insert'; name: string; index?: number; defaultValue?: unknown }\n | { type: 'remove'; name: string; index: number }\n | { type: 'reorder'; name: string; from: number; to: number }\n | { type: 'reset'; name?: string }\n | { type: 'validate'; name: string };\n\nconst isIndex = (value: unknown): value is number =>\n Number.isInteger(value) && (value as number) >= 0 && (value as number) <= MAX_INDEX;\n\n/**\n * Reads the intent that a submit button posted, as JSON. Undefined for a\n * value that is not an intent, such as one with a name that is not a path.\n */\nexport function parseIntent(text: string): Intent | undefined {\n let intent: unknown;\n try {\n intent = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof intent !== 'object' || intent === null) {\n return undefined;\n }\n const { type, name, index, from, to } = intent as Record<string, unknown>;\n if (name !== undefined && (typeof name !== 'string' || !parsePath(name))) {\n return undefined;\n }\n switch (type) {\n case 'insert':\n return name !== undefined && (index === undefined || isIndex(index))\n ? (intent as Intent)\n : undefined;\n case 'remove':\n return name !== undefined && isIndex(index) ? (intent as Intent) : undefined;\n case 'reorder':\n return name !== undefined && isIndex(from) && isIndex(to) ? (intent as Intent) : undefined;\n case 'reset':\n return intent as Intent;\n case 'validate':\n return name !== undefined ? (intent as Intent) : undefined;\n default:\n return undefined;\n }\n}\n\n/** The value of a submit button that posts an intent. */\nexport function intentValue(intent: Intent): string {\n return JSON.stringify(intent);\n}\n\n/**\n * Applies an intent to the posted values. Returns the new values, and the\n * name of the list that it changed. Undefined when the intent does not fit\n * the values, such as an index past the end of the list.\n */\nexport function applyIntent(\n value: unknown,\n intent: Intent,\n): { value: unknown; list?: string } | undefined {\n if (intent.type === 'validate') {\n return { value };\n }\n if (intent.type === 'reset') {\n return {\n value:\n intent.name === undefined ? undefined : setAt(value, parsePath(intent.name)!, undefined),\n };\n }\n const path = parsePath(intent.name)!;\n const current = getAt(value, path) ?? [];\n if (!Array.isArray(current)) {\n return undefined;\n }\n const items = [...current];\n if (intent.type === 'insert') {\n const index = intent.index ?? items.length;\n if (index > items.length || items.length > MAX_INDEX) {\n return undefined;\n }\n items.splice(index, 0, intent.defaultValue);\n } else if (intent.type === 'remove') {\n if (intent.index >= items.length) {\n return undefined;\n }\n items.splice(intent.index, 1);\n } else {\n if (intent.from >= items.length || intent.to >= items.length) {\n return undefined;\n }\n items.splice(intent.to, 0, ...items.splice(intent.from, 1));\n }\n return { value: setAt(value, path, items), list: intent.name };\n}\n\n/**\n * What a server function of a form answers, for `createForm` to show. It is\n * plain data, so it goes through `$action` and the state of the page.\n */\nexport interface SubmissionResult {\n /** `success` when the values passed the schema, `error` when not, and `intent` for an intent. */\n status: 'success' | 'error' | 'intent';\n /**\n * The values as posted, after the intent, for the fields to show again.\n * Files and hidden fields are left out. Undefined after a reset, so the\n * fields show their default values.\n */\n value?: unknown;\n /** The errors of each field, by field name, such as `items[0].name`. */\n errors: Record<string, string[]>;\n /** The errors of the whole form. */\n formErrors: string[];\n /**\n * The keys of the items of a list that an intent changed, by field name.\n * They are new, so `#for … by` renders the items again, and an element\n * never shows another item. Other lists keep the index as the key.\n */\n keys: Record<string, string[]>;\n /** True when the form goes back to its default values, such as after a save. */\n reset?: boolean;\n /** A new ID for each reply, which keys of new items start with. */\n id: string;\n}\n\n/** The attributes of a submit button that posts an intent. They work without scripts. */\nexport interface IntentAttributes {\n type: 'submit';\n name: typeof INTENT;\n value: string;\n formnovalidate: true;\n /** With scripts, applies the intent in the browser instead of posting the form. */\n onClick?: (event: MouseEvent) => unknown;\n}\n\n/**\n * The changes of lists that the browser made since the last reply: the\n * values of the form after them, and the keys of the items of each list.\n */\nexport interface LocalChanges {\n /** The ID of the reply that the changes came after, or undefined before the first submit. */\n reply: string | undefined;\n value: unknown;\n /** The keys of the items of each list that changed, by field name. */\n keys: Record<string, string[]>;\n}\n\n/** What `formFields` reads besides the reply: the state of the browser, and the handler of intents. */\nexport interface FormState {\n checked?: CheckedErrors;\n local?: LocalChanges;\n /** The click handler of an intent button. */\n press?: (intent: Intent) => (event: MouseEvent) => unknown;\n}\n\n/** The attributes of a field that `createForm` gives. */\nexport interface FieldAttributes {\n name: string;\n id: string;\n 'aria-invalid'?: 'true';\n 'aria-describedby'?: string;\n value?: string;\n checked?: boolean;\n}\n\n/** The state of a field: its name, its value and its errors. */\nexport interface FieldState<T = unknown> {\n /** The field name, such as `items[0].name`. */\n name: string;\n /** The ID of the input, for a `<label for>`. */\n id: string;\n /** The value that the field shows: the posted value after a submit, or the default value. */\n value: T | undefined;\n /** The errors of the field, or undefined when it has none. */\n errors: string[] | undefined;\n /** The attributes of the input: `name`, `id`, the ARIA state of its errors and its value. */\n attrs: FieldAttributes;\n /** The attributes of the element that shows the errors: its ID, and `role=\"alert\"` after a submit. */\n errorAttrs: { id: string; role?: 'alert' };\n}\n\n/** An item of a list field. */\nexport type ListItem<T> = Field<T> & {\n /** A key that stays with the item when others are added or removed, for `#for … by`. */\n key: string;\n index: number;\n /** The attributes of a button that removes the item. */\n remove: IntentAttributes;\n /** The attributes of a button that moves the item up, or down. */\n moveUp: IntentAttributes;\n moveDown: IntentAttributes;\n};\n\n/** A field, typed by its value: a list has its items, and an object its fields. */\nexport type Field<T> = FieldState<T> &\n (NonNullable<T> extends readonly (infer Item)[]\n ? {\n list: ListItem<Item>[];\n /** The attributes of a button that adds an item at the end of the list. */\n insert: IntentAttributes;\n }\n : NonNullable<T> extends Date | File | Blob\n ? unknown\n : NonNullable<T> extends object\n ? { fields: Fields<NonNullable<T>> }\n : unknown);\n\n/** The fields of an object, by key. */\nexport type Fields<T> = { [K in keyof T]-?: Field<T[K]> };\n\nconst isFile = (value: unknown): boolean => typeof Blob !== 'undefined' && value instanceof Blob;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !isFile(value) &&\n !(value instanceof Date);\n\n/** The attributes of a submit button that posts an intent. */\nexport function intentButton(\n intent: Intent,\n press?: (intent: Intent) => (event: MouseEvent) => unknown,\n): IntentAttributes {\n const attrs: IntentAttributes = {\n type: 'submit',\n name: INTENT,\n value: intentValue(intent),\n formnovalidate: true,\n };\n if (press) {\n attrs.onClick = press(intent);\n }\n return attrs;\n}\n\n/** The changes of the browser when they came after the last reply. */\nexport function localSince(\n local: LocalChanges | undefined,\n result: SubmissionResult | undefined,\n): LocalChanges | undefined {\n return local && local.reply === result?.id ? local : undefined;\n}\n\n/** A key for a new item, which no other item of the page has. */\nlet nextKey = 0;\n\n/**\n * Applies an intent in the browser to the values that the form holds now.\n * The items of the list keep their keys, so their elements and what was\n * typed in them stay, and a new item gets a new key. Undefined when the\n * intent does not fit the values.\n */\nexport function applyLocalIntent(\n form: HTMLFormElement | null,\n intent: Intent,\n local: LocalChanges | undefined,\n result: SubmissionResult | undefined,\n): LocalChanges | undefined {\n if (!form || intent.type === 'reset' || intent.type === 'validate') {\n return undefined;\n }\n const values = formValues(new FormData(form), (name) => name === INTENT);\n const applied = values.value && applyIntent(values.value, intent);\n if (!applied) {\n return undefined;\n }\n const current = localSince(local, result);\n const before = getAt(values.value, parsePath(intent.name)!);\n const length = Array.isArray(before) ? before.length : 0;\n const keys = [\n ...(current?.keys[intent.name] ??\n (result && !result.reset ? result.keys[intent.name] : undefined) ??\n Array.from({ length }, (_, index) => String(index))),\n ];\n if (intent.type === 'insert') {\n keys.splice(intent.index ?? keys.length, 0, `n${nextKey++}`);\n } else if (intent.type === 'remove') {\n keys.splice(intent.index, 1);\n } else {\n keys.splice(intent.to, 0, ...keys.splice(intent.from, 1));\n }\n return {\n reply: result?.id,\n value: applied.value,\n keys: { ...current?.keys, [intent.name]: keys },\n };\n}\n\n/**\n * The fields of a form, from its default value and the reply of its last\n * submit. A field exists for each key of the default value or of the posted\n * value, so the default value names every field that the form shows.\n */\nexport function formFields<T>(\n id: string,\n defaultValue: T | undefined,\n result: SubmissionResult | undefined,\n { checked, local, press }: FormState = {},\n): Fields<T> {\n const changes = localSince(local, result);\n let value: unknown;\n if (changes) {\n value = changes.value;\n } else if (result && !result.reset) {\n value = result.value;\n }\n const submitted = result !== undefined;\n const keys = { ...(result && !result.reset ? result.keys : {}), ...changes?.keys };\n // The errors of the reply for the items of a list that the browser changed are of other items.\n const replied: Record<string, string[]> = {};\n for (const [name, messages] of Object.entries(result && !result.reset ? result.errors : {})) {\n if (!Object.keys(changes?.keys ?? {}).some((list) => name.startsWith(`${list}[`))) {\n replied[name] = messages;\n }\n }\n // The errors that the browser found replace those of the reply, for the fields that it checked.\n const current = checkedSince(checked, result);\n const shows = (name: string): boolean =>\n current !== undefined && (current.all || current.touched.includes(name));\n const errorsOf = (name: string): string[] | undefined => {\n const source = shows(name) ? current!.errors : replied;\n return Object.hasOwn(source, name) ? source[name] : undefined;\n };\n\n const state = (path: PathSegment[], shown: unknown): FieldState => {\n const name = formatPath(path);\n const fieldId = `${id}-${name}`;\n const errorId = `${fieldId}-error`;\n const messages = errorsOf(name);\n const attrs: FieldAttributes = { name, id: fieldId };\n if (messages) {\n attrs['aria-invalid'] = 'true';\n attrs['aria-describedby'] = errorId;\n }\n if (typeof shown === 'string' || typeof shown === 'number') {\n attrs.value = String(shown);\n } else if (typeof shown === 'boolean') {\n attrs.checked = shown;\n }\n return {\n name,\n id: fieldId,\n value: shown,\n errors: messages,\n attrs,\n errorAttrs: submitted ? { id: errorId, role: 'alert' } : { id: errorId },\n };\n };\n\n // After a submit, the fields show what was posted, and a field that was not posted, such as a\n // checkbox that was not checked, is empty. The default value still gives the shape.\n const posted = value !== undefined;\n const field = (path: PathSegment[], fallback: unknown, sent: unknown): unknown => {\n const shown = posted ? sent : fallback;\n const own = state(path, shown);\n // A list stays a list when nothing of it was posted, such as a list with no items.\n if (Array.isArray(shown) || Array.isArray(fallback)) {\n const items = Array.isArray(shown) ? shown : [];\n const name = own.name;\n const itemKeys = Object.hasOwn(keys, name) ? keys[name] : undefined;\n const defaults: unknown[] = Array.isArray(fallback) ? fallback : [];\n const list = items.map((item, index) =>\n Object.assign(\n // A new item takes the shape of the first default item.\n field([...path, index], defaults[index] ?? defaults[0], item) as object,\n {\n key: itemKeys?.[index] ?? String(index),\n index,\n remove: intentButton({ type: 'remove', name, index }, press),\n moveUp: intentButton(\n {\n type: 'reorder',\n name,\n from: index,\n to: Math.max(index - 1, 0),\n },\n press,\n ),\n moveDown: intentButton(\n {\n type: 'reorder',\n name,\n from: index,\n to: Math.min(index + 1, items.length - 1),\n },\n press,\n ),\n },\n ),\n );\n return Object.assign(own, { list, insert: intentButton({ type: 'insert', name }, press) });\n }\n if (isPlainObject(shown) || isPlainObject(fallback)) {\n const defaults = isPlainObject(fallback) ? fallback : {};\n const values = isPlainObject(sent) ? sent : {};\n const fields: Record<string, unknown> = {};\n for (const key of new Set([...Object.keys(defaults), ...Object.keys(posted ? values : {})])) {\n fields[key] = field(\n [...path, key],\n Object.hasOwn(defaults, key) ? defaults[key] : undefined,\n Object.hasOwn(values, key) ? values[key] : undefined,\n );\n }\n return path.length === 0 ? fields : Object.assign(own, { fields });\n }\n return own;\n };\n\n return field([], defaultValue, value) as Fields<T>;\n}\n\n/** The check of the browser when it came after the last reply, or undefined when a reply came after it. */\nexport function checkedSince(\n checked: CheckedErrors | undefined,\n result: SubmissionResult | undefined,\n): CheckedErrors | undefined {\n return checked && checked.reply === result?.id ? checked : undefined;\n}\n\n/**\n * The errors of the whole form: those that the browser found, when it\n * checked every field since the last reply, or else those of the reply.\n */\nexport function formErrorsOf(\n result: SubmissionResult | undefined,\n checked: CheckedErrors | undefined,\n): string[] | undefined {\n const current = checkedSince(checked, result);\n const errors = current?.all ? current.formErrors : result?.formErrors;\n return errors && errors.length > 0 ? errors : undefined;\n}\n\n/**\n * The next check of the browser, after the user leaves or changes a field.\n * A field counts once the user leaves it. After a submit, every field counts.\n * Undefined when the event changes nothing, such as typing in a field that\n * the user has not left yet.\n */\nexport async function checkField(\n schema: FormSchema,\n form: HTMLFormElement | null,\n name: string,\n left: boolean,\n checked: CheckedErrors | undefined,\n result: SubmissionResult | undefined,\n): Promise<CheckedErrors | undefined> {\n const current = checkedSince(checked, result);\n const all = result !== undefined && !result.reset;\n const touched = current?.touched ?? [];\n if (!form || !name || name === INTENT || (!left && !all && !touched.includes(name))) {\n return undefined;\n }\n const report = await validateForm(schema, new FormData(form));\n return {\n ...report,\n reply: result?.id,\n touched: touched.includes(name) ? touched : [...touched, name],\n all,\n };\n}\n\n/**\n * The attributes of a submit button that the form presses on Enter. Without\n * it, Enter in a field presses the first submit button of the form, which\n * can be an intent button, such as \"Remove\". It is hidden from sight and\n * from assistive technology, and cannot take focus.\n */\nexport const DEFAULT_SUBMIT = {\n type: 'submit',\n tabindex: -1,\n 'aria-hidden': 'true',\n style:\n 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0;padding:0;margin:-1px',\n} as const;\n"],"mappings":";;AASA,MAAa,SAAS;;AAGtB,MAAa,YAAY;;AAGzB,MAAa,4BAAiC,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;;;;;;;AAS/F,SAAgB,UAAU,MAAyC;CACjE,MAAM,OAAsB,CAAC;CAC7B,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;EAClC,MAAM,QAAQ,4BAA4B,KAAK,IAAI;EACnD,IAAI,CAAC,SAAS,UAAU,IAAI,MAAM,EAAG,GACnC;EAEF,KAAK,KAAK,MAAM,EAAG;EACnB,KAAK,MAAM,SAAS,MAAM,EAAE,CAAE,SAAS,YAAY,GAAG;GACpD,MAAM,QAAQ,OAAO,MAAM,EAAE;GAC7B,IAAI,QAAA,OAAsB,MAAM,EAAE,CAAE,SAAS,KAAK,MAAM,EAAE,CAAE,WAAW,GAAG,GACxE;GAEF,KAAK,KAAK,KAAK;EACjB;CACF;CACA,OAAO;AACT;;AAGA,SAAgB,WAAW,MAAsC;CAC/D,IAAI,OAAO;CACX,KAAK,MAAM,WAAW,MACpB,IAAI,OAAO,YAAY,UACrB,QAAQ,IAAI,QAAQ;MAEpB,QAAQ,OAAO,IAAI,YAAY;CAGnC,OAAO;AACT;;AAGA,SAAgB,MAAM,OAAgB,MAAuC;CAC3E,IAAI,UAAU;CACd,KAAK,MAAM,WAAW,MAAM;EAC1B,IAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,CAAC,OAAO,OAAO,SAAS,OAAO,GACpF;EAEF,UAAW,QAAyC;CACtD;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,MAAM,OAAgB,MAA8B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,CAAC,GAAG,MAAM,GAAG,GACb,OAAO,OAAO,UAAU,GAAG,IAAI,SAAS,OAAO,KAAA,GAC/C,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,KAAA,CAC7C;GAEF,OAAO,KAAK,WAAW,IAAI,SAAS,OAAO,OAAO,KAAK,EAAE,OAAO,CAAC;EACnE;EACA,OAAO;CACT;CAEA,OAAO,MAAM,CAAC,GAAG,cAAc,KAAK;AACtC;;AAGA,SAAgB,aACd,SACA,QAC2B;CAC3B,OAAO,WAAW,QAAQ,UAAU,QAAQ,KAAK,UAAU,KAAA;AAC7D;;;;;AAMA,SAAgB,aACd,QACA,SACsB;CACtB,MAAM,UAAU,aAAa,SAAS,MAAM;CAC5C,MAAM,SAAS,SAAS,MAAM,QAAQ,aAAa,QAAQ;CAC3D,OAAO,UAAU,OAAO,SAAS,IAAI,SAAS,KAAA;AAChD;;;;;;;AAQA,eAAsB,WACpB,QACA,MACA,MACA,MACA,SACA,QACoC;CACpC,MAAM,UAAU,aAAa,SAAS,MAAM;CAC5C,MAAM,MAAM,WAAW,KAAA,KAAa,CAAC,OAAO;CAC5C,MAAM,UAAU,SAAS,WAAW,CAAC;CACrC,IAAI,CAAC,QAAQ,CAAC,QAAQ,SAAA,cAAoB,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,SAAS,IAAI,GAC/E;CAGF,OAAO;EACL,GAAG,MAFgB,aAAa,QAAQ,IAAI,SAAS,IAAI,CAAC;EAG1D,OAAO,QAAQ;EACf,SAAS,QAAQ,SAAS,IAAI,IAAI,UAAU,CAAC,GAAG,SAAS,IAAI;EAC7D;CACF;AACF;;;;;;;AAQA,MAAa,iBAAiB;CAC5B,MAAM;CACN,UAAU;CACV,eAAe;CACf,OACE;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"html-mNTKzaDD.js","names":[],"sources":["../src/runtime/html.ts"],"sourcesContent":["// HTML string helpers that the server and the client both use.\n\nconst RAW: unique symbol = Symbol.for('brumate.raw');\n\n/** HTML that is inserted as it is, such as the output of a template. */\nexport interface Raw {\n [RAW]: string;\n}\n\n// A class, not an object literal, so serializers can skip their test for raw HTML on plain objects.\nclass RawHTML implements Raw {\n readonly [RAW]: string;\n\n constructor(html: string) {\n this[RAW] = html;\n }\n}\n\nexport function raw(html: string): Raw {\n return new RawHTML(html);\n}\n\nexport function isRaw(value: unknown): value is Raw {\n return typeof value === 'object' && value !== null && RAW in value;\n}\n\nexport function rawHTML(value: Raw): string {\n return value[RAW];\n}\n\nconst ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' };\n\nconst toEscape = (char: string): string => ESCAPES[char]!;\n\n// Most text has nothing to escape, so a test without the global flag skips the replace.\nexport function escape(value: string): string {\n return /[&<>]/.test(value) ? value.replace(/[&<>]/g, toEscape) : value;\n}\n\nexport function escapeAttribute(value: string): string {\n return /[&<\"]/.test(value) ? value.replace(/[&<\"]/g, toEscape) : value;\n}\n\n/** Renders a value inserted in markup. Promises are not awaited. */\nexport function insertValue(value: unknown): string {\n if (isRaw(value)) {\n return value[RAW];\n }\n if (value === null || value === undefined || typeof value === 'boolean') {\n return '';\n }\n if (Array.isArray(value)) {\n return value.map(insertValue).join('');\n }\n return escape(String(value));\n}\n\n/**\n * Renders a value as the text of an element whose content is text, such as\n * a `<textarea>`, as `insertValue` does but without escaping.\n */\nexport function textValue(value: unknown): string {\n if (isRaw(value)) {\n return value[RAW];\n }\n if (value === null || value === undefined || typeof value === 'boolean') {\n return '';\n }\n if (Array.isArray(value)) {\n return value.map(textValue).join('');\n }\n return String(value);\n}\n\nfunction toKebabCase(name: string): string {\n return name.startsWith('--') ? name : name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n\nexport function classValue(value: unknown): string {\n if (typeof value !== 'object' || value === null) {\n return value ? String(value) : '';\n }\n let text = '';\n if (Array.isArray(value)) {\n for (const item of value) {\n const part = classValue(item);\n if (part !== '') {\n text = text === '' ? part : `${text} ${part}`;\n }\n }\n return text;\n }\n // An empty name still adds a space between its neighbours, as in a join.\n let first = true;\n for (const name in value) {\n if (Object.hasOwn(value, name) && (value as Record<string, unknown>)[name]) {\n text = first ? name : `${text} ${name}`;\n first = false;\n }\n }\n return text;\n}\n\n/**\n * Renders a `class` attribute from classes that each have a space before\n * them, which the compiler builds from a literal class value. The classes\n * are escaped already. No class renders nothing.\n */\nexport function classAttribute(classes: string): string {\n return classes === '' ? '' : ` class=\"${classes.slice(1)}\"`;\n}\n\nfunction styleValue(value: unknown): string {\n if (typeof value === 'object' && value !== null) {\n return Object.entries(value)\n .filter(([, item]) => item !== null && item !== undefined && item !== false)\n .map(([name, item]) => `${toKebabCase(name)}:${String(item)}`)\n .join(';');\n }\n return String(value);\n}\n\n/** The brand of a binding of `$bind`, under the key of the registry. See `Binding`. */\nconst BOUND = Symbol.for('brumate.binding');\n\n/** The words of an attribute that says `true` or `false` in its value. */\nconst TRUE_FALSE = ['true', 'false'] as const;\n\n/**\n * Attributes whose two states are words in the value, not whether the\n * attribute is there, by their words for `true` and `false`. A missing\n * attribute means a third state, such as the default of the element, so\n * `false` must not remove it. `aria-*` and `data-*` are such attributes too.\n */\nconst SWITCHES = new Map<string, readonly [string, string]>([\n ['contenteditable', TRUE_FALSE],\n ['draggable', TRUE_FALSE],\n ['spellcheck', TRUE_FALSE],\n ['writingsuggestions', TRUE_FALSE],\n // SVG.\n ['focusable', TRUE_FALSE],\n ['translate', ['yes', 'no']],\n ['autocomplete', ['on', 'off']],\n ['autocorrect', ['on', 'off']],\n]);\n\n/** The words of `true` and `false` for an attribute that says them in its value, or undefined. */\nfunction switchWords(name: string): readonly [string, string] | undefined {\n const lower = name.toLowerCase();\n if (lower.startsWith('aria-') || lower.startsWith('data-')) {\n return TRUE_FALSE;\n }\n return SWITCHES.get(lower);\n}\n\n/**\n * Returns the text of an attribute, or undefined if the attribute is not\n * rendered.\n *\n * - `null` and `undefined` leave the attribute out.\n * - For an attribute whose value says its state, such as `aria-expanded`,\n * `draggable` or `translate`, `true` and `false` render as its words:\n * `\"true\"` and `\"false\"`, or `\"yes\"` and `\"no\"`, or `\"on\"` and `\"off\"`.\n * - For other attributes, such as `disabled`, `true` renders the attribute\n * without a value, and `false` leaves it out.\n */\nexport function attributeText(name: string, value: unknown): string | undefined {\n // `value=$bind(name)` on an element renders the value of the name.\n if (typeof value === 'object' && value !== null && BOUND in value) {\n value = (value as unknown as { value: unknown }).value;\n }\n if (value === null || value === undefined || typeof value === 'function') {\n return undefined;\n }\n if (typeof value === 'boolean') {\n const words = switchWords(name);\n if (words) {\n return value ? words[0] : words[1];\n }\n return value ? '' : undefined;\n }\n if (name === 'class') {\n const text = classValue(value);\n return text === '' ? undefined : text;\n }\n return name === 'style' ? styleValue(value) : String(value);\n}\n\n/**\n * A name that HTML reads as one attribute. A spread takes its names from\n * data, so a name with a space, a quote, `>`, `/` or `=` could write other\n * attributes or markup.\n */\n// oxlint-disable-next-line no-control-regex -- HTML reads no control character in a name.\nconst ATTRIBUTE_NAME = /^[^\\s\"'>/=\\x00-\\x1f\\x7f]+$/;\n\n/** Renders one attribute, with a leading space. A name that is not one attribute renders nothing. */\nexport function attribute(name: string, value: unknown): string {\n const text = attributeText(name, value);\n if (text === undefined || !ATTRIBUTE_NAME.test(name)) {\n return '';\n }\n return value === true && text === '' ? ` ${name}` : ` ${name}=\"${escapeAttribute(text)}\"`;\n}\n\n/**\n * Returns the value of a style variable with text around it, such as `12px`\n * for `${size}px`. A value that sets no variable stays as it is.\n */\nexport function affix(prefix: string, value: unknown, suffix: string): unknown {\n return value === null || value === undefined || value === false\n ? value\n : `${prefix}${String(value)}${suffix}`;\n}\n\n/** Returns a style with custom properties before an element's own style. */\nexport function vars(variables: Record<string, unknown>, own: unknown): string {\n const parts: string[] = [];\n for (const [name, value] of Object.entries(variables)) {\n if (value !== null && value !== undefined && value !== false) {\n parts.push(`${name}:${String(value)}`);\n }\n }\n const rest = own === null || own === undefined || own === false ? '' : styleValue(own);\n if (rest) {\n parts.push(rest);\n }\n return parts.join(';');\n}\n\n/** Returns a `<style>` element for a component's stylesheet. */\nexport function styleElement(id: string, css: string): string {\n return `<style b-style=\"${escapeAttribute(id)}\">${css.replace(/<\\/style/gi, '<\\\\/style')}</style>`;\n}\n\n/**\n * Merges the attributes of an element that has spreads, in their order: a\n * later value wins, except `class`, whose values all apply.\n */\nexport function mergeAttributes(parts: Record<string, unknown>[]): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const part of parts) {\n for (const [name, value] of Object.entries(part ?? {})) {\n result[name] =\n name === 'class' && result.class !== undefined && value !== undefined\n ? [result.class, value]\n : value;\n }\n }\n return result;\n}\n\n/**\n * The `b-on` entry of a handler that a spread passes on, such as\n * `click:prevent=Parent#h1@3`: its event, the modifiers of its wrappers, its\n * client function and the scope it runs in. A handler that `$handler` made\n * has its arguments after another `@`, encoded so that they hold no space.\n */\nexport function handlerEntry(\n name: string,\n ref: string,\n scope: number | string,\n modifiers: readonly string[] = [],\n args?: unknown[],\n): string {\n const bound = args === undefined ? '' : `@${encodeURIComponent(JSON.stringify(args))}`;\n return `${[name.slice(2).toLowerCase(), ...modifiers].join(':')}=${ref}@${scope}${bound}`;\n}\n\n/**\n * The `b-on` entry of a binding that a spread puts on `value` or `checked`\n * of an element. It names the scope of the slot, or of the setter of\n * `$bind(name, fn)`, after `@`. A box writes on `change`.\n */\nexport function bindEntry(\n name: string,\n ref: { scope: number | string; slot: number },\n setter?: { ref: string; scope: number | string },\n): string {\n const event = name === 'checked' ? 'change' : 'input';\n return setter\n ? `${event}=$set:${setter.ref}@${setter.scope}`\n : `${event}=$bind#0.${ref.slot}@${ref.scope}`;\n}\n\n/**\n * The `b-on` attribute of an element with spreads: the bindings of its\n * spreads, so its handlers read the new value, then its own handlers, then\n * those of its spreads.\n */\nexport function onAttribute(on: string[], own: string): string {\n const bindings = on.filter((entry) => /=\\$(bind#|set:)/.test(entry));\n const value = [...bindings, own, ...on.filter((entry) => !bindings.includes(entry))]\n .filter(Boolean)\n .join(' ');\n return value ? ` b-on=\"${escapeAttribute(value)}\"` : '';\n}\n\n/** Renders an object of attributes. */\nexport function spread(attributes: Record<string, unknown>): string {\n let result = '';\n for (const [name, value] of Object.entries(attributes)) {\n if (name !== 'children' && !/^on[A-Z]/.test(name)) {\n result += attribute(name, value);\n }\n }\n return result;\n}\n\nexport const VOID_ELEMENTS: Set<string> = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\n/**\n * Renders the attributes of a form that posts to a server function, such as\n * ` action=\"/_brumate/App_1abc%23save\" method=\"post\"`. `method` is the name of\n * the method attribute to add, if the element has none. `build` is the ID\n * of the build of the page, which the URL carries as `__build`, so the\n * server can tell a post from before a deploy without scripts.\n */\nexport function actionAttributes(\n prefix: string,\n name: string,\n id: string,\n method?: string,\n result?: string,\n build?: string,\n key?: string,\n): string {\n const methodText = method ? ` ${method}=\"post\"` : '';\n // The key of a form of a function that `idempotent` made, so a second post gets the first result.\n const query = [\n build === undefined ? '' : `__build=${encodeURIComponent(build)}`,\n key === undefined ? '' : `__key=${key}`,\n ]\n .filter(Boolean)\n .join('&');\n if (result !== undefined) {\n // The form posts to its page, which renders with the result. With the\n // loader, the result is written into the `$action` at `result` instead.\n const url = `?__action=${encodeURIComponent(id)}${query ? `&${query}` : ''}`;\n return ` ${name}=\"${escapeAttribute(url)}\"${methodText} b-action=\"${escapeAttribute(id)}\" b-result=\"${escapeAttribute(result)}\"`;\n }\n const url = `${prefix}/${encodeURIComponent(id)}${query ? `?${query}` : ''}`;\n return ` ${name}=\"${escapeAttribute(url)}\"${methodText}`;\n}\n"],"mappings":";AAEA,MAAM,MAAqB,OAAO,IAAI,aAAa;AAQnD,IAAM,UAAN,MAA6B;CAC3B,CAAU;CAEV,YAAY,MAAc;EACxB,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,IAAI,MAAmB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