brumate 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{boot-DN1ZU8Hg.d.ts → boot-C25Sa6vq.d.ts} +27 -2
- package/dist/cli.js +2 -2
- package/dist/client-BD6XT-s5.js +1968 -0
- package/dist/client-BD6XT-s5.js.map +1 -0
- package/dist/{client-DwJInP_a.d.ts → client-D0CqSxoO.d.ts} +211 -30
- package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
- package/dist/client-routes-JTbGtukf.js.map +1 -0
- package/dist/context-CTiSzQRc.js +27 -0
- package/dist/context-CTiSzQRc.js.map +1 -0
- package/dist/context-btHuB01Z.d.ts +42 -0
- package/dist/{cookies-Av5WFmcf.js → cookies-BzllthiF.js} +2 -1
- package/dist/cookies-BzllthiF.js.map +1 -0
- package/dist/defer-BbD7JQhj.js +56 -0
- package/dist/defer-BbD7JQhj.js.map +1 -0
- package/dist/devtools-CQgD7NPB.js +623 -0
- package/dist/devtools-CQgD7NPB.js.map +1 -0
- package/dist/devtools-panel-BVB-W5q4.js +1930 -0
- package/dist/devtools-panel-BVB-W5q4.js.map +1 -0
- package/dist/events-CSs7OwIC.js +85 -0
- package/dist/events-CSs7OwIC.js.map +1 -0
- package/dist/{files-DdT84mPy.js → files-BXSSrQgc.js} +34 -6
- package/dist/files-BXSSrQgc.js.map +1 -0
- package/dist/forms-Bg-CwGqX.js +406 -0
- package/dist/forms-Bg-CwGqX.js.map +1 -0
- package/dist/forms-Cl21hkHt.d.ts +281 -0
- package/dist/highlight.d.ts +17 -0
- package/dist/highlight.js +269 -0
- package/dist/highlight.js.map +1 -0
- package/dist/html-Bq1rFxX_.d.ts +92 -0
- package/dist/html-mNTKzaDD.js +241 -0
- package/dist/html-mNTKzaDD.js.map +1 -0
- package/dist/index.d.ts +123 -30
- package/dist/index.js +14 -6
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BPchdWbU.js → inspect-BHpOw1LF.js} +1400 -121
- package/dist/inspect-BHpOw1LF.js.map +1 -0
- package/dist/{loader-Dc9OwY5I.js → loader-Dos_3NP0.js} +47 -11
- package/dist/loader-Dos_3NP0.js.map +1 -0
- package/dist/{navigate-CzLjnoPH.js → navigate-O78d_zGN.js} +115 -13
- package/dist/navigate-O78d_zGN.js.map +1 -0
- package/dist/produce-D0V0ICkz.d.ts +114 -0
- package/dist/produce-Doc91GkX.js +274 -0
- package/dist/produce-Doc91GkX.js.map +1 -0
- package/dist/routes-BZNt7DSZ.d.ts +38 -0
- package/dist/{rpc-9fSqL_YK.js → rpc-ygMRPmN4.js} +39 -23
- package/dist/rpc-ygMRPmN4.js.map +1 -0
- package/dist/runtime/batch.d.ts +23 -0
- package/dist/runtime/batch.js +69 -0
- package/dist/runtime/batch.js.map +1 -0
- package/dist/runtime/client.d.ts +5 -5
- package/dist/runtime/client.js +5 -1345
- package/dist/runtime/context.d.ts +2 -2
- package/dist/runtime/context.js +1 -1
- package/dist/runtime/devtools.d.ts +191 -5
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/env.d.ts +44 -0
- package/dist/runtime/env.js +61 -0
- package/dist/runtime/env.js.map +1 -0
- package/dist/runtime/events.d.ts +42 -0
- package/dist/runtime/events.js +1 -0
- package/dist/runtime/forms.d.ts +2 -0
- package/dist/runtime/forms.js +1 -0
- package/dist/runtime/gather.d.ts +25 -0
- package/dist/runtime/gather.js +33 -0
- package/dist/runtime/gather.js.map +1 -0
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.d.ts +2 -21
- package/dist/runtime/routes.js +31 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +7 -5
- package/dist/runtime/server.js +6 -7
- package/dist/runtime/signals.d.ts +60 -3
- package/dist/runtime/signals.js +40 -2
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +46 -5
- package/dist/runtime/testing.js +240 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/runtime/values.d.ts +2 -0
- package/dist/runtime/values.js +24 -0
- package/dist/runtime/values.js.map +1 -0
- package/dist/secrets-BxagsJxJ.js +23 -0
- package/dist/secrets-BxagsJxJ.js.map +1 -0
- package/dist/server-CxVDYE_V.js +3417 -0
- package/dist/server-CxVDYE_V.js.map +1 -0
- package/dist/server-DuFYRXrd.d.ts +1460 -0
- package/dist/skew-FRmAy9iy.js +49 -0
- package/dist/skew-FRmAy9iy.js.map +1 -0
- package/dist/standard-schema-BNY82yX3.d.ts +63 -0
- package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-Drpr0AzI.d.ts} +2 -2
- package/dist/static-loader-nZssh66R.js +333 -0
- package/dist/static-loader-nZssh66R.js.map +1 -0
- package/dist/stream-DCYZO4IF.js +424 -0
- package/dist/stream-DCYZO4IF.js.map +1 -0
- package/dist/values-B8C7CLvG.d.ts +63 -0
- package/dist/vite.d.ts +49 -1
- package/dist/vite.js +598 -68
- package/dist/vite.js.map +1 -1
- package/forms/forms.brm.ts +141 -0
- package/package.json +45 -3
- package/types.d.ts +9 -1
- package/dist/client-routes-DakuM32C.js.map +0 -1
- package/dist/context-BG8KCF3v.js +0 -15
- package/dist/context-BG8KCF3v.js.map +0 -1
- package/dist/context-aeo9esY9.d.ts +0 -16
- package/dist/cookies-Av5WFmcf.js.map +0 -1
- package/dist/devtools-BKjnHrnv.js +0 -113
- package/dist/devtools-BKjnHrnv.js.map +0 -1
- package/dist/devtools-panel-AWOn0VK2.js +0 -434
- package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
- package/dist/files-DdT84mPy.js.map +0 -1
- package/dist/html-DEeoepg3.js +0 -152
- package/dist/html-DEeoepg3.js.map +0 -1
- package/dist/html-Du8jY2Cc.d.ts +0 -53
- package/dist/inspect-BPchdWbU.js.map +0 -1
- package/dist/loader-Dc9OwY5I.js.map +0 -1
- package/dist/navigate-CzLjnoPH.js.map +0 -1
- package/dist/produce-BRGHP7e0.js +0 -126
- package/dist/produce-BRGHP7e0.js.map +0 -1
- package/dist/produce-CtZ32UGG.d.ts +0 -60
- package/dist/rpc-9fSqL_YK.js.map +0 -1
- package/dist/runtime/client.js.map +0 -1
- package/dist/server-BxqjLUnV.d.ts +0 -753
- package/dist/server-DZsgnPKS.js +0 -1615
- package/dist/server-DZsgnPKS.js.map +0 -1
- package/dist/shared-CWYOd0H3.js +0 -40
- package/dist/shared-CWYOd0H3.js.map +0 -1
- package/dist/static-loader-ClNkHZGn.js +0 -185
- package/dist/static-loader-ClNkHZGn.js.map +0 -1
- package/dist/stream-bgNCMcaA.js +0 -280
- package/dist/stream-bgNCMcaA.js.map +0 -1
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// `createForm`, the component side of progressive forms. It is a module
|
|
2
|
+
// function, so the compiler copies it into the component that calls it, and
|
|
3
|
+
// its state resumes with the page.
|
|
4
|
+
|
|
5
|
+
import { prevent } from 'brumate/events';
|
|
6
|
+
import { $action, $effect, $handler, $id, $memo, $signal } from 'brumate/signals';
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_SUBMIT,
|
|
9
|
+
applyLocalIntent,
|
|
10
|
+
checkField,
|
|
11
|
+
checkedSince,
|
|
12
|
+
formErrorsOf,
|
|
13
|
+
formFields,
|
|
14
|
+
validateValues,
|
|
15
|
+
} from 'brumate/forms/core';
|
|
16
|
+
import type { CheckedErrors, Intent, LocalChanges, SubmissionResult } from 'brumate/forms/core';
|
|
17
|
+
import type { StandardSchemaV1 } from 'brumate/server';
|
|
18
|
+
|
|
19
|
+
export type {
|
|
20
|
+
Field,
|
|
21
|
+
FieldAttributes,
|
|
22
|
+
FieldState,
|
|
23
|
+
Fields,
|
|
24
|
+
IntentAttributes,
|
|
25
|
+
ListItem,
|
|
26
|
+
SubmissionResult,
|
|
27
|
+
} from 'brumate/forms/core';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The values of a form: the input of its schema, or the type of the default
|
|
31
|
+
* value when the schema does not type its input.
|
|
32
|
+
*/
|
|
33
|
+
export type FormValue<S extends StandardSchemaV1, D> =
|
|
34
|
+
unknown extends StandardSchemaV1.InferInput<S> ? D : StandardSchemaV1.InferInput<S>;
|
|
35
|
+
|
|
36
|
+
/** The options of `createForm`. */
|
|
37
|
+
export interface FormOptions<T> {
|
|
38
|
+
/**
|
|
39
|
+
* The values that the fields show before a submit. It names every field
|
|
40
|
+
* of the form, and a list of objects has one item, which new items take
|
|
41
|
+
* the fields of.
|
|
42
|
+
*/
|
|
43
|
+
defaultValue?: T;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The state of a form that posts to a server function, which answers with
|
|
48
|
+
* `parseSubmission(…).reply()`. It gives the attributes of the form, of its
|
|
49
|
+
* fields and of the buttons of its lists, with the posted values and the
|
|
50
|
+
* errors of the last submit. The form works without scripts, and with
|
|
51
|
+
* scripts it posts without loading the page.
|
|
52
|
+
*
|
|
53
|
+
* ```brm
|
|
54
|
+
* <script>
|
|
55
|
+
* import { createForm } from 'brumate/forms';
|
|
56
|
+
*
|
|
57
|
+
* const { attrs, fields, errors, defaultSubmit } = createForm(save, Order, {
|
|
58
|
+
* defaultValue: { email: '' },
|
|
59
|
+
* });
|
|
60
|
+
* </script>
|
|
61
|
+
*
|
|
62
|
+
* <form action=save {...attrs}>
|
|
63
|
+
* <button {...defaultSubmit}></button>
|
|
64
|
+
* <input {...fields.email.attrs} type="email">
|
|
65
|
+
* </form>
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
export function createForm<S extends StandardSchemaV1, D = StandardSchemaV1.InferInput<S>>(
|
|
69
|
+
action: (form: FormData) => Promise<SubmissionResult>,
|
|
70
|
+
schema: S,
|
|
71
|
+
options: FormOptions<D> = {},
|
|
72
|
+
) {
|
|
73
|
+
const result = $action(action);
|
|
74
|
+
const id = $id();
|
|
75
|
+
// The errors that the browser found since the last reply.
|
|
76
|
+
let checked = $signal<CheckedErrors | undefined>(undefined);
|
|
77
|
+
// The changes of lists that the browser made since the last reply.
|
|
78
|
+
let local = $signal<LocalChanges | undefined>(undefined);
|
|
79
|
+
|
|
80
|
+
// Applies the intent of a button of a list at once. Its `prevent` stops the post of the form,
|
|
81
|
+
// even before this code loads.
|
|
82
|
+
async function change(intent: Intent) {
|
|
83
|
+
const next = applyLocalIntent(
|
|
84
|
+
document.getElementById(id) as HTMLFormElement | null,
|
|
85
|
+
intent,
|
|
86
|
+
local,
|
|
87
|
+
result,
|
|
88
|
+
);
|
|
89
|
+
if (!next) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
local = next;
|
|
93
|
+
// The errors that show follow the items to where they are now.
|
|
94
|
+
const current = checkedSince(checked, result);
|
|
95
|
+
if (current) {
|
|
96
|
+
checked = { ...current, ...(await validateValues(schema, next.value)) };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const press = (intent: Intent) => $handler(prevent(change), intent);
|
|
100
|
+
|
|
101
|
+
const fields = $memo(
|
|
102
|
+
formFields(id, options.defaultValue as FormValue<S, D> | undefined, result, {
|
|
103
|
+
checked,
|
|
104
|
+
local,
|
|
105
|
+
press,
|
|
106
|
+
}),
|
|
107
|
+
);
|
|
108
|
+
const errors = $memo(formErrorsOf(result, checked));
|
|
109
|
+
|
|
110
|
+
// Validates with the schema when the user leaves a field, and as the user types in a field
|
|
111
|
+
// that shows its errors. The code of the schema loads with the first of these events.
|
|
112
|
+
async function check(event: Event) {
|
|
113
|
+
const next = await checkField(
|
|
114
|
+
schema,
|
|
115
|
+
document.getElementById(id) as HTMLFormElement | null,
|
|
116
|
+
(event.target as HTMLInputElement).name,
|
|
117
|
+
event.type === 'focusout',
|
|
118
|
+
checked,
|
|
119
|
+
result,
|
|
120
|
+
);
|
|
121
|
+
if (next) {
|
|
122
|
+
checked = next;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// A reply that resets the form sets the fields back to their default values,
|
|
127
|
+
// which the browser keeps in their attributes.
|
|
128
|
+
$effect(() => {
|
|
129
|
+
if (result?.reset) {
|
|
130
|
+
(document.getElementById(id) as HTMLFormElement | null)?.reset();
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
result,
|
|
136
|
+
fields,
|
|
137
|
+
errors,
|
|
138
|
+
attrs: { id, onFocusout: $handler(check), onInput: $handler(check) },
|
|
139
|
+
defaultSubmit: DEFAULT_SUBMIT,
|
|
140
|
+
};
|
|
141
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brumate",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "A component language and compiler for resumable web apps",
|
|
5
5
|
"homepage": "https://github.com/lxsmnsyc/brumate",
|
|
6
6
|
"bugs": "https://github.com/lxsmnsyc/brumate/issues",
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
},
|
|
17
17
|
"files": [
|
|
18
18
|
"dist",
|
|
19
|
-
"types.d.ts"
|
|
19
|
+
"types.d.ts",
|
|
20
|
+
"forms"
|
|
20
21
|
],
|
|
21
22
|
"type": "module",
|
|
22
23
|
"exports": {
|
|
@@ -63,6 +64,34 @@
|
|
|
63
64
|
"types": "./dist/runtime/routes.d.ts",
|
|
64
65
|
"default": "./dist/runtime/routes.js"
|
|
65
66
|
},
|
|
67
|
+
"./batch": {
|
|
68
|
+
"types": "./dist/runtime/batch.d.ts",
|
|
69
|
+
"default": "./dist/runtime/batch.js"
|
|
70
|
+
},
|
|
71
|
+
"./events": {
|
|
72
|
+
"types": "./dist/runtime/events.d.ts",
|
|
73
|
+
"default": "./dist/runtime/events.js"
|
|
74
|
+
},
|
|
75
|
+
"./stream": {
|
|
76
|
+
"types": "./dist/runtime/gather.d.ts",
|
|
77
|
+
"default": "./dist/runtime/gather.js"
|
|
78
|
+
},
|
|
79
|
+
"./serial": {
|
|
80
|
+
"types": "./dist/runtime/values.d.ts",
|
|
81
|
+
"default": "./dist/runtime/values.js"
|
|
82
|
+
},
|
|
83
|
+
"./highlight": {
|
|
84
|
+
"types": "./dist/highlight.d.ts",
|
|
85
|
+
"default": "./dist/highlight.js"
|
|
86
|
+
},
|
|
87
|
+
"./forms": {
|
|
88
|
+
"types": "./forms/forms.brm.ts",
|
|
89
|
+
"default": "./forms/forms.brm.ts"
|
|
90
|
+
},
|
|
91
|
+
"./forms/core": {
|
|
92
|
+
"types": "./dist/runtime/forms.d.ts",
|
|
93
|
+
"default": "./dist/runtime/forms.js"
|
|
94
|
+
},
|
|
66
95
|
"./devtools": {
|
|
67
96
|
"types": "./dist/runtime/devtools.d.ts",
|
|
68
97
|
"default": "./dist/runtime/devtools.js"
|
|
@@ -75,16 +104,25 @@
|
|
|
75
104
|
"types": "./dist/runtime/testing.d.ts",
|
|
76
105
|
"default": "./dist/runtime/testing.js"
|
|
77
106
|
},
|
|
107
|
+
"./env": {
|
|
108
|
+
"types": "./dist/runtime/env.d.ts",
|
|
109
|
+
"default": "./dist/runtime/env.js"
|
|
110
|
+
},
|
|
78
111
|
"./package.json": "./package.json"
|
|
79
112
|
},
|
|
80
113
|
"publishConfig": {
|
|
81
114
|
"access": "public"
|
|
82
115
|
},
|
|
83
116
|
"dependencies": {
|
|
117
|
+
"@twinkleplop/core": "0.3.1",
|
|
118
|
+
"@twinkleplop/css": "0.1.7",
|
|
119
|
+
"@twinkleplop/theme-github": "0.2.4",
|
|
120
|
+
"@twinkleplop/tsx": "0.1.7",
|
|
84
121
|
"oxc-parser": "^0.154.0",
|
|
85
122
|
"postcss": "^8.5.31",
|
|
86
123
|
"postcss-selector-parser": "^7.1.6",
|
|
87
|
-
"seroval": "^1.7.0"
|
|
124
|
+
"seroval": "^1.7.0",
|
|
125
|
+
"seroval-plugins": "^1.7.0"
|
|
88
126
|
},
|
|
89
127
|
"devDependencies": {
|
|
90
128
|
"@oxc-project/types": "^0.154.0",
|
|
@@ -117,6 +155,10 @@
|
|
|
117
155
|
"engines": {
|
|
118
156
|
"node": ">=22"
|
|
119
157
|
},
|
|
158
|
+
"brumate": {
|
|
159
|
+
"version": 1,
|
|
160
|
+
"dir": "forms"
|
|
161
|
+
},
|
|
120
162
|
"scripts": {
|
|
121
163
|
"build": "tsdown",
|
|
122
164
|
"test": "vitest run",
|
package/types.d.ts
CHANGED
|
@@ -12,6 +12,11 @@ declare module 'virtual:brumate/testing' {
|
|
|
12
12
|
* the app, until the returned function restores `fetch`.
|
|
13
13
|
*/
|
|
14
14
|
export function answerCalls(options?: import('brumate/testing').AnswerOptions): () => void;
|
|
15
|
+
/**
|
|
16
|
+
* Visits a path of the app, as a browser that runs scripts does. The
|
|
17
|
+
* routes of the app answer the page and every request that it makes.
|
|
18
|
+
*/
|
|
19
|
+
export const visit: import('brumate/testing').Visit;
|
|
15
20
|
}
|
|
16
21
|
|
|
17
22
|
declare module '*.brm' {
|
|
@@ -29,7 +34,10 @@ declare module 'virtual:brumate/manifest' {
|
|
|
29
34
|
|
|
30
35
|
declare module 'virtual:brumate/server' {
|
|
31
36
|
export const functions: Record<string, (...args: any[]) => unknown>;
|
|
32
|
-
export function handle(
|
|
37
|
+
export function handle(
|
|
38
|
+
request: Request,
|
|
39
|
+
options?: import('brumate/server').RequestOptions,
|
|
40
|
+
): Promise<Response | undefined>;
|
|
33
41
|
}
|
|
34
42
|
|
|
35
43
|
declare module 'virtual:brumate/routes' {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-routes-DakuM32C.js","names":[],"sources":["../src/runtime/client-routes.ts"],"sourcesContent":["// What the core needs to read the pages that client navigation adds. Only\n// `navigate.ts` writes the attributes that this module reads, so the loader\n// imports it when it navigates or finds such a record, and a page that never\n// navigates does not load it. Importing it sets the core's `record` hook.\n//\n// It reads the core with `import()`, as `rpc.ts` does, and imports nothing\n// else. A static import of the core would make the package build move the\n// core into a chunk behind a module that only re-exports it, and a static\n// import of `shared.ts` would split that module out of the core of a page.\n// The core is loaded already, or loads with this module.\n\nimport type * as Client from './client.ts';\nimport type { Scope } from './client.ts';\nimport type { PageState, ScopeState } from './shared.ts';\n\n/** The parts of the core that this module uses. */\ntype Core = Pick<\n typeof Client,\n 'ElementReference' | 'FunctionReference' | 'hooks' | 'removeScope' | 'scopes'\n>;\n\n/** Adds a number to the scope IDs of a state record. */\nfunction shiftState(core: Core, state: PageState, by: number): PageState {\n const { ElementReference, FunctionReference } = core;\n const seen = new Set<object>();\n // References to elements and client functions name the scope of their markup.\n const shiftValue = (value: unknown): unknown => {\n if (value instanceof ElementReference) {\n return new ElementReference(value.scope + by, value.anchor);\n }\n if (value instanceof FunctionReference) {\n return new FunctionReference(value.ref, value.scope + by);\n }\n // A later record settles it, with a value whose IDs move too.\n if (value instanceof Promise) {\n return value.then(shiftValue);\n }\n if (typeof value === 'object' && value !== null && !seen.has(value)) {\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n value[index] = shiftValue(item);\n });\n } else if (Object.getPrototypeOf(value) === Object.prototype) {\n for (const [key, item] of Object.entries(value)) {\n (value as Record<string, unknown>)[key] = shiftValue(item);\n }\n }\n }\n return value;\n };\n const result: PageState = {};\n for (const [key, record] of Object.entries(state)) {\n result[Number(key) + by] = {\n ...record,\n p: record.p === undefined ? undefined : record.p + by,\n o: record.o === undefined ? undefined : record.o + by,\n c:\n record.c &&\n Object.fromEntries(Object.entries(record.c).map(([anchor, id]) => [anchor, id + by])),\n s: record.s?.map(shiftValue),\n };\n }\n return result;\n}\n\n/** Removes scopes and the scopes inside them, and runs their cleanups. */\nfunction dropScopes(core: Core, roots: Set<number>): void {\n const inside = (scope: Scope): boolean => {\n for (let current: Scope | undefined = scope; current; current = current.p ?? current.o) {\n if (roots.has(current.id)) {\n return true;\n }\n }\n return false;\n };\n // Deleting from a map while iterating it is safe.\n for (const scope of core.scopes.values()) {\n if (inside(scope)) {\n core.removeScope(scope);\n }\n }\n}\n\n/**\n * Reads the attributes that navigation set on a state record. A page whose\n * IDs started at another number, such as a prerendered file, has them moved\n * with `b-offset`. A page that replaced only some routes of the one before\n * it drops the old routes with `b-drop`, and adds only the scopes inside\n * `b-roots`, with the scopes of the kept layouts in place of the new\n * page's copies of them, by `b-alias`.\n */\nfunction routeRecord(core: Core, script: Element, state: PageState): PageState {\n // Only records with scopes hold IDs. Later records settle promises, which `shiftState` wraps.\n const offset = Number(script.getAttribute('b-offset') ?? 0);\n const value = offset ? shiftState(core, state, offset) : state;\n const drop = script.getAttribute('b-drop');\n if (drop) {\n dropScopes(core, new Set(drop.split(',').map(Number)));\n }\n const list = script.getAttribute('b-roots');\n if (list === null) {\n return value;\n }\n const roots = new Set(list.split(',').filter(Boolean).map(Number));\n const alias = new Map<number, number>();\n for (const pair of (script.getAttribute('b-alias') ?? '').split(',').filter(Boolean)) {\n const [from, to] = pair.split(':').map(Number) as [number, number];\n alias.set(from, to);\n }\n const kept = (id: number): boolean => {\n for (let current: number | undefined = id; current !== undefined;) {\n if (roots.has(current)) {\n return true;\n }\n const record: ScopeState | undefined = value[current];\n current = record?.p ?? record?.o;\n }\n return false;\n };\n const resolve = (id: number | undefined): number | undefined =>\n id === undefined ? undefined : (alias.get(id) ?? id);\n const result: PageState = {};\n for (const [key, record] of Object.entries(value)) {\n // The new page renders the kept layouts again. Their scopes are not added.\n if (kept(Number(key))) {\n result[Number(key)] = { ...record, p: resolve(record.p), o: resolve(record.o) };\n }\n }\n return result;\n}\n\n/**\n * Settles once the core reads records with this module, with the function\n * that forgets the page before navigation replaces it, or only stops reading\n * when layouts stay.\n */\nexport const ready: Promise<(partial: boolean) => void> = import('./client.ts').then(\n ({ ElementReference, FunctionReference, hooks, leavePage, leaveRoutes, removeScope, scopes }) => {\n const core = { ElementReference, FunctionReference, hooks, removeScope, scopes };\n hooks.record = (script, state) => routeRecord(core, script, state);\n return (partial) => (partial ? leaveRoutes() : leavePage());\n },\n);\n"],"mappings":";;AAsBA,SAAS,WAAW,MAAY,OAAkB,IAAuB;CACvE,MAAM,EAAE,kBAAkB,sBAAsB;CAChD,MAAM,uBAAO,IAAI,IAAY;CAE7B,MAAM,cAAc,UAA4B;EAC9C,IAAI,iBAAiB,kBACnB,OAAO,IAAI,iBAAiB,MAAM,QAAQ,IAAI,MAAM,MAAM;EAE5D,IAAI,iBAAiB,mBACnB,OAAO,IAAI,kBAAkB,MAAM,KAAK,MAAM,QAAQ,EAAE;EAG1D,IAAI,iBAAiB,SACnB,OAAO,MAAM,KAAK,UAAU;EAE9B,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,KAAK,IAAI,KAAK,GAAG;GACnE,KAAK,IAAI,KAAK;GACd,IAAI,MAAM,QAAQ,KAAK,GACrB,MAAM,SAAS,MAAM,UAAU;IAC7B,MAAM,SAAS,WAAW,IAAI;GAChC,CAAC;QACI,IAAI,OAAO,eAAe,KAAK,MAAM,OAAO,WACjD,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAK,GAC5C,MAAmC,OAAO,WAAW,IAAI;EAG/D;EACA,OAAO;CACT;CACA,MAAM,SAAoB,CAAC;CAC3B,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,KAAK,GAC9C,OAAO,OAAO,GAAG,IAAI,MAAM;EACzB,GAAG;EACH,GAAG,OAAO,MAAM,KAAA,IAAY,KAAA,IAAY,OAAO,IAAI;EACnD,GAAG,OAAO,MAAM,KAAA,IAAY,KAAA,IAAY,OAAO,IAAI;EACnD,GACE,OAAO,KACP,OAAO,YAAY,OAAO,QAAQ,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,QAAQ,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC;EACtF,GAAG,OAAO,GAAG,IAAI,UAAU;CAC7B;CAEF,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IAAY,KAAA,IAAa,MAAM,IAAI,EAAE,KAAK;CACnD,MAAM,SAAoB,CAAC;CAC3B,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,KAAK,GAE9C,IAAI,KAAK,OAAO,GAAG,CAAC,GAClB,OAAO,OAAO,GAAG,KAAK;EAAE,GAAG;EAAQ,GAAG,QAAQ,OAAO,CAAC;EAAG,GAAG,QAAQ,OAAO,CAAC;CAAE;CAGlF,OAAO;AACT;;;;;;AAOA,MAAa,QAA6C,OAAO,sBAAc,CAAC,MAC7E,EAAE,kBAAkB,mBAAmB,OAAO,WAAW,aAAa,aAAa,aAAa;CAC/F,MAAM,OAAO;EAAE;EAAkB;EAAmB;EAAO;EAAa;CAAO;CAC/E,MAAM,UAAU,QAAQ,UAAU,YAAY,MAAM,QAAQ,KAAK;CACjE,QAAQ,YAAa,UAAU,YAAY,IAAI,UAAU;AAC3D,CACF"}
|
package/dist/context-BG8KCF3v.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
|
@@ -1,16 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cookies-Av5WFmcf.js","names":[],"sources":["../src/runtime/cookies.ts"],"sourcesContent":["// Cookies and sessions, for server functions, rendering, middleware and\n// endpoints. They read the request of a `RequestEvent` and write `set-cookie`\n// headers on its response.\n\nimport type { RequestEvent } from './request.ts';\n\nexport interface CookieOptions {\n /** Seconds until the cookie expires. Without it, the cookie lasts until the browser closes. */\n maxAge?: number;\n expires?: Date;\n /** Defaults to `/`. */\n path?: string;\n domain?: string;\n /** Defaults to true when the request is HTTPS. */\n secure?: boolean;\n /** Keeps the cookie from browser code. Defaults to true. */\n httpOnly?: boolean;\n /** Defaults to `lax`. */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\n/** Reads the cookies of a `cookie` header. */\nexport function parseCookies(header: string | null): Record<string, string> {\n const result: Record<string, string> = {};\n for (const part of (header ?? '').split(';')) {\n const index = part.indexOf('=');\n if (index === -1) {\n continue;\n }\n const name = part.slice(0, index).trim();\n if (name && !(name in result)) {\n const value = part.slice(index + 1).trim();\n try {\n result[name] = decodeURIComponent(value);\n } catch {\n result[name] = value;\n }\n }\n }\n return result;\n}\n\n/** Writes a `set-cookie` header value. */\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n if (!/^[\\w!#$%&'*+.^`|~-]+$/.test(name)) {\n throw new Error(`\"${name}\" is not a valid cookie name`);\n }\n const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? '/'}`];\n if (options.maxAge !== undefined) {\n parts.push(`Max-Age=${Math.floor(options.maxAge)}`);\n }\n if (options.expires) {\n parts.push(`Expires=${options.expires.toUTCString()}`);\n }\n if (options.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n if (options.httpOnly !== false) {\n parts.push('HttpOnly');\n }\n if (options.secure) {\n parts.push('Secure');\n }\n parts.push(\n `SameSite=${(options.sameSite ?? 'lax').replace(/^./, (letter) => letter.toUpperCase())}`,\n );\n return parts.join('; ');\n}\n\n/** The parsed `cookie` header of each event, with the header it was parsed from. */\nconst parsed = new WeakMap<\n RequestEvent,\n { header: string | null; cookies: Record<string, string> }\n>();\n\n/** The cookies of the request, with the ones that this request set or deleted. */\nexport function getCookies(event: RequestEvent): Record<string, string> {\n const header = event.request.headers.get('cookie');\n let cached = parsed.get(event);\n if (cached?.header !== header) {\n cached = { header, cookies: parseCookies(header) };\n parsed.set(event, cached);\n }\n // A copy, so the caller cannot change the cache.\n const result = { ...cached.cookies };\n for (const [name, value] of event.cookies ?? []) {\n if (value === undefined) {\n delete result[name];\n } else {\n result[name] = value;\n }\n }\n return result;\n}\n\n/** Sets a cookie on the response of an event. See `RequestEvent.setCookie`. */\nexport function setCookie(\n event: RequestEvent,\n name: string,\n value: string,\n options: CookieOptions = {},\n): void {\n const secure = options.secure ?? new URL(event.request.url).protocol === 'https:';\n event.headers.append('set-cookie', serializeCookie(name, value, { ...options, secure }));\n event.cookies ??= new Map();\n event.cookies.set(name, value);\n}\n\n/** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */\nexport function deleteCookie(\n event: RequestEvent,\n name: string,\n options: Pick<CookieOptions, 'path' | 'domain'> = {},\n): void {\n // `secure` follows the request, as for a cookie set without it.\n setCookie(event, name, '', { ...options, secure: undefined, maxAge: 0, expires: new Date(0) });\n event.cookies!.set(name, undefined);\n}\n\nexport interface SessionOptions {\n /**\n * Signs the cookie, so a browser cannot change it. Use a random string of\n * at least 32 characters, kept out of the code, such as in an environment\n * variable. A list signs with the first and accepts all, for changing it.\n */\n secret: string | string[];\n /** The name of the cookie. Defaults to `session`. */\n name?: string;\n /** Seconds until the session expires. Defaults to 7 days. */\n maxAge?: number;\n /** Other options of the cookie. */\n cookie?: Omit<CookieOptions, 'maxAge' | 'expires'>;\n}\n\nexport interface Session<T> {\n /** The data of the session, or undefined when there is none, it expired, or its signature does not match. */\n get(event: RequestEvent): Promise<T | undefined>;\n /** Replaces the data of the session, and starts its time again. */\n set(event: RequestEvent, data: T): Promise<void>;\n /** Changes some fields of the data, and returns the new data. */\n update(event: RequestEvent, change: Partial<T>): Promise<T>;\n /** Ends the session. */\n clear(event: RequestEvent): void;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst keys = new Map<string, Promise<CryptoKey>>();\n\nfunction key(secret: string): Promise<CryptoKey> {\n let promise = keys.get(secret);\n if (!promise) {\n promise = crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n );\n keys.set(secret, promise);\n }\n return promise;\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let text = '';\n for (const byte of bytes) {\n text += String.fromCharCode(byte);\n }\n return btoa(text).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array<ArrayBuffer> {\n const base64 = text.replace(/-/g, '+').replace(/_/g, '/');\n return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));\n}\n\n/**\n * A session in a signed cookie. The browser can read the data, but cannot\n * change it, so keep secrets out of it: store an ID, and look the rest up\n * on the server.\n *\n * ```ts\n * export const session = createSession<{ userId: string }>({ secret: process.env.SESSION_SECRET! });\n *\n * async function login(form: FormData) {\n * 'use server';\n * const event = getEvent();\n * await session.set(event, { userId: await checkPassword(form) });\n * }\n * ```\n */\nexport function createSession<T>(options: SessionOptions): Session<T> {\n const secrets = Array.isArray(options.secret) ? options.secret : [options.secret];\n 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(decoder.decode(fromBase64Url(payload))) as {\n d: T;\n e: number;\n };\n return expires > Date.now() ? data : undefined;\n } catch {\n return undefined;\n }\n };\n\n 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,CAAC,GAAG,KAAK,GAAG,mBAAmB,KAAK,KAAK,QAAQ,QAAQ,QAAQ,KAAK;CACpF,IAAI,QAAQ,WAAW,KAAA,GACrB,MAAM,KAAK,WAAW,KAAK,MAAM,QAAQ,MAAM,GAAG;CAEpD,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,OAAO,MAAM;GAAE,MAAM,QAAQ,QAAQ;GAAM,QAAQ,QAAQ,QAAQ;EAAO,CAAC;CAC5F;AACF;;;;;;AAOA,SAAgB,cAAc,SAAqD;CACjF,MAAM,SAA4C,OAAO,YAAY,OAAO;CAC5E,MAAM,UAAU,QAAQ,aAAa;CACrC,IAAI,QAAQ,SAAS,GACnB,OAAO,gBAAgB;CAEzB,OAAO;AACT"}
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
//#region src/runtime/devtools.ts
|
|
2
|
-
const DEVTOOLS = Symbol.for("brumate.devtools");
|
|
3
|
-
const MAX_LOG = 300;
|
|
4
|
-
/** The root scope of a scope, whose `m` names its component. */
|
|
5
|
-
function rootOf(scope) {
|
|
6
|
-
let root = scope;
|
|
7
|
-
while (root.p) root = root.p;
|
|
8
|
-
return root;
|
|
9
|
-
}
|
|
10
|
-
/** A short text for a value in the log. */
|
|
11
|
-
function preview(value) {
|
|
12
|
-
if (typeof value === "string") return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);
|
|
13
|
-
if (typeof value === "function") return "function";
|
|
14
|
-
if (Array.isArray(value)) return `Array(${value.length})`;
|
|
15
|
-
if (value instanceof Element) return `<${value.tagName.toLowerCase()}>`;
|
|
16
|
-
if (value !== null && typeof value === "object") {
|
|
17
|
-
const name = value.constructor?.name;
|
|
18
|
-
return name && name !== "Object" ? name : `{${Object.keys(value).slice(0, 3).join(", ")}}`;
|
|
19
|
-
}
|
|
20
|
-
return String(value);
|
|
21
|
-
}
|
|
22
|
-
/** Listens to the core, and adds the button that opens the panel. */
|
|
23
|
-
function installDevtools(endpoint = "/__brumate/inspect", rpc = "/_brumate") {
|
|
24
|
-
const state = {
|
|
25
|
-
log: [],
|
|
26
|
-
written: /* @__PURE__ */ new Set(),
|
|
27
|
-
endpoint
|
|
28
|
-
};
|
|
29
|
-
const add = (entry) => {
|
|
30
|
-
state.log.push({
|
|
31
|
-
...entry,
|
|
32
|
-
time: performance.now()
|
|
33
|
-
});
|
|
34
|
-
if (state.log.length > MAX_LOG) state.log.splice(0, state.log.length - MAX_LOG);
|
|
35
|
-
state.changed?.();
|
|
36
|
-
};
|
|
37
|
-
globalThis[DEVTOOLS] = {
|
|
38
|
-
attach(core) {
|
|
39
|
-
state.scopes = core.scopes;
|
|
40
|
-
state.set = core.set;
|
|
41
|
-
state.changed?.();
|
|
42
|
-
},
|
|
43
|
-
handler(ref, element, event) {
|
|
44
|
-
add({
|
|
45
|
-
kind: "handler",
|
|
46
|
-
text: `${event?.type ?? "call"} on <${element.tagName.toLowerCase()}>: ${ref}`
|
|
47
|
-
});
|
|
48
|
-
},
|
|
49
|
-
part(component, name) {
|
|
50
|
-
add({
|
|
51
|
-
kind: "part",
|
|
52
|
-
text: `loaded ${component} ${name}`
|
|
53
|
-
});
|
|
54
|
-
},
|
|
55
|
-
write(scope, slot, value) {
|
|
56
|
-
state.written.add(scope.id);
|
|
57
|
-
const root = rootOf(scope);
|
|
58
|
-
add({
|
|
59
|
-
kind: "write",
|
|
60
|
-
text: `scope ${scope.id} slot ${slot} = ${preview(value)}`,
|
|
61
|
-
scope: scope.id,
|
|
62
|
-
write: {
|
|
63
|
-
component: root.m ?? "",
|
|
64
|
-
k: scope.k,
|
|
65
|
-
slot
|
|
66
|
-
}
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
const original = globalThis.fetch.bind(globalThis);
|
|
71
|
-
globalThis.fetch = async (input, init) => {
|
|
72
|
-
const url = new URL(input instanceof Request ? input.url : String(input), location.href);
|
|
73
|
-
if (url.origin !== location.origin || !url.pathname.startsWith(`${rpc}/`)) return original(input, init);
|
|
74
|
-
const name = decodeURIComponent(url.pathname.slice(rpc.length + 1));
|
|
75
|
-
const started = performance.now();
|
|
76
|
-
try {
|
|
77
|
-
const response = await original(input, init);
|
|
78
|
-
const took = Math.round(performance.now() - started);
|
|
79
|
-
const redirect = response.headers.get("x-brumate-redirect");
|
|
80
|
-
add({
|
|
81
|
-
kind: "call",
|
|
82
|
-
text: `${name}: ${redirect ? `redirect to ${redirect}` : response.status} in ${took} ms`
|
|
83
|
-
});
|
|
84
|
-
return response;
|
|
85
|
-
} catch (error) {
|
|
86
|
-
add({
|
|
87
|
-
kind: "call",
|
|
88
|
-
text: `${name}: failed, ${error instanceof Error ? error.message : String(error)}`
|
|
89
|
-
});
|
|
90
|
-
throw error;
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
const host = document.createElement("brumate-devtools");
|
|
94
|
-
const root = host.attachShadow({ mode: "open" });
|
|
95
|
-
const button = document.createElement("button");
|
|
96
|
-
button.textContent = "brm";
|
|
97
|
-
button.title = "Open the brumate devtools";
|
|
98
|
-
button.setAttribute("style", "position:fixed;right:12px;bottom:12px;z-index:2147483647;font:600 12px ui-monospace,monospace;padding:6px 10px;border-radius:999px;border:1px solid #8884;background:#111;color:#fff;cursor:pointer");
|
|
99
|
-
button.addEventListener("click", () => {
|
|
100
|
-
import("./devtools-panel-AWOn0VK2.js").then(({ togglePanel }) => togglePanel(root, state));
|
|
101
|
-
});
|
|
102
|
-
root.append(button);
|
|
103
|
-
const append = () => {
|
|
104
|
-
document.documentElement.append(host);
|
|
105
|
-
};
|
|
106
|
-
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", append);
|
|
107
|
-
else append();
|
|
108
|
-
return state;
|
|
109
|
-
}
|
|
110
|
-
//#endregion
|
|
111
|
-
export { preview as n, rootOf as r, installDevtools as t };
|
|
112
|
-
|
|
113
|
-
//# sourceMappingURL=devtools-BKjnHrnv.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"devtools-BKjnHrnv.js","names":[],"sources":["../src/runtime/devtools.ts"],"sourcesContent":["// The devtools overlay of development builds. This module only listens to\n// the core and shows a button. The panel loads when the button is pressed,\n// so the page behaves as in production until then.\n\nimport type { DevtoolsHooks, Scope } from './client.ts';\n\n// The same key as the core's, without importing the core.\nconst DEVTOOLS = Symbol.for('brumate.devtools');\n\n/** Something that happened on the page, for the log of the panel. */\nexport interface DevtoolsEntry {\n time: number;\n kind: 'handler' | 'part' | 'write' | 'call';\n text: string;\n /** The scope of a write, so the panel can mark it. */\n scope?: number;\n /** For a write: the component, the scope in the compiled component, and the slot. */\n write?: { component: string; k: number; slot: number };\n}\n\nexport interface DevtoolsState {\n scopes?: Map<number, Scope>;\n /** Writes a slot, as a handler does, so the page updates. */\n set?: (scope: Scope, slot: number, value: unknown) => void;\n log: DevtoolsEntry[];\n /** The scopes written since the panel last drew, by scope ID. */\n written: Set<number>;\n /** The URL prefix of the inspect endpoint of the dev server. */\n endpoint: string;\n /** Called after each change, while the panel is open. */\n changed?: () => void;\n}\n\nconst MAX_LOG = 300;\n\n/** The root scope of a scope, whose `m` names its component. */\nexport function rootOf(scope: Scope): Scope {\n let root = scope;\n while (root.p) {\n root = root.p;\n }\n return root;\n}\n\n/** A short text for a value in the log. */\nexport function preview(value: unknown): string {\n if (typeof value === 'string') {\n return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);\n }\n if (typeof value === 'function') {\n return 'function';\n }\n if (Array.isArray(value)) {\n return `Array(${value.length})`;\n }\n if (value instanceof Element) {\n return `<${value.tagName.toLowerCase()}>`;\n }\n if (value !== null && typeof value === 'object') {\n const name = value.constructor?.name;\n return name && name !== 'Object' ? name : `{${Object.keys(value).slice(0, 3).join(', ')}}`;\n }\n return String(value);\n}\n\n/** Listens to the core, and adds the button that opens the panel. */\nexport function installDevtools(endpoint = '/__brumate/inspect', rpc = '/_brumate'): DevtoolsState {\n const state: DevtoolsState = { log: [], written: new Set(), endpoint };\n const add = (entry: Omit<DevtoolsEntry, 'time'>): void => {\n state.log.push({ ...entry, time: performance.now() });\n if (state.log.length > MAX_LOG) {\n state.log.splice(0, state.log.length - MAX_LOG);\n }\n state.changed?.();\n };\n const hooks: DevtoolsHooks = {\n attach(core) {\n state.scopes = core.scopes;\n state.set = core.set;\n state.changed?.();\n },\n handler(ref, element, event) {\n add({\n kind: 'handler',\n text: `${event?.type ?? 'call'} on <${element.tagName.toLowerCase()}>: ${ref}`,\n });\n },\n part(component, name) {\n add({ kind: 'part', text: `loaded ${component} ${name}` });\n },\n write(scope, slot, value) {\n state.written.add(scope.id);\n const root = rootOf(scope);\n add({\n kind: 'write',\n text: `scope ${scope.id} slot ${slot} = ${preview(value)}`,\n scope: scope.id,\n write: { component: root.m ?? '', k: scope.k, slot },\n });\n },\n };\n (globalThis as Record<symbol, DevtoolsHooks | undefined>)[DEVTOOLS] = hooks;\n\n // Server function calls, with how long each took and how it answered.\n const original = globalThis.fetch.bind(globalThis);\n globalThis.fetch = async (input, init) => {\n const url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== location.origin || !url.pathname.startsWith(`${rpc}/`)) {\n return original(input, init);\n }\n const name = decodeURIComponent(url.pathname.slice(rpc.length + 1));\n const started = performance.now();\n try {\n const response = await original(input, init);\n const took = Math.round(performance.now() - started);\n const redirect = response.headers.get('x-brumate-redirect');\n add({\n kind: 'call',\n text: `${name}: ${redirect ? `redirect to ${redirect}` : response.status} in ${took} ms`,\n });\n return response;\n } catch (error) {\n add({\n kind: 'call',\n text: `${name}: failed, ${error instanceof Error ? error.message : String(error)}`,\n });\n throw error;\n }\n };\n\n const host = document.createElement('brumate-devtools');\n const root = host.attachShadow({ mode: 'open' });\n const button = document.createElement('button');\n button.textContent = 'brm';\n button.title = 'Open the brumate devtools';\n button.setAttribute(\n 'style',\n 'position:fixed;right:12px;bottom:12px;z-index:2147483647;font:600 12px ui-monospace,monospace;padding:6px 10px;border-radius:999px;border:1px solid #8884;background:#111;color:#fff;cursor:pointer',\n );\n button.addEventListener('click', () => {\n void import('./devtools-panel.ts').then(({ togglePanel }) => togglePanel(root, state));\n });\n root.append(button);\n const append = (): void => {\n // Navigation replaces the body, so the button goes on the document element.\n document.documentElement.append(host);\n };\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', append);\n } else {\n append();\n }\n return state;\n}\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