brumate 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +97 -2
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +68 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-DuDTDePF.d.ts +190 -0
- package/dist/context-BG8KCF3v.js +15 -0
- package/dist/context-BG8KCF3v.js.map +1 -0
- package/dist/context-aeo9esY9.d.ts +16 -0
- package/dist/cookies-rgIAc8IE.js +165 -0
- package/dist/cookies-rgIAc8IE.js.map +1 -0
- package/dist/devtools-Bm8cS7hX.js +108 -0
- package/dist/devtools-Bm8cS7hX.js.map +1 -0
- package/dist/devtools-panel-CTbDSBBA.js +437 -0
- package/dist/devtools-panel-CTbDSBBA.js.map +1 -0
- package/dist/files-D_JUcSU5.js +158 -0
- package/dist/files-D_JUcSU5.js.map +1 -0
- package/dist/html-CxWpXngy.js +115 -0
- package/dist/html-CxWpXngy.js.map +1 -0
- package/dist/html-DV-Tezgq.d.ts +41 -0
- package/dist/index.d.ts +2031 -0
- package/dist/index.js +691 -0
- package/dist/index.js.map +1 -0
- package/dist/inspect-CGCWfaEx.js +6346 -0
- package/dist/inspect-CGCWfaEx.js.map +1 -0
- package/dist/loader-BUhNqDHw.d.ts +30 -0
- package/dist/loader-py4qu6tQ.js +215 -0
- package/dist/loader-py4qu6tQ.js.map +1 -0
- package/dist/navigate-C5dP89YL.js +369 -0
- package/dist/navigate-C5dP89YL.js.map +1 -0
- package/dist/produce-BRGHP7e0.js +126 -0
- package/dist/produce-BRGHP7e0.js.map +1 -0
- package/dist/produce-BjQGMpqL.d.ts +50 -0
- package/dist/rpc-B86KKjzx.js +83 -0
- package/dist/rpc-B86KKjzx.js.map +1 -0
- package/dist/runtime/client.d.ts +5 -0
- package/dist/runtime/client.js +1052 -0
- package/dist/runtime/client.js.map +1 -0
- package/dist/runtime/context.d.ts +2 -0
- package/dist/runtime/context.js +1 -0
- package/dist/runtime/devtools.d.ts +34 -0
- package/dist/runtime/devtools.js +1 -0
- package/dist/runtime/hot.d.ts +36 -0
- package/dist/runtime/hot.js +40 -0
- package/dist/runtime/hot.js.map +1 -0
- package/dist/runtime/html.d.ts +2 -0
- package/dist/runtime/html.js +1 -0
- package/dist/runtime/loader.d.ts +2 -0
- package/dist/runtime/loader.js +1 -0
- package/dist/runtime/routes.d.ts +21 -0
- package/dist/runtime/routes.js +18 -0
- package/dist/runtime/routes.js.map +1 -0
- package/dist/runtime/server.d.ts +5 -0
- package/dist/runtime/server.js +7 -0
- package/dist/runtime/signals.d.ts +46 -0
- package/dist/runtime/signals.js +74 -0
- package/dist/runtime/signals.js.map +1 -0
- package/dist/runtime/testing.d.ts +36 -0
- package/dist/runtime/testing.js +96 -0
- package/dist/runtime/testing.js.map +1 -0
- package/dist/server-CX3JnPCs.js +1205 -0
- package/dist/server-CX3JnPCs.js.map +1 -0
- package/dist/server-sQCvduOz.d.ts +562 -0
- package/dist/shared-BE_oBSDM.js +176 -0
- package/dist/shared-BE_oBSDM.js.map +1 -0
- package/dist/stream-cvhqOzfs.js +145 -0
- package/dist/stream-cvhqOzfs.js.map +1 -0
- package/dist/vite.d.ts +121 -0
- package/dist/vite.js +958 -0
- package/dist/vite.js.map +1 -0
- package/package.json +117 -3
- package/types.d.ts +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alexis Munsayac
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
|
1
|
-
#
|
|
1
|
+
# brumate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> A component language and compiler for resumable web apps.
|
|
4
|
+
|
|
5
|
+
`brumate` compiles single-file components into server-rendered HTML and small client chunks. The client does not hydrate. It reads the state that the server wrote into the page and loads the code for an event handler only when that event fires.
|
|
6
|
+
|
|
7
|
+
This repository holds the design and the compiler. The compiler generates a server module that renders HTML with the state, and a client module that resumes it. A Vite plugin compiles `.brm` files in an app.
|
|
8
|
+
|
|
9
|
+
## Goals
|
|
10
|
+
|
|
11
|
+
- Ship only the client code that an interaction can reach. Markup that never changes ships as HTML and nothing else.
|
|
12
|
+
- Never run component code again on the client to rebuild state.
|
|
13
|
+
- Keep a loader under 1 KB that is the only code loaded before the first interaction.
|
|
14
|
+
- Keep the syntax small: scripts, markup with `#` blocks, and a few compile-time functions.
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
```html
|
|
19
|
+
<script>
|
|
20
|
+
import { $memo, $props, $signal } from 'brumate/signals';
|
|
21
|
+
import { persist } from './todos.server';
|
|
22
|
+
|
|
23
|
+
const { initial } = $props<{ initial: Todo[] }>();
|
|
24
|
+
let todos = $signal(initial);
|
|
25
|
+
let draft = $signal('');
|
|
26
|
+
const left = $memo(todos.filter((todo) => !todo.done).length);
|
|
27
|
+
|
|
28
|
+
async function add() {
|
|
29
|
+
todos = [...todos, { id: crypto.randomUUID(), title: draft, done: false }];
|
|
30
|
+
draft = '';
|
|
31
|
+
await persist(todos);
|
|
32
|
+
}
|
|
33
|
+
</script>
|
|
34
|
+
|
|
35
|
+
<h1>Todos</h1>
|
|
36
|
+
<form onSubmit:prevent=add>
|
|
37
|
+
<input value=draft onInput=((event) => (draft = event.currentTarget.value))>
|
|
38
|
+
</form>
|
|
39
|
+
<ul>
|
|
40
|
+
#for (todo of todos by todo.id) {
|
|
41
|
+
<li class={ done: todo.done }>{todo.title}</li>
|
|
42
|
+
}
|
|
43
|
+
</ul>
|
|
44
|
+
<p>{left} left</p>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The `<h1>` produces no client code. The `#for` item template ships because `add` can change `todos`. `persist` is a server function, so the client only gets a call stub.
|
|
48
|
+
|
|
49
|
+
## Try it
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pnpm install
|
|
53
|
+
pnpm build
|
|
54
|
+
pnpm --filter example-todos dev
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
[`examples/todos`](./examples/todos) renders a todo list and a counter on the server. In the browser, only the loader runs before the first click.
|
|
58
|
+
|
|
59
|
+
## Documents
|
|
60
|
+
|
|
61
|
+
The documentation is in [`website/docs`](./website/docs), and the website shows it with samples that run in the page.
|
|
62
|
+
|
|
63
|
+
- [Introduction](./website/docs/index.md) and [Getting started](./website/docs/getting-started.md) set up a project.
|
|
64
|
+
- [Your first app](./website/docs/tutorial.md) builds a todo app step by step.
|
|
65
|
+
- The guides cover [components](./website/docs/components.md), [state](./website/docs/state.md), [async data](./website/docs/async-data.md), [server functions](./website/docs/server-functions.md), [routing](./website/docs/routing.md) and the rest.
|
|
66
|
+
- The reference lists every [compile-time function](./website/docs/reference-signals.md), [block](./website/docs/reference-blocks.md), [runtime export](./website/docs/reference-server.md) and [plugin option](./website/docs/reference-plugin.md).
|
|
67
|
+
- The internals describe the [reactive graph](./website/docs/reactive-graph.md), the [page format](./website/docs/page-format.md) and the [server function protocol](./website/docs/server-protocol.md).
|
|
68
|
+
|
|
69
|
+
Design notes for contributors are in [`docs`](./docs):
|
|
70
|
+
|
|
71
|
+
- [Grammar](./docs/grammar.md) defines the file format in EBNF.
|
|
72
|
+
- [Intermediate representation](./docs/ir.md) defines the data that each compiler stage produces.
|
|
73
|
+
- [Compiler](./docs/compiler.md) describes the pipeline, the output and the runtime.
|
|
74
|
+
- [Decisions](./docs/decisions.md) lists what is decided and what is still open.
|
|
75
|
+
- [Proposals](./docs/proposals.md) lists features that would be good to add, with a sketch of each.
|
|
76
|
+
- [Prior art](./docs/prior-art.md) compares other resumable and partially hydrated frameworks.
|
|
77
|
+
|
|
78
|
+
## Development
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
pnpm install
|
|
82
|
+
pnpm test
|
|
83
|
+
pnpm typecheck
|
|
84
|
+
pnpm lint
|
|
85
|
+
pnpm format
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The tests in [`packages/brumate/test/fixtures`](./packages/brumate/test/fixtures) parse and analyze each `.brm` file. The output of every stage is compared with a snapshot in `test/__snapshots__`. The tests in [`packages/brumate/test/render`](./packages/brumate/test/render) compile each component, render it on the server, and compare the modules, the HTML and the state with a snapshot. The tests in `test/resume.test.ts` load that HTML into a DOM, start the loader, and check that events update the page.
|
|
89
|
+
|
|
90
|
+
## Name
|
|
91
|
+
|
|
92
|
+
Brumation is the dormant state of reptiles in cold weather. A reptile in brumation stays inactive but wakes up briefly to drink when it needs to, then goes back to rest. A `brumate` page does the same with its code. It loads a handler only when an event needs it.
|
|
93
|
+
|
|
94
|
+
The name is free on npm.
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
MIT © [lxsmnsyc](https://github.com/lxsmnsyc)
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { T as analyzeProjectProps, a as CompileError, n as inspect } from "./inspect-CGCWfaEx.js";
|
|
3
|
+
import { n as findFiles, t as defaultExclude } from "./files-D_JUcSU5.js";
|
|
4
|
+
import { readFile, stat } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
//#region src/cli.ts
|
|
7
|
+
const USAGE = `Usage: brumate inspect [--json] [files or directories]
|
|
8
|
+
|
|
9
|
+
Shows what each component ships to the client, and why.
|
|
10
|
+
Without paths, inspects every .brm file under the current directory.`;
|
|
11
|
+
function toPosix(file) {
|
|
12
|
+
return file.split(path.sep).join("/");
|
|
13
|
+
}
|
|
14
|
+
/** Shows parent files relative to the current directory. */
|
|
15
|
+
function relativeParents(parents, root) {
|
|
16
|
+
const result = /* @__PURE__ */ new Map();
|
|
17
|
+
for (const [prop, files] of parents) result.set(prop, new Set([...files].map((file) => toPosix(path.relative(root, file)))));
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
async function inspectCommand(args) {
|
|
21
|
+
const json = args.includes("--json");
|
|
22
|
+
const paths = args.filter((arg) => arg !== "--json");
|
|
23
|
+
const root = process.cwd();
|
|
24
|
+
const project = await findFiles(root, defaultExclude);
|
|
25
|
+
const sources = /* @__PURE__ */ new Map();
|
|
26
|
+
for (const [index, source] of (await Promise.all(project.map((file) => readFile(file, "utf8")))).entries()) sources.set(project[index], source);
|
|
27
|
+
const props = analyzeProjectProps(sources);
|
|
28
|
+
const targets = (await Promise.all((paths.length > 0 ? paths : ["."]).map(async (target) => {
|
|
29
|
+
const absolute = path.resolve(root, target);
|
|
30
|
+
return (await stat(absolute)).isDirectory() ? findFiles(absolute, defaultExclude) : [toPosix(absolute)];
|
|
31
|
+
}))).flat();
|
|
32
|
+
const extra = targets.filter((file) => !sources.has(file));
|
|
33
|
+
for (const [index, source] of (await Promise.all(extra.map((file) => readFile(file, "utf8")))).entries()) sources.set(extra[index], source);
|
|
34
|
+
const reports = [];
|
|
35
|
+
const texts = [];
|
|
36
|
+
let failed = false;
|
|
37
|
+
for (const file of targets) {
|
|
38
|
+
const source = sources.get(file);
|
|
39
|
+
const filename = toPosix(path.relative(root, file));
|
|
40
|
+
try {
|
|
41
|
+
const parents = props.get(file);
|
|
42
|
+
const result = inspect(source, {
|
|
43
|
+
filename,
|
|
44
|
+
liveProps: parents && new Set(parents.keys()),
|
|
45
|
+
parents: parents && relativeParents(parents, root)
|
|
46
|
+
});
|
|
47
|
+
reports.push(result.report);
|
|
48
|
+
texts.push(result.text);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (!(error instanceof CompileError)) throw error;
|
|
51
|
+
failed = true;
|
|
52
|
+
console.error(error.message);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
console.log(json ? JSON.stringify(reports, null, 2) : texts.join("\n\n"));
|
|
56
|
+
return failed ? 1 : 0;
|
|
57
|
+
}
|
|
58
|
+
async function main(args) {
|
|
59
|
+
const [command, ...rest] = args;
|
|
60
|
+
if (command === "inspect") return inspectCommand(rest);
|
|
61
|
+
console.log(USAGE);
|
|
62
|
+
return command === void 0 || command === "--help" ? 0 : 1;
|
|
63
|
+
}
|
|
64
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
65
|
+
//#endregion
|
|
66
|
+
export {};
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { CompileError } from './compile.ts';\nimport { defaultExclude, findFiles } from './files.ts';\nimport { inspect } from './inspect.ts';\nimport type { InspectReport } from './inspect.ts';\nimport { analyzeProjectProps } from './project.ts';\n\nconst USAGE = `Usage: brumate inspect [--json] [files or directories]\n\nShows what each component ships to the client, and why.\nWithout paths, inspects every .brm file under the current directory.`;\n\nfunction toPosix(file: string): string {\n return file.split(path.sep).join('/');\n}\n\n/** Shows parent files relative to the current directory. */\nfunction relativeParents(\n parents: Map<string, Set<string>>,\n root: string,\n): Map<string, Set<string>> {\n const result = new Map<string, Set<string>>();\n for (const [prop, files] of parents) {\n result.set(prop, new Set([...files].map((file) => toPosix(path.relative(root, file)))));\n }\n return result;\n}\n\nasync function inspectCommand(args: string[]): Promise<number> {\n const json = args.includes('--json');\n const paths = args.filter((arg) => arg !== '--json');\n const root = process.cwd();\n\n // Props are analyzed across every file under the current directory.\n const project = await findFiles(root, defaultExclude);\n const sources = new Map<string, string>();\n for (const [index, source] of (\n await Promise.all(project.map((file) => readFile(file, 'utf8')))\n ).entries()) {\n sources.set(project[index]!, source);\n }\n const props = analyzeProjectProps(sources);\n\n const found = await Promise.all(\n (paths.length > 0 ? paths : ['.']).map(async (target) => {\n const absolute = path.resolve(root, target);\n return (await stat(absolute)).isDirectory()\n ? findFiles(absolute, defaultExclude)\n : [toPosix(absolute)];\n }),\n );\n const targets = found.flat();\n // Files outside the current directory are read here.\n const extra = targets.filter((file) => !sources.has(file));\n for (const [index, source] of (\n await Promise.all(extra.map((file) => readFile(file, 'utf8')))\n ).entries()) {\n sources.set(extra[index]!, source);\n }\n\n const reports: InspectReport[] = [];\n const texts: string[] = [];\n let failed = false;\n for (const file of targets) {\n const source = sources.get(file)!;\n const filename = toPosix(path.relative(root, file));\n try {\n const parents = props.get(file);\n const result = inspect(source, {\n filename,\n liveProps: parents && new Set(parents.keys()),\n parents: parents && relativeParents(parents, root),\n });\n reports.push(result.report);\n texts.push(result.text);\n } catch (error) {\n if (!(error instanceof CompileError)) {\n throw error;\n }\n failed = true;\n console.error(error.message);\n }\n }\n console.log(json ? JSON.stringify(reports, null, 2) : texts.join('\\n\\n'));\n return failed ? 1 : 0;\n}\n\nasync function main(args: string[]): Promise<number> {\n const [command, ...rest] = args;\n if (command === 'inspect') {\n return inspectCommand(rest);\n }\n console.log(USAGE);\n return command === undefined || command === '--help' ? 0 : 1;\n}\n\nprocess.exitCode = await main(process.argv.slice(2));\n"],"mappings":";;;;;;AASA,MAAM,QAAQ;;;;AAKd,SAAS,QAAQ,MAAsB;CACrC,OAAO,KAAK,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;AACtC;;AAGA,SAAS,gBACP,SACA,MAC0B;CAC1B,MAAM,yBAAS,IAAI,IAAyB;CAC5C,KAAK,MAAM,CAAC,MAAM,UAAU,SAC1B,OAAO,IAAI,MAAM,IAAI,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,SAAS,QAAQ,KAAK,SAAS,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC;CAExF,OAAO;AACT;AAEA,eAAe,eAAe,MAAiC;CAC7D,MAAM,OAAO,KAAK,SAAS,QAAQ;CACnC,MAAM,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,QAAQ;CACnD,MAAM,OAAO,QAAQ,IAAI;CAGzB,MAAM,UAAU,MAAM,UAAU,MAAM,cAAc;CACpD,MAAM,0BAAU,IAAI,IAAoB;CACxC,KAAK,MAAM,CAAC,OAAO,YACjB,MAAM,QAAQ,IAAI,QAAQ,KAAK,SAAS,SAAS,MAAM,MAAM,CAAC,CAAC,EAAA,CAC/D,QAAQ,GACR,QAAQ,IAAI,QAAQ,QAAS,MAAM;CAErC,MAAM,QAAQ,oBAAoB,OAAO;CAUzC,MAAM,WAAU,MARI,QAAQ,KACzB,MAAM,SAAS,IAAI,QAAQ,CAAC,GAAG,EAAA,CAAG,IAAI,OAAO,WAAW;EACvD,MAAM,WAAW,KAAK,QAAQ,MAAM,MAAM;EAC1C,QAAQ,MAAM,KAAK,QAAQ,EAAA,CA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AAM,CAAC,CAAC"}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { t as Raw } from "./html-DV-Tezgq.js";
|
|
2
|
+
import { n as ElementReference } from "./produce-BjQGMpqL.js";
|
|
3
|
+
import { t as Context } from "./context-aeo9esY9.js";
|
|
4
|
+
//#region src/runtime/client.d.ts
|
|
5
|
+
type Update = [kind: number, name: string];
|
|
6
|
+
/** The entry of a compiled client module. */
|
|
7
|
+
interface ClientModule {
|
|
8
|
+
id: string;
|
|
9
|
+
/** Prop names to slot indices. `*` is the slot of a props object. */
|
|
10
|
+
props: Record<string, number>;
|
|
11
|
+
/** Scope kind, then slot, to the updates that read it. */
|
|
12
|
+
g: Record<number, Record<number, Update[]>>;
|
|
13
|
+
/** Imports a part of the module. */
|
|
14
|
+
load: (part: string) => Promise<Part>;
|
|
15
|
+
/** Server function ID to the memos that call it, as scope kind and update, for `refresh`. */
|
|
16
|
+
refresh?: Record<string, Update[]>;
|
|
17
|
+
}
|
|
18
|
+
/** A part of a client module: one client root, or the updates. */
|
|
19
|
+
type Part = Record<string, unknown>;
|
|
20
|
+
/** The instance of a scope in the page. */
|
|
21
|
+
interface Scope {
|
|
22
|
+
id: number;
|
|
23
|
+
/** The scope's ID in the compiled component. */
|
|
24
|
+
k: number;
|
|
25
|
+
p?: Scope;
|
|
26
|
+
/** The component ID, for a component's root scope. */
|
|
27
|
+
m?: string;
|
|
28
|
+
s: unknown[];
|
|
29
|
+
/** The item of a list item scope. */
|
|
30
|
+
i?: unknown;
|
|
31
|
+
c?: Record<number, number>;
|
|
32
|
+
/** The scope that rendered a component's root scope. */
|
|
33
|
+
o?: Scope;
|
|
34
|
+
/** The values that the scope provides, by context key. */
|
|
35
|
+
v?: Record<string, unknown>;
|
|
36
|
+
/** The slots that hold the contexts that the scope reads, by context key. */
|
|
37
|
+
x?: Record<string, number>;
|
|
38
|
+
children: Set<Scope>;
|
|
39
|
+
cleanups?: Map<string, () => void>;
|
|
40
|
+
keys?: Map<number, unknown>;
|
|
41
|
+
}
|
|
42
|
+
interface CoreOptions {
|
|
43
|
+
load: (id: string) => Promise<ClientModule>;
|
|
44
|
+
/** Adds event listeners for the `data-on` attributes in new markup. */
|
|
45
|
+
listen: (root: ParentNode) => void;
|
|
46
|
+
/** The URL prefix of server function calls. Defaults to `/_brumate`. */
|
|
47
|
+
rpc?: string;
|
|
48
|
+
}
|
|
49
|
+
/** What the devtools overlay hears from the core. It is set only in development. */
|
|
50
|
+
interface DevtoolsHooks {
|
|
51
|
+
/** The core started, with the scopes of the page, and a way to write a slot, as a handler does. */
|
|
52
|
+
attach?(core: {
|
|
53
|
+
scopes: Map<number, Scope>;
|
|
54
|
+
set: (scope: Scope, slot: number, value: unknown) => void;
|
|
55
|
+
}): void;
|
|
56
|
+
/** A handler starts for an event. */
|
|
57
|
+
handler?(ref: string, element: Element, event?: Event): void;
|
|
58
|
+
/** A part of a component's client code loaded. */
|
|
59
|
+
part?(component: string, name: string): void;
|
|
60
|
+
/** A slot got a new value. */
|
|
61
|
+
write?(scope: Scope, slot: number, value: unknown): void;
|
|
62
|
+
}
|
|
63
|
+
/** The global key of the devtools hooks. */
|
|
64
|
+
declare const DEVTOOLS: unique symbol;
|
|
65
|
+
/** Stops reading state records that arrive later. */
|
|
66
|
+
declare function dispose(): void;
|
|
67
|
+
/**
|
|
68
|
+
* Forgets the page, before another page replaces it. Cleanups run. Loaded
|
|
69
|
+
* modules and parts stay, so the next page does not load them again.
|
|
70
|
+
*/
|
|
71
|
+
declare function leavePage(): void;
|
|
72
|
+
/** Reads the page state. The loader calls it once, before the first handler. */
|
|
73
|
+
declare function init(value: CoreOptions): void;
|
|
74
|
+
declare function loadModule(id: string): Promise<ClientModule>;
|
|
75
|
+
/** Runs the handler `ref` for an element with a `data-b` anchor. */
|
|
76
|
+
declare function handle(element: Element, ref: string, event?: Event): Promise<unknown>;
|
|
77
|
+
/** Returns the instance of a scope by its ID. */
|
|
78
|
+
declare function scopeOf(id: number): Scope | undefined;
|
|
79
|
+
declare function get(scope: Scope, slot: number): any;
|
|
80
|
+
declare function set<T>(scope: Scope, slot: number, value: T): T;
|
|
81
|
+
/**
|
|
82
|
+
* The names of a call of a module function, for its shared code. Each ref
|
|
83
|
+
* is a slot of `scope`, `[scope, slot]` for a slot of another scope, or
|
|
84
|
+
* `[value]` for a value that does not change, such as a literal argument.
|
|
85
|
+
*/
|
|
86
|
+
declare function cells(scope: Scope, links: unknown[], names: string[]): Record<string, unknown>;
|
|
87
|
+
/**
|
|
88
|
+
* Writes the result of an async memo when it arrives. Until then the slot
|
|
89
|
+
* keeps its value, and `pending` is true. Only the latest load is written.
|
|
90
|
+
*/
|
|
91
|
+
declare function asyncMemo(scope: Scope, slot: number, promise: Promise<unknown>): void;
|
|
92
|
+
/**
|
|
93
|
+
* Computes a memo. A promise loads, and the memo keeps its value until it
|
|
94
|
+
* settles. A memo that reads a value that is still loading keeps its value
|
|
95
|
+
* too, and is pending until that value arrives and the memo computes again.
|
|
96
|
+
*/
|
|
97
|
+
declare function memo(scope: Scope, slot: number, compute: () => unknown): void;
|
|
98
|
+
/**
|
|
99
|
+
* Writes a guess into an optimistic value. It goes back to its source when
|
|
100
|
+
* the source changes, which computes it again, or when every server call of
|
|
101
|
+
* the page finishes, such as after a post failed.
|
|
102
|
+
*/
|
|
103
|
+
declare function guess<T>(scope: Scope, slot: number, ...rest: [value: T] | [sourceScope: Scope, sourceSlot: number, value: T]): T;
|
|
104
|
+
/** True while a new value of a memo loads, or while the server still streams its value. */
|
|
105
|
+
declare function pending(scope: Scope, slot: number): boolean;
|
|
106
|
+
/** `x++`, `x--`, `++x` and `--x`. */
|
|
107
|
+
declare function update(scope: Scope, slot: number, delta: number, prefix: boolean): number;
|
|
108
|
+
/**
|
|
109
|
+
* Renders a `#portal` body into its target, between markers with its scope
|
|
110
|
+
* ID. `kinds` names the body, so a new target first removes it from the old one.
|
|
111
|
+
*/
|
|
112
|
+
declare function portal(scope: Scope, target: unknown, render: Render, kinds?: number[]): void;
|
|
113
|
+
declare function text(scope: Scope, anchor: number, value: unknown): void;
|
|
114
|
+
declare function attr(scope: Scope, anchor: number, name: string, value: unknown): void;
|
|
115
|
+
declare function attrs(scope: Scope, anchor: number, values: Record<string, unknown>): void;
|
|
116
|
+
type Render = (parent: Scope, item?: unknown, index?: number) => string;
|
|
117
|
+
/** Shows the branch at `index` of `#if` or `#switch`, or nothing for -1. */
|
|
118
|
+
declare function branch(scope: Scope, anchor: number, index: number, renders: (Render | undefined)[], kinds: number[]): void;
|
|
119
|
+
/** Renders the body of `#key` again when its value changes. */
|
|
120
|
+
declare function rekey(scope: Scope, anchor: number, value: unknown, render: Render, kinds: number[]): void;
|
|
121
|
+
/**
|
|
122
|
+
* Renders the body of a `#try` block again, for its `reset` function. If the
|
|
123
|
+
* body throws, the fallback renders again with the error.
|
|
124
|
+
*/
|
|
125
|
+
declare function reset(scope: Scope, anchor: number, id: string, body: string, fallback: string, kinds: number[]): Promise<void>;
|
|
126
|
+
/** Renders the body of a `#client` block once. */
|
|
127
|
+
declare function fill(scope: Scope, anchor: number, render: Render): void;
|
|
128
|
+
/** Updates the items of `#for` or `#repeat`, keeping the elements of items whose keys stay. */
|
|
129
|
+
declare function list(scope: Scope, anchor: number, items: unknown[], key: (item: unknown, index: number) => unknown, render: Render, assign: (scope: Scope, item: unknown, index: number) => void, fallback: Render | undefined, fallbackKinds: number[]): void;
|
|
130
|
+
/** Sets a style variable on the top-level elements of a component instance. */
|
|
131
|
+
declare function setVar(scope: Scope, name: string, value: unknown): void;
|
|
132
|
+
/** Writes a provided value, and the slot of every scope that reads it from this provider. */
|
|
133
|
+
declare function provide(scope: Scope, context: Context<unknown>, value: unknown): void;
|
|
134
|
+
/** Sets the title of the page. */
|
|
135
|
+
declare function title(value: unknown): void;
|
|
136
|
+
/** Writes a prop of a child component. */
|
|
137
|
+
declare function prop(scope: Scope, anchor: number, name: string, value: unknown): void;
|
|
138
|
+
/** Runs an effect or a `$client` callback, after the cleanup of its previous run. */
|
|
139
|
+
declare function effect(scope: Scope, name: string, callback: () => unknown): void;
|
|
140
|
+
/** Renders the attributes of a form or button that posts to a server function. */
|
|
141
|
+
declare function action(name: string, id: string, method?: string, result?: string): string;
|
|
142
|
+
/**
|
|
143
|
+
* Sends a form to the server function of its `$action`, and writes the
|
|
144
|
+
* result into the `$action` when it arrives. It is pending until then.
|
|
145
|
+
*/
|
|
146
|
+
declare function submitAction(form: HTMLFormElement, submitter: HTMLElement | null): void;
|
|
147
|
+
/** Calls a server function. */
|
|
148
|
+
declare function rpc(id: string, args: unknown[]): Promise<unknown>;
|
|
149
|
+
/** Renders a value inserted in markup. */
|
|
150
|
+
declare function insert(value: unknown): string;
|
|
151
|
+
/** A component's client render function, from its `?brumate-render` module. */
|
|
152
|
+
type Component<P = any> = (props: P) => string;
|
|
153
|
+
/**
|
|
154
|
+
* Renders a child component on the client. With `scope` and `anchor`,
|
|
155
|
+
* records the child's scope so the parent can update its props.
|
|
156
|
+
*/
|
|
157
|
+
declare function component<P>(Child: Component<P>, props: P, _ctx?: unknown, scope?: Scope | number, anchor?: number): string;
|
|
158
|
+
declare function dynamic(tag: unknown, attributes: Record<string, unknown>, children: Raw | undefined, _ctx?: unknown, scope?: Scope | number): string;
|
|
159
|
+
declare class ClientContext {
|
|
160
|
+
/** Work that waits until rendered markup is in the page. */
|
|
161
|
+
readonly after: (() => void)[];
|
|
162
|
+
/** The scope that renders the next component, which becomes its owner. */
|
|
163
|
+
private owner;
|
|
164
|
+
scope(kind: number, parent?: Scope | number, module?: string): number;
|
|
165
|
+
/** The ID that `$id()` makes. Client scope IDs are negative, so they differ from the server's. */
|
|
166
|
+
id(scope: Scope | number, index: number): string;
|
|
167
|
+
/** Sets the owner of the next component's root scope. */
|
|
168
|
+
own(scope: Scope | number): void;
|
|
169
|
+
/** Provides a value of a context to the scopes inside `scope`. */
|
|
170
|
+
provide<T>(context: Context<T>, value: T, scope: Scope | number): void;
|
|
171
|
+
/** Reads a context, and records its slot so that changes to the provided value reach it. */
|
|
172
|
+
consume<T>(context: Context<T>, scope: Scope | number, slot?: number): T;
|
|
173
|
+
slots(id: number, values: unknown[]): void;
|
|
174
|
+
item(id: number, value: unknown): void;
|
|
175
|
+
element(scope: number, anchor: number): ElementReference;
|
|
176
|
+
/** Adds the markup of a `#head` block to the document's head. */
|
|
177
|
+
head(html: string): void;
|
|
178
|
+
/** Sets the title of the page, for a component that the client renders. */
|
|
179
|
+
title(value: unknown): void;
|
|
180
|
+
/** Adds the markup of a `#portal` block at the end of the page, after the markup around it. */
|
|
181
|
+
portal(html: string): void;
|
|
182
|
+
/** Adds a component's stylesheet to the page, if the server did not. */
|
|
183
|
+
style(id: string, css: string): string;
|
|
184
|
+
/** A function prop rendered on the client calls the parent's exported handler. */
|
|
185
|
+
fn(value: unknown, ref: string, scope: Scope | number): unknown;
|
|
186
|
+
}
|
|
187
|
+
declare const context: ClientContext;
|
|
188
|
+
//#endregion
|
|
189
|
+
export { portal as A, text as B, init as C, loadModule as D, list as E, rpc as F, update as H, scopeOf as I, set as L, provide as M, rekey as N, memo as O, reset as P, setVar as R, handle as S, leavePage as T, title as V, dynamic as _, DevtoolsHooks as a, get as b, action as c, attrs as d, branch as f, dispose as g, context as h, DEVTOOLS as i, prop as j, pending as k, asyncMemo as l, component as m, Component as n, Part as o, cells as p, CoreOptions as r, Scope as s, ClientModule as t, attr as u, effect as v, insert as w, guess as x, fill as y, submitAction as z };
|
|
190
|
+
//# sourceMappingURL=client-DuDTDePF.d.ts.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//#region src/runtime/context.ts
|
|
2
|
+
/**
|
|
3
|
+
* Creates a context. `key` names it in the page state, so it must be unique
|
|
4
|
+
* in the app and the same on the server and the client.
|
|
5
|
+
*/
|
|
6
|
+
function createContext(key, defaultValue) {
|
|
7
|
+
return {
|
|
8
|
+
key,
|
|
9
|
+
defaultValue
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
export { createContext as t };
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=context-BG8KCF3v.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-BG8KCF3v.js","names":[],"sources":["../src/runtime/context.ts"],"sourcesContent":["/** A value that a component provides to the components inside it. */\nexport interface Context<T> {\n /** The same on the server and the client, so the page state can name the context. */\n readonly key: string;\n /** The value of a component that reads the context without a provider above it. */\n readonly defaultValue: T;\n}\n\n/**\n * Creates a context. `key` names it in the page state, so it must be unique\n * in the app and the same on the server and the client.\n */\nexport function createContext<T>(key: string, defaultValue: T): Context<T> {\n return { key, defaultValue };\n}\n"],"mappings":";;;;;AAYA,SAAgB,cAAiB,KAAa,cAA6B;CACzE,OAAO;EAAE;EAAK;CAAa;AAC7B"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/runtime/context.d.ts
|
|
2
|
+
/** A value that a component provides to the components inside it. */
|
|
3
|
+
interface Context<T> {
|
|
4
|
+
/** The same on the server and the client, so the page state can name the context. */
|
|
5
|
+
readonly key: string;
|
|
6
|
+
/** The value of a component that reads the context without a provider above it. */
|
|
7
|
+
readonly defaultValue: T;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Creates a context. `key` names it in the page state, so it must be unique
|
|
11
|
+
* in the app and the same on the server and the client.
|
|
12
|
+
*/
|
|
13
|
+
declare function createContext<T>(key: string, defaultValue: T): Context<T>;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { createContext as n, Context as t };
|
|
16
|
+
//# sourceMappingURL=context-aeo9esY9.d.ts.map
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
//#region src/runtime/cookies.ts
|
|
2
|
+
/** Reads the cookies of a `cookie` header. */
|
|
3
|
+
function parseCookies(header) {
|
|
4
|
+
const result = {};
|
|
5
|
+
for (const part of (header ?? "").split(";")) {
|
|
6
|
+
const index = part.indexOf("=");
|
|
7
|
+
if (index === -1) continue;
|
|
8
|
+
const name = part.slice(0, index).trim();
|
|
9
|
+
if (name && !(name in result)) {
|
|
10
|
+
const value = part.slice(index + 1).trim();
|
|
11
|
+
try {
|
|
12
|
+
result[name] = decodeURIComponent(value);
|
|
13
|
+
} catch {
|
|
14
|
+
result[name] = value;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
/** Writes a `set-cookie` header value. */
|
|
21
|
+
function serializeCookie(name, value, options = {}) {
|
|
22
|
+
if (!/^[\w!#$%&'*+.^`|~-]+$/.test(name)) throw new Error(`"${name}" is not a valid cookie name`);
|
|
23
|
+
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? "/"}`];
|
|
24
|
+
if (options.maxAge !== void 0) parts.push(`Max-Age=${Math.floor(options.maxAge)}`);
|
|
25
|
+
if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);
|
|
26
|
+
if (options.domain) parts.push(`Domain=${options.domain}`);
|
|
27
|
+
if (options.httpOnly !== false) parts.push("HttpOnly");
|
|
28
|
+
if (options.secure) parts.push("Secure");
|
|
29
|
+
parts.push(`SameSite=${(options.sameSite ?? "lax").replace(/^./, (letter) => letter.toUpperCase())}`);
|
|
30
|
+
return parts.join("; ");
|
|
31
|
+
}
|
|
32
|
+
/** The cookies of the request, with the ones that this request set or deleted. */
|
|
33
|
+
function getCookies(event) {
|
|
34
|
+
const result = parseCookies(event.request.headers.get("cookie"));
|
|
35
|
+
for (const [name, value] of event.cookies ?? []) if (value === void 0) delete result[name];
|
|
36
|
+
else result[name] = value;
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
/** Sets a cookie on the response of an event. See `RequestEvent.setCookie`. */
|
|
40
|
+
function setCookie(event, name, value, options = {}) {
|
|
41
|
+
const secure = options.secure ?? new URL(event.request.url).protocol === "https:";
|
|
42
|
+
event.headers.append("set-cookie", serializeCookie(name, value, {
|
|
43
|
+
...options,
|
|
44
|
+
secure
|
|
45
|
+
}));
|
|
46
|
+
event.cookies ??= /* @__PURE__ */ new Map();
|
|
47
|
+
event.cookies.set(name, value);
|
|
48
|
+
}
|
|
49
|
+
/** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */
|
|
50
|
+
function deleteCookie(event, name, options = {}) {
|
|
51
|
+
const secure = new URL(event.request.url).protocol === "https:";
|
|
52
|
+
event.headers.append("set-cookie", serializeCookie(name, "", {
|
|
53
|
+
...options,
|
|
54
|
+
secure,
|
|
55
|
+
maxAge: 0,
|
|
56
|
+
expires: /* @__PURE__ */ new Date(0)
|
|
57
|
+
}));
|
|
58
|
+
event.cookies ??= /* @__PURE__ */ new Map();
|
|
59
|
+
event.cookies.set(name, void 0);
|
|
60
|
+
}
|
|
61
|
+
const encoder = new TextEncoder();
|
|
62
|
+
const keys = /* @__PURE__ */ new Map();
|
|
63
|
+
function key(secret) {
|
|
64
|
+
let promise = keys.get(secret);
|
|
65
|
+
if (!promise) {
|
|
66
|
+
promise = crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
67
|
+
name: "HMAC",
|
|
68
|
+
hash: "SHA-256"
|
|
69
|
+
}, false, ["sign", "verify"]);
|
|
70
|
+
keys.set(secret, promise);
|
|
71
|
+
}
|
|
72
|
+
return promise;
|
|
73
|
+
}
|
|
74
|
+
function toBase64Url(bytes) {
|
|
75
|
+
let text = "";
|
|
76
|
+
for (const byte of bytes) text += String.fromCharCode(byte);
|
|
77
|
+
return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
78
|
+
}
|
|
79
|
+
function fromBase64Url(text) {
|
|
80
|
+
const base64 = text.replace(/-/g, "+").replace(/_/g, "/");
|
|
81
|
+
return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* A session in a signed cookie. The browser can read the data, but cannot
|
|
85
|
+
* change it, so keep secrets out of it: store an ID, and look the rest up
|
|
86
|
+
* on the server.
|
|
87
|
+
*
|
|
88
|
+
* ```ts
|
|
89
|
+
* export const session = createSession<{ userId: string }>({ secret: process.env.SESSION_SECRET! });
|
|
90
|
+
*
|
|
91
|
+
* async function login(form: FormData) {
|
|
92
|
+
* 'use server';
|
|
93
|
+
* const event = getEvent();
|
|
94
|
+
* await session.set(event, { userId: await checkPassword(form) });
|
|
95
|
+
* }
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
function createSession(options) {
|
|
99
|
+
const secrets = Array.isArray(options.secret) ? options.secret : [options.secret];
|
|
100
|
+
if (secrets.length === 0 || secrets.some((secret) => secret.length < 32)) throw new Error("A session secret needs at least 32 characters");
|
|
101
|
+
const name = options.name ?? "session";
|
|
102
|
+
const maxAge = options.maxAge ?? 604800;
|
|
103
|
+
const read = async (event) => {
|
|
104
|
+
const value = getCookies(event)[name];
|
|
105
|
+
const dot = value?.lastIndexOf(".") ?? -1;
|
|
106
|
+
if (!value || dot === -1) return;
|
|
107
|
+
const payload = value.slice(0, dot);
|
|
108
|
+
let signature;
|
|
109
|
+
try {
|
|
110
|
+
signature = fromBase64Url(value.slice(dot + 1));
|
|
111
|
+
} catch {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (!(await Promise.all(secrets.map(async (secret) => crypto.subtle.verify("HMAC", await key(secret), signature, encoder.encode(payload))))).includes(true)) return;
|
|
115
|
+
try {
|
|
116
|
+
const { d: data, e: expires } = JSON.parse(new TextDecoder().decode(fromBase64Url(payload)));
|
|
117
|
+
return expires > Date.now() ? data : void 0;
|
|
118
|
+
} catch {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const write = async (event, data) => {
|
|
123
|
+
const payload = toBase64Url(encoder.encode(JSON.stringify({
|
|
124
|
+
d: data,
|
|
125
|
+
e: Date.now() + maxAge * 1e3
|
|
126
|
+
})));
|
|
127
|
+
const value = `${payload}.${toBase64Url(new Uint8Array(await crypto.subtle.sign("HMAC", await key(secrets[0]), encoder.encode(payload))))}`;
|
|
128
|
+
if (value.length > 4e3) throw new Error(`The session is ${value.length} bytes, over the 4000 that a cookie can hold. Store an ID in it instead`);
|
|
129
|
+
setCookie(event, name, value, {
|
|
130
|
+
...options.cookie,
|
|
131
|
+
maxAge
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
return {
|
|
135
|
+
get: read,
|
|
136
|
+
set: write,
|
|
137
|
+
async update(event, change) {
|
|
138
|
+
const data = {
|
|
139
|
+
...await read(event),
|
|
140
|
+
...change
|
|
141
|
+
};
|
|
142
|
+
await write(event, data);
|
|
143
|
+
return data;
|
|
144
|
+
},
|
|
145
|
+
clear: (event) => deleteCookie(event, name, {
|
|
146
|
+
path: options.cookie?.path,
|
|
147
|
+
domain: options.cookie?.domain
|
|
148
|
+
})
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The headers of a response for Node's `writeHead`, with each `set-cookie`
|
|
153
|
+
* apart. `Object.fromEntries(headers)` joins them into one, which browsers
|
|
154
|
+
* read as a single cookie.
|
|
155
|
+
*/
|
|
156
|
+
function toNodeHeaders(headers) {
|
|
157
|
+
const result = Object.fromEntries(headers);
|
|
158
|
+
const cookies = headers.getSetCookie();
|
|
159
|
+
if (cookies.length > 0) result["set-cookie"] = cookies;
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
export { serializeCookie as a, parseCookies as i, deleteCookie as n, setCookie as o, getCookies as r, toNodeHeaders as s, createSession as t };
|
|
164
|
+
|
|
165
|
+
//# sourceMappingURL=cookies-rgIAc8IE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cookies-rgIAc8IE.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 cookies of the request, with the ones that this request set or deleted. */\nexport function getCookies(event: RequestEvent): Record<string, string> {\n const result = parseCookies(event.request.headers.get('cookie'));\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 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 const secure = new URL(event.request.url).protocol === 'https:';\n event.headers.append(\n 'set-cookie',\n serializeCookie(name, '', { ...options, secure, maxAge: 0, expires: new Date(0) }),\n );\n event.cookies ??= new Map();\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 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 if (secrets.length === 0 || secrets.some((secret) => secret.length < 32)) {\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 const read = async (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 checks = await Promise.all(\n secrets.map(async (secret) =>\n crypto.subtle.verify('HMAC', await key(secret), signature, encoder.encode(payload)),\n ),\n );\n if (!checks.includes(true)) {\n return undefined;\n }\n try {\n const { d: data, e: expires } = JSON.parse(\n new TextDecoder().decode(fromBase64Url(payload)),\n ) as {\n d: T;\n e: number;\n };\n return expires > Date.now() ? data : undefined;\n } catch {\n return undefined;\n }\n };\n\n const write = async (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,GAAG;EAC9B,IAAI,UAAU,IACZ;EAEF,MAAM,OAAO,KAAK,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK;EACvC,IAAI,QAAQ,EAAE,QAAQ,SAAS;GAC7B,MAAM,QAAQ,KAAK,MAAM,QAAQ,CAAC,CAAC,CAAC,KAAK;GACzC,IAAI;IACF,OAAO,QAAQ,mBAAmB,KAAK;GACzC,QAAQ;IACN,OAAO,QAAQ;GACjB;EACF;CACF;CACA,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAc,OAAe,UAAyB,CAAC,GAAW;CAChG,IAAI,CAAC,wBAAwB,KAAK,IAAI,GACpC,MAAM,IAAI,MAAM,IAAI,KAAK,6BAA6B;CAExD,MAAM,QAAQ,C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