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,274 @@
|
|
|
1
|
+
import { g as raw } from "./html-mNTKzaDD.js";
|
|
2
|
+
//#region src/runtime/shared.ts
|
|
3
|
+
/** The plugins of values of the app, by tag, which the entry `src/serial.ts` exports. */
|
|
4
|
+
const valuePlugins = /* @__PURE__ */ new Map();
|
|
5
|
+
const pluginListeners = [];
|
|
6
|
+
/** The options of the entry, which the serializer reads when it loads. */
|
|
7
|
+
let entryOptions = {};
|
|
8
|
+
const optionListeners = [];
|
|
9
|
+
/**
|
|
10
|
+
* Takes the exports of the serial entry: its plugins and the options that it
|
|
11
|
+
* changes. The server and the loader call it before the first value is
|
|
12
|
+
* written or read.
|
|
13
|
+
*/
|
|
14
|
+
function useSerialEntry(entry) {
|
|
15
|
+
const { plugins = [], ...options } = entry;
|
|
16
|
+
if (options.disabledFeatures !== void 0 || options.depthLimit !== void 0) {
|
|
17
|
+
entryOptions = options;
|
|
18
|
+
for (const listener of optionListeners) listener(options);
|
|
19
|
+
}
|
|
20
|
+
registerValues(plugins);
|
|
21
|
+
}
|
|
22
|
+
/** Calls `listener` with the options of the entry, now and when they change. */
|
|
23
|
+
function onSerialOptions(listener) {
|
|
24
|
+
optionListeners.push(listener);
|
|
25
|
+
listener(entryOptions);
|
|
26
|
+
}
|
|
27
|
+
/** Adds plugins of values of the app. */
|
|
28
|
+
function registerValues(plugins) {
|
|
29
|
+
for (const plugin of plugins) {
|
|
30
|
+
if (valuePlugins.get(plugin.tag) === plugin) continue;
|
|
31
|
+
valuePlugins.set(plugin.tag, plugin);
|
|
32
|
+
for (const listener of pluginListeners) listener(plugin);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Calls `listener` for each plugin of the app, those added so far and those added later. */
|
|
36
|
+
function onValuePlugin(listener) {
|
|
37
|
+
pluginListeners.push(listener);
|
|
38
|
+
for (const plugin of valuePlugins.values()) listener(plugin);
|
|
39
|
+
}
|
|
40
|
+
/** Reads a scope or boundary ID from markup. */
|
|
41
|
+
function parseId(text) {
|
|
42
|
+
return /^-?\d+$/.test(text) ? Number(text) : text;
|
|
43
|
+
}
|
|
44
|
+
/** An element that the server rendered. The client finds it by its anchor. */
|
|
45
|
+
var ElementReference = class {
|
|
46
|
+
scope;
|
|
47
|
+
anchor;
|
|
48
|
+
constructor(scope, anchor) {
|
|
49
|
+
this.scope = scope;
|
|
50
|
+
this.anchor = anchor;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/** A client function: an export of a client module, and the scope it reads. */
|
|
54
|
+
var FunctionReference = class {
|
|
55
|
+
/** `<component id>#<export name>`. */
|
|
56
|
+
ref;
|
|
57
|
+
scope;
|
|
58
|
+
/** The arguments of a handler that `$handler` made, which come before the event. */
|
|
59
|
+
args;
|
|
60
|
+
/** The modifiers of the wrappers of a handler, such as `prevent`, for the `b-on` of a spread. */
|
|
61
|
+
modifiers;
|
|
62
|
+
constructor(ref, scope, args, modifiers) {
|
|
63
|
+
this.ref = ref;
|
|
64
|
+
this.scope = scope;
|
|
65
|
+
this.args = args ?? void 0;
|
|
66
|
+
this.modifiers = modifiers;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const BINDING = Symbol.for("brumate.binding");
|
|
70
|
+
const SLOT = Symbol.for("brumate.slot");
|
|
71
|
+
/** A slot of a scope, which a write of a bound prop goes to. */
|
|
72
|
+
var SlotReference = class {
|
|
73
|
+
scope;
|
|
74
|
+
slot;
|
|
75
|
+
constructor(scope, slot) {
|
|
76
|
+
this.scope = scope;
|
|
77
|
+
this.slot = slot;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
SlotReference.prototype[SLOT] = true;
|
|
81
|
+
/** True for a slot reference of any copy of the runtime. */
|
|
82
|
+
function isSlotReference(value) {
|
|
83
|
+
return typeof value === "object" && value !== null && SLOT in value;
|
|
84
|
+
}
|
|
85
|
+
/** True for a binding of any copy of the runtime. */
|
|
86
|
+
function isBinding(value) {
|
|
87
|
+
return typeof value === "object" && value !== null && BINDING in value;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* What `$bind(name)` passes a child: the value of the name, and its slot,
|
|
91
|
+
* which the child's writes of the prop go to.
|
|
92
|
+
*/
|
|
93
|
+
var Binding = class {
|
|
94
|
+
value;
|
|
95
|
+
ref;
|
|
96
|
+
/** The function of `$bind(name, fn)`, which a write calls in place of writing the slot. */
|
|
97
|
+
set;
|
|
98
|
+
constructor(value, ref, set) {
|
|
99
|
+
this.value = value;
|
|
100
|
+
this.ref = ref;
|
|
101
|
+
this.set = set;
|
|
102
|
+
}
|
|
103
|
+
/** What a write of the bound prop goes to: the setter, or else the slot. */
|
|
104
|
+
get target() {
|
|
105
|
+
return this.set ?? this.ref;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
Binding.prototype[BINDING] = true;
|
|
109
|
+
/**
|
|
110
|
+
* The props that a component destructures, with the values of their
|
|
111
|
+
* bindings. `names` are the props that it destructures by name: the others,
|
|
112
|
+
* which a rest prop holds, keep their bindings, so a spread passes them on.
|
|
113
|
+
* Without `names`, every binding gives its value.
|
|
114
|
+
*/
|
|
115
|
+
function unbind(props, names) {
|
|
116
|
+
let result;
|
|
117
|
+
for (const key of names ?? Object.keys(props)) {
|
|
118
|
+
const value = props[key];
|
|
119
|
+
if (isBinding(value)) {
|
|
120
|
+
result ??= { ...props };
|
|
121
|
+
result[key] = value.value;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return result ?? props;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Makes the values of brumate's plugins. A state record calls them as `$b`,
|
|
128
|
+
* with one letter each, and the plugins read nodes of server function calls
|
|
129
|
+
* with them too, so both give the same values.
|
|
130
|
+
*/
|
|
131
|
+
const stateValues = {
|
|
132
|
+
e: (scope, anchor) => new ElementReference(scope, anchor),
|
|
133
|
+
f: (ref, scope, args, modifiers) => new FunctionReference(ref, scope, args, modifiers),
|
|
134
|
+
r: raw,
|
|
135
|
+
c: (id) => Object.assign(() => "", { brumateId: id }),
|
|
136
|
+
l: (scope, slot) => new SlotReference(scope, slot),
|
|
137
|
+
b: (value, scope, slot, set) => new Binding(value, new SlotReference(scope, slot), set),
|
|
138
|
+
u: (tag, data) => {
|
|
139
|
+
const plugin = valuePlugins.get(tag);
|
|
140
|
+
if (!plugin) throw new Error(`No plugin reads the value "${tag}". Export it in the plugins of the serial entry, src/serial.ts`);
|
|
141
|
+
return plugin.fromData(data);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
/** True for a value that `for await` reads, such as the result of an async generator. */
|
|
145
|
+
function isAsyncIterable(value) {
|
|
146
|
+
return value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region src/runtime/produce.ts
|
|
150
|
+
const DRAFT = Symbol("brumate.draft");
|
|
151
|
+
/** Plain objects and arrays can be drafted. Other values, such as `Map`, are used as they are. */
|
|
152
|
+
function isDraftable(value) {
|
|
153
|
+
if (typeof value !== "object" || value === null) return false;
|
|
154
|
+
if (Array.isArray(value)) return true;
|
|
155
|
+
const prototype = Object.getPrototypeOf(value);
|
|
156
|
+
return prototype === Object.prototype || prototype === null;
|
|
157
|
+
}
|
|
158
|
+
function latest(state) {
|
|
159
|
+
return state.copy ?? state.base;
|
|
160
|
+
}
|
|
161
|
+
/** Copies an object and its parents on the first change. */
|
|
162
|
+
function prepare(state) {
|
|
163
|
+
for (let current = state; current && !current.modified; current = current.parent) {
|
|
164
|
+
current.modified = true;
|
|
165
|
+
current.copy = Array.isArray(current.base) ? [...current.base] : { ...current.base };
|
|
166
|
+
}
|
|
167
|
+
return state.copy;
|
|
168
|
+
}
|
|
169
|
+
function stateOf(value) {
|
|
170
|
+
return typeof value === "object" && value !== null ? value[DRAFT] : void 0;
|
|
171
|
+
}
|
|
172
|
+
function createDraft(base, parent) {
|
|
173
|
+
const state = {
|
|
174
|
+
base,
|
|
175
|
+
copy: void 0,
|
|
176
|
+
parent,
|
|
177
|
+
children: /* @__PURE__ */ new Map(),
|
|
178
|
+
modified: false
|
|
179
|
+
};
|
|
180
|
+
const target = Array.isArray(base) ? [] : Object.create(Object.getPrototypeOf(base));
|
|
181
|
+
state.proxy = new Proxy(target, {
|
|
182
|
+
get(_, key) {
|
|
183
|
+
if (key === DRAFT) return state;
|
|
184
|
+
const source = latest(state);
|
|
185
|
+
const value = source[key];
|
|
186
|
+
if (!Object.hasOwn(source, key) || !isDraftable(value) || value !== state.base[key]) return value;
|
|
187
|
+
let child = state.children.get(key);
|
|
188
|
+
if (!child) {
|
|
189
|
+
child = createDraft(value, state);
|
|
190
|
+
state.children.set(key, child);
|
|
191
|
+
}
|
|
192
|
+
return child.proxy;
|
|
193
|
+
},
|
|
194
|
+
set(_, key, value) {
|
|
195
|
+
const source = latest(state);
|
|
196
|
+
if (Object.is(source[key], value) && Object.hasOwn(source, key)) return true;
|
|
197
|
+
prepare(state)[key] = value;
|
|
198
|
+
state.children.delete(key);
|
|
199
|
+
return true;
|
|
200
|
+
},
|
|
201
|
+
deleteProperty(_, key) {
|
|
202
|
+
if (Object.hasOwn(latest(state), key)) {
|
|
203
|
+
delete prepare(state)[key];
|
|
204
|
+
state.children.delete(key);
|
|
205
|
+
}
|
|
206
|
+
return true;
|
|
207
|
+
},
|
|
208
|
+
has(_, key) {
|
|
209
|
+
return key in latest(state);
|
|
210
|
+
},
|
|
211
|
+
ownKeys() {
|
|
212
|
+
return Reflect.ownKeys(latest(state));
|
|
213
|
+
},
|
|
214
|
+
getOwnPropertyDescriptor(_, key) {
|
|
215
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(latest(state), key);
|
|
216
|
+
if (descriptor && key !== "length") {
|
|
217
|
+
descriptor.configurable = true;
|
|
218
|
+
descriptor.writable = true;
|
|
219
|
+
}
|
|
220
|
+
return descriptor;
|
|
221
|
+
},
|
|
222
|
+
defineProperty(_, key, descriptor) {
|
|
223
|
+
prepare(state);
|
|
224
|
+
return Reflect.defineProperty(state.copy, key, descriptor);
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
return state;
|
|
228
|
+
}
|
|
229
|
+
/** Returns the final value of a draft: the base if nothing changed, or a new object that shares what did not. */
|
|
230
|
+
function finalize(state) {
|
|
231
|
+
if (!state.modified) {
|
|
232
|
+
for (const child of state.children.values()) if (child.modified) {
|
|
233
|
+
prepare(state);
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
if (!state.modified) return state.base;
|
|
237
|
+
}
|
|
238
|
+
const copy = state.copy;
|
|
239
|
+
for (const [key, child] of state.children) if (copy[key] === child.base) copy[key] = finalize(child);
|
|
240
|
+
for (const key of Reflect.ownKeys(copy)) {
|
|
241
|
+
const draft = stateOf(copy[key]);
|
|
242
|
+
if (draft) copy[key] = finalize(draft);
|
|
243
|
+
}
|
|
244
|
+
return copy;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Returns a changed copy of a value. The recipe changes a draft as if it
|
|
248
|
+
* were the value. Objects that it does not change keep their identity, and
|
|
249
|
+
* if it changes nothing, the value itself is returned. A recipe can also
|
|
250
|
+
* return a new value. Only plain objects and arrays are drafted.
|
|
251
|
+
*/
|
|
252
|
+
function produce(base, recipe) {
|
|
253
|
+
if (!isDraftable(base)) {
|
|
254
|
+
const result = recipe(base);
|
|
255
|
+
return result === void 0 ? base : result;
|
|
256
|
+
}
|
|
257
|
+
const state = createDraft(base, void 0);
|
|
258
|
+
const result = recipe(state.proxy);
|
|
259
|
+
if (result !== void 0 && result !== state.proxy) return resolve(result, /* @__PURE__ */ new Set());
|
|
260
|
+
return finalize(state);
|
|
261
|
+
}
|
|
262
|
+
/** Replaces the drafts in a value that a recipe returns, such as the result of `draft.filter(…)`. */
|
|
263
|
+
function resolve(value, seen) {
|
|
264
|
+
const draft = stateOf(value);
|
|
265
|
+
if (draft) return finalize(draft);
|
|
266
|
+
if (!isDraftable(value) || seen.has(value)) return value;
|
|
267
|
+
seen.add(value);
|
|
268
|
+
for (const key of Reflect.ownKeys(value)) value[key] = resolve(value[key], seen);
|
|
269
|
+
return value;
|
|
270
|
+
}
|
|
271
|
+
//#endregion
|
|
272
|
+
export { SlotReference as a, isSlotReference as c, parseId as d, stateValues as f, FunctionReference as i, onSerialOptions as l, useSerialEntry as m, Binding as n, isAsyncIterable as o, unbind as p, ElementReference as r, isBinding as s, produce as t, onValuePlugin as u };
|
|
273
|
+
|
|
274
|
+
//# sourceMappingURL=produce-Doc91GkX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"produce-Doc91GkX.js","names":[],"sources":["../src/runtime/shared.ts","../src/runtime/produce.ts"],"sourcesContent":["// Values and types that the server and the browser share. It does not import\n// seroval, so the core, which reads the page state without it, stays small.\n// The plugins that write and read these values are in `serial.ts`.\n\nimport { raw } from './html.ts';\nimport type { Raw } from './html.ts';\nimport type { SerialEntry, ValuePlugin } from './values.ts';\n\n/** The plugins of values of the app, by tag, which the entry `src/serial.ts` exports. */\nconst valuePlugins = new Map<string, ValuePlugin>();\nconst pluginListeners: ((plugin: ValuePlugin) => void)[] = [];\n/** The options of the entry, which the serializer reads when it loads. */\nlet entryOptions: Omit<SerialEntry, 'plugins'> = {};\nconst optionListeners: ((options: Omit<SerialEntry, 'plugins'>) => void)[] = [];\n\n/**\n * Takes the exports of the serial entry: its plugins and the options that it\n * changes. The server and the loader call it before the first value is\n * written or read.\n */\nexport function useSerialEntry(entry: SerialEntry): void {\n const { plugins = [], ...options } = entry;\n if (options.disabledFeatures !== undefined || options.depthLimit !== undefined) {\n entryOptions = options;\n for (const listener of optionListeners) {\n listener(options);\n }\n }\n registerValues(plugins);\n}\n\n/** Calls `listener` with the options of the entry, now and when they change. */\nexport function onSerialOptions(listener: (options: Omit<SerialEntry, 'plugins'>) => void): void {\n optionListeners.push(listener);\n listener(entryOptions);\n}\n\n/** Adds plugins of values of the app. */\nfunction registerValues(plugins: readonly ValuePlugin[]): void {\n for (const plugin of plugins) {\n if (valuePlugins.get(plugin.tag) === plugin) {\n continue;\n }\n valuePlugins.set(plugin.tag, plugin);\n for (const listener of pluginListeners) {\n listener(plugin);\n }\n }\n}\n\n/** Calls `listener` for each plugin of the app, those added so far and those added later. */\nexport function onValuePlugin(listener: (plugin: ValuePlugin) => void): void {\n pluginListeners.push(listener);\n for (const plugin of valuePlugins.values()) {\n listener(plugin);\n }\n}\n\n/**\n * The ID of a scope or of a `#loading` boundary. The rest of the page numbers\n * its scopes from the base of the render, such as `3`. A `#loading` body\n * numbers its own from 0 after the ID of its boundary and a dot, such as\n * `5.0` and `5.1`, so its IDs do not depend on when its data arrives.\n */\nexport type ScopeId = number | string;\n\n/** Reads a scope or boundary ID from markup. */\nexport function parseId(text: string): ScopeId {\n return /^-?\\d+$/.test(text) ? Number(text) : text;\n}\n\n/** Adds a number to an ID. An ID inside a boundary moves with its boundary. */\nexport function shiftId(id: ScopeId, by: number): ScopeId {\n if (typeof id === 'number') {\n return id + by;\n }\n const dot = id.indexOf('.');\n return `${Number(id.slice(0, dot)) + by}${id.slice(dot)}`;\n}\n\n/** An element that the server rendered. The client finds it by its anchor. */\nexport class ElementReference {\n readonly scope: ScopeId;\n readonly anchor: number;\n\n constructor(scope: ScopeId, anchor: number) {\n this.scope = scope;\n this.anchor = anchor;\n }\n}\n\n/** A client function: an export of a client module, and the scope it reads. */\nexport class FunctionReference {\n /** `<component id>#<export name>`. */\n readonly ref: string;\n readonly scope: ScopeId;\n /** The arguments of a handler that `$handler` made, which come before the event. */\n readonly args: unknown[] | undefined;\n /** The modifiers of the wrappers of a handler, such as `prevent`, for the `b-on` of a spread. */\n readonly modifiers: string[] | undefined;\n\n constructor(ref: string, scope: ScopeId, args?: unknown[] | null, modifiers?: string[]) {\n this.ref = ref;\n this.scope = scope;\n this.args = args ?? undefined;\n this.modifiers = modifiers;\n }\n}\n\n// Brands of bindings and slot references, under keys of the registry, so two copies of the\n// runtime, such as a component's and the render context's, know each other's.\nconst BINDING = Symbol.for('brumate.binding');\nconst SLOT = Symbol.for('brumate.slot');\n\n/** A slot of a scope, which a write of a bound prop goes to. */\nexport class SlotReference {\n readonly scope: ScopeId;\n readonly slot: number;\n\n constructor(scope: ScopeId, slot: number) {\n this.scope = scope;\n this.slot = slot;\n }\n}\n\n(SlotReference.prototype as unknown as Record<symbol, boolean>)[SLOT] = true;\n\n/** True for a slot reference of any copy of the runtime. */\nexport function isSlotReference(value: unknown): value is SlotReference {\n return typeof value === 'object' && value !== null && SLOT in value;\n}\n\n/** True for a binding of any copy of the runtime. */\nexport function isBinding(value: unknown): value is Binding {\n return typeof value === 'object' && value !== null && BINDING in value;\n}\n\n/**\n * What `$bind(name)` passes a child: the value of the name, and its slot,\n * which the child's writes of the prop go to.\n */\nexport class Binding<T = unknown> {\n readonly value: T;\n readonly ref: SlotReference;\n /** The function of `$bind(name, fn)`, which a write calls in place of writing the slot. */\n readonly set: unknown;\n\n constructor(value: T, ref: SlotReference, set?: unknown) {\n this.value = value;\n this.ref = ref;\n this.set = set;\n }\n\n /** What a write of the bound prop goes to: the setter, or else the slot. */\n get target(): unknown {\n return this.set ?? this.ref;\n }\n}\n\n(Binding.prototype as unknown as Record<symbol, boolean>)[BINDING] = true;\n\n/**\n * The props that a component destructures, with the values of their\n * bindings. `names` are the props that it destructures by name: the others,\n * which a rest prop holds, keep their bindings, so a spread passes them on.\n * Without `names`, every binding gives its value.\n */\nexport function unbind(\n props: Record<string, unknown>,\n names?: readonly string[],\n): Record<string, unknown> {\n let result: Record<string, unknown> | undefined;\n for (const key of names ?? Object.keys(props)) {\n const value = props[key];\n if (isBinding(value)) {\n result ??= { ...props };\n result[key] = value.value;\n }\n }\n return result ?? props;\n}\n\n/** A component, which the compiler marks with its ID. */\nexport type ComponentValue = ((...args: never[]) => unknown) & { brumateId: string };\n\n/**\n * Makes the values of brumate's plugins. A state record calls them as `$b`,\n * with one letter each, and the plugins read nodes of server function calls\n * with them too, so both give the same values.\n */\nexport const stateValues: {\n /** An element that the server rendered, by its scope and anchor. */\n e: (scope: ScopeId, anchor: number) => ElementReference;\n /** A client function, by its reference and scope. */\n f: (\n ref: string,\n scope: ScopeId,\n args?: unknown[] | null,\n modifiers?: string[],\n ) => FunctionReference;\n /** HTML that the client may insert again. */\n r: (html: string) => Raw;\n /**\n * A component, such as the value of a dynamic tag. The client gets a\n * function with the same ID that renders nothing. The client code that\n * changes the value uses the component's render module instead.\n */\n c: (id: string) => ComponentValue;\n /** A slot of a scope, which a bound prop writes. */\n l: (scope: ScopeId, slot: number) => SlotReference;\n /** A binding that a rest prop holds, with its value and its slot. */\n b: (value: unknown, scope: ScopeId, slot: number, set?: unknown) => Binding;\n /** A value of the app, which a plugin of the entry makes from its data. */\n u: (tag: string, data: unknown) => unknown;\n} = {\n e: (scope, anchor) => new ElementReference(scope, anchor),\n f: (ref, scope, args, modifiers) => new FunctionReference(ref, scope, args, modifiers),\n r: raw,\n c: (id) => Object.assign(() => '', { brumateId: id }),\n l: (scope, slot) => new SlotReference(scope, slot),\n b: (value, scope, slot, set) => new Binding(value, new SlotReference(scope, slot), set),\n u: (tag, data) => {\n const plugin = valuePlugins.get(tag);\n if (!plugin) {\n throw new Error(\n `No plugin reads the value \"${tag}\". Export it in the plugins of the serial entry, src/serial.ts`,\n );\n }\n return plugin.fromData(data);\n },\n};\n\n/** True for a value that `for await` reads, such as the result of an async generator. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'\n );\n}\n\n/** The state of one scope in the page. */\nexport interface ScopeState {\n /** The scope's ID in the compiled component. */\n k?: number;\n /** The ID of the scope that contains this one. Component root scopes have none. */\n p?: ScopeId;\n /** The component ID of a component's root scope. */\n m?: string;\n /** The item of a list item scope. */\n i?: unknown;\n /** The scope that rendered a component's root scope, for finding contexts. */\n o?: ScopeId;\n /**\n * For a scope of children that a component inserted, the scope where they\n * are, which contexts are found from in place of `p` and `o`.\n */\n t?: ScopeId;\n /** The values that the scope provides, by context key. */\n v?: Record<string, unknown>;\n /** The slots that hold the contexts that the scope reads, by context key. */\n x?: Record<string, number>;\n /** Slot values, in the order of the scope's layout. */\n s?: unknown[];\n /** The scope IDs of child components, by anchor index. */\n c?: Record<number, ScopeId>;\n /**\n * What the bound props of a component write, by the slot of the prop: a\n * slot of a parent, or the function of `$bind(name, fn)`.\n */\n b?: Record<number, unknown>;\n}\n\n/** The state of a page, by scope ID. */\nexport type PageState = Record<ScopeId, ScopeState>;\n\n/**\n * The flags of a group of scope records in `PackedState`:\n * - `ITEM_SLOT`: the item of each scope is its first slot.\n * - `ITEM`: each scope has its item after its slots.\n * - `CHILDREN`: each scope has its child components after that.\n * - `OWNER`: the scopes are component root scopes. `base` is the distance from the scope that\n * rendered each one, `o`, to the scope, and the first gap is from 0. Otherwise `base` is the\n * parent, `p`, of every scope.\n * - `MODULE`: the group has the component ID of its scopes after its header.\n * - `SOURCE`: the scopes are the items of a list whose list is a slot of an enclosing scope.\n * The header then has that scope's ID and the slot's index, and the items are not written:\n * the item of the scope at position `n` in the group is the value at `n` of the list, or of\n * `Array.from` of a Set. With `ITEM_SLOT`, each scope writes its slots after the first.\n * - `PREFIX`: the scopes are inside a `#loading` body. The header ends with the prefix of\n * their IDs, such as `5.`, and the gaps count the numbers after it.\n */\nexport const ITEM_SLOT = 1;\nexport const ITEM = 2;\nexport const CHILDREN = 4;\nexport const OWNER = 8;\nexport const MODULE = 16;\nexport const SOURCE = 32;\nexport const PREFIX = 64;\n\n/**\n * The page state as the server writes it. Records of scopes that share their\n * kind, their parent or owner, and their shape are in one group of `g`,\n * such as the items of a list, instead of one object each. A group is a flat\n * array: `[kind, base, flags, slotCount, module?, source?, sourceSlot?, prefix?, ...scopes]`, and each scope\n * is its ID as the gap from the one before it (the first from `base`), its\n * slots, and then its item and its child components, as `flags` says.\n */\nexport type PackedState = PageState & { g?: unknown[][] };\n","const DRAFT = Symbol('brumate.draft');\n\ninterface DraftState {\n base: Record<PropertyKey, unknown>;\n /** A shallow copy, made on the first change. */\n copy: Record<PropertyKey, unknown> | undefined;\n parent: DraftState | undefined;\n /** Drafts of the objects inside, by key. */\n children: Map<PropertyKey, DraftState & { proxy: object }>;\n modified: boolean;\n}\n\n/** Plain objects and arrays can be drafted. Other values, such as `Map`, are used as they are. */\nfunction isDraftable(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction latest(state: DraftState): Record<PropertyKey, unknown> {\n return state.copy ?? state.base;\n}\n\n/** Copies an object and its parents on the first change. */\nfunction prepare(state: DraftState): Record<PropertyKey, unknown> {\n for (\n let current: DraftState | undefined = state;\n current && !current.modified;\n current = current.parent\n ) {\n current.modified = true;\n current.copy = (\n Array.isArray(current.base) ? [...current.base] : { ...current.base }\n ) as Record<PropertyKey, unknown>;\n }\n return state.copy!;\n}\n\nfunction stateOf(value: unknown): DraftState | undefined {\n return typeof value === 'object' && value !== null\n ? ((value as Record<PropertyKey, unknown>)[DRAFT] as DraftState | undefined)\n : undefined;\n}\n\nfunction createDraft(\n base: Record<PropertyKey, unknown>,\n parent: DraftState | undefined,\n): DraftState & { proxy: object } {\n const state = {\n base,\n copy: undefined,\n parent,\n children: new Map(),\n modified: false,\n } as DraftState & {\n proxy: object;\n };\n // An empty target, so the draft can report the keys of the copy.\n const target = Array.isArray(base) ? [] : Object.create(Object.getPrototypeOf(base));\n state.proxy = new Proxy(target, {\n get(_, key) {\n if (key === DRAFT) {\n return state;\n }\n const source = latest(state);\n const value = source[key];\n if (!Object.hasOwn(source, key) || !isDraftable(value) || value !== state.base[key]) {\n return value;\n }\n let child = state.children.get(key);\n if (!child) {\n child = createDraft(value, state);\n state.children.set(key, child);\n }\n return child.proxy;\n },\n set(_, key, value) {\n const source = latest(state);\n if (Object.is(source[key], value) && Object.hasOwn(source, key)) {\n return true;\n }\n prepare(state)[key] = value;\n state.children.delete(key);\n return true;\n },\n deleteProperty(_, key) {\n if (Object.hasOwn(latest(state), key)) {\n delete prepare(state)[key];\n state.children.delete(key);\n }\n return true;\n },\n has(_, key) {\n return key in latest(state);\n },\n ownKeys() {\n return Reflect.ownKeys(latest(state));\n },\n getOwnPropertyDescriptor(_, key) {\n const descriptor = Reflect.getOwnPropertyDescriptor(latest(state), key);\n if (descriptor && key !== 'length') {\n descriptor.configurable = true;\n descriptor.writable = true;\n }\n return descriptor;\n },\n defineProperty(_, key, descriptor) {\n prepare(state);\n return Reflect.defineProperty(state.copy!, key, descriptor);\n },\n });\n return state;\n}\n\n/** Returns the final value of a draft: the base if nothing changed, or a new object that shares what did not. */\nfunction finalize(state: DraftState): unknown {\n if (!state.modified) {\n // A child can change without its parent being copied yet.\n for (const child of state.children.values()) {\n if (child.modified) {\n prepare(state);\n break;\n }\n }\n if (!state.modified) {\n return state.base;\n }\n }\n const copy = state.copy!;\n for (const [key, child] of state.children) {\n if (copy[key] === child.base) {\n copy[key] = finalize(child);\n }\n }\n // Drafts can also be assigned to other keys, such as when an array is reordered.\n for (const key of Reflect.ownKeys(copy)) {\n const draft = stateOf(copy[key]);\n if (draft) {\n copy[key] = finalize(draft);\n }\n }\n return copy;\n}\n\n/**\n * Returns a changed copy of a value. The recipe changes a draft as if it\n * were the value. Objects that it does not change keep their identity, and\n * if it changes nothing, the value itself is returned. A recipe can also\n * return a new value. Only plain objects and arrays are drafted.\n */\nexport function produce<T>(base: T, recipe: (draft: T) => T | void): T {\n if (!isDraftable(base)) {\n const result = recipe(base);\n return result === undefined ? base : result;\n }\n const state = createDraft(base, undefined);\n const result = recipe(state.proxy as T);\n if (result !== undefined && result !== state.proxy) {\n return resolve(result, new Set()) as T;\n }\n return finalize(state) as T;\n}\n\n/** Replaces the drafts in a value that a recipe returns, such as the result of `draft.filter(…)`. */\nfunction resolve(value: unknown, seen: Set<unknown>): unknown {\n const draft = stateOf(value);\n if (draft) {\n return finalize(draft);\n }\n if (!isDraftable(value) || seen.has(value)) {\n return value;\n }\n seen.add(value);\n for (const key of Reflect.ownKeys(value)) {\n value[key] = resolve(value[key], seen);\n }\n return value;\n}\n"],"mappings":";;;AASA,MAAM,+BAAe,IAAI,IAAyB;AAClD,MAAM,kBAAqD,CAAC;;AAE5D,IAAI,eAA6C,CAAC;AAClD,MAAM,kBAAuE,CAAC;;;;;;AAO9E,SAAgB,eAAe,OAA0B;CACvD,MAAM,EAAE,UAAU,CAAC,GAAG,GAAG,YAAY;CACrC,IAAI,QAAQ,qBAAqB,KAAA,KAAa,QAAQ,eAAe,KAAA,GAAW;EAC9E,eAAe;EACf,KAAK,MAAM,YAAY,iBACrB,SAAS,OAAO;CAEpB;CACA,eAAe,OAAO;AACxB;;AAGA,SAAgB,gBAAgB,UAAiE;CAC/F,gBAAgB,KAAK,QAAQ;CAC7B,SAAS,YAAY;AACvB;;AAGA,SAAS,eAAe,SAAuC;CAC7D,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,aAAa,IAAI,OAAO,GAAG,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,KAAa,WAAW,MAAM,OAC3C,OAAO,QAAQ,wBAAQ,IAAI,IAAI,CAAC;CAElC,OAAO,SAAS,KAAK;AACvB;;AAGA,SAAS,QAAQ,OAAgB,MAA6B;CAC5D,MAAM,QAAQ,QAAQ,KAAK;CAC3B,IAAI,OACF,OAAO,SAAS,KAAK;CAEvB,IAAI,CAAC,YAAY,KAAK,KAAK,KAAK,IAAI,KAAK,GACvC,OAAO;CAET,KAAK,IAAI,KAAK;CACd,KAAK,MAAM,OAAO,QAAQ,QAAQ,KAAK,GACrC,MAAM,OAAO,QAAQ,MAAM,MAAM,IAAI;CAEvC,OAAO;AACT"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/runtime/routes.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The paths of the routes, with their params, such as
|
|
4
|
+
* `'/todos/[id]': { id: string }`. The Vite plugin adds them.
|
|
5
|
+
*/
|
|
6
|
+
interface Routes {}
|
|
7
|
+
/** A route path, such as `/todos/[id]`. Any string while no routes are declared. */
|
|
8
|
+
type RoutePath = [keyof Routes] extends [never] ? string : keyof Routes & string;
|
|
9
|
+
/** The params of a route path, such as `{ id: string }` for `/todos/[id]`. */
|
|
10
|
+
type RouteParams<P extends RoutePath> = P extends keyof Routes ? Routes[P] : Record<string, string>;
|
|
11
|
+
/** The arguments after the path: none for a path without params. */
|
|
12
|
+
type ParamsArgument<P extends RoutePath> = [keyof RouteParams<P>] extends [never] ? [params?: RouteParams<P>] : [params: RouteParams<P>];
|
|
13
|
+
/**
|
|
14
|
+
* The URL of a route, with its params in place:
|
|
15
|
+
* `href('/todos/[id]', { id: '3' })` is `/todos/3`. A rest param, such as
|
|
16
|
+
* `[...path]`, keeps its slashes.
|
|
17
|
+
*/
|
|
18
|
+
declare function href<P extends RoutePath>(path: P, ...[params]: ParamsArgument<P>): string;
|
|
19
|
+
interface NavigateOptions {
|
|
20
|
+
/** Replaces the current entry of the history instead of adding one. */
|
|
21
|
+
replace?: boolean;
|
|
22
|
+
/** Scrolls to the top of the new page, or to its hash. Defaults to true. False keeps the place. */
|
|
23
|
+
scroll?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Loads a page as a link does: the layouts that stay keep their state. It
|
|
27
|
+
* returns when the page shows. A URL of another origin, or a page without
|
|
28
|
+
* the loader, loads in full.
|
|
29
|
+
*
|
|
30
|
+
* ```ts
|
|
31
|
+
* await navigate(href('/issues/[id]', { id: issue.id }));
|
|
32
|
+
* navigate(`?q=${query}`, { replace: true });
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
declare function navigate(to: string, options?: NavigateOptions): Promise<void>;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { href as a, Routes as i, RouteParams as n, navigate as o, RoutePath as r, NavigateOptions as t };
|
|
38
|
+
//# sourceMappingURL=routes-BZNt7DSZ.d.ts.map
|
|
@@ -1,28 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as callPlugins, n as fromChunkStream, o as serialOptions } from "./stream-DCYZO4IF.js";
|
|
2
|
+
import { dt as skew, p as build } from "./client-BD6XT-s5.js";
|
|
2
3
|
import { toJSONAsync } from "seroval";
|
|
3
4
|
//#region src/runtime/rpc.ts
|
|
4
5
|
/**
|
|
5
|
-
* True for a file or a blob. One from another frame, or another DOM, is an
|
|
6
|
-
* instance of another `Blob` class, so its methods tell instead.
|
|
7
|
-
*/
|
|
8
|
-
function isBlob(value) {
|
|
9
|
-
if (value instanceof Blob) return true;
|
|
10
|
-
const blob = value;
|
|
11
|
-
return typeof blob === "object" && blob !== null && typeof blob.size === "number" && typeof blob.type === "string" && typeof blob.arrayBuffer === "function" && typeof blob.slice === "function";
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
6
|
* Calls a server function. It is a separate module, so pages that never call
|
|
15
7
|
* one never load seroval's serializer.
|
|
16
8
|
*
|
|
17
|
-
* Files and blobs in the arguments, in
|
|
18
|
-
*
|
|
9
|
+
* Files and blobs in the arguments, anywhere in them, go as parts of
|
|
10
|
+
* multipart form data. `signal` aborts the call.
|
|
19
11
|
*/
|
|
20
12
|
async function call(prefix, id, args, signal) {
|
|
21
13
|
const files = [];
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
disabledFeatures
|
|
14
|
+
const json = JSON.stringify(await toJSONAsync(args, {
|
|
15
|
+
plugins: callPlugins(files),
|
|
16
|
+
...serialOptions()
|
|
26
17
|
}));
|
|
27
18
|
let init;
|
|
28
19
|
if (files.length > 0) {
|
|
@@ -47,16 +38,20 @@ async function call(prefix, id, args, signal) {
|
|
|
47
38
|
* Sends a form to a server function, and returns its result. The form data
|
|
48
39
|
* goes as it is, files included, as when the browser posts the form.
|
|
49
40
|
*/
|
|
50
|
-
async function submit(prefix, id, form) {
|
|
41
|
+
async function submit(prefix, id, form, key) {
|
|
51
42
|
return post(prefix, id, {
|
|
52
43
|
headers: { "x-brumate-result": "1" },
|
|
53
44
|
body: form
|
|
54
|
-
});
|
|
45
|
+
}, key);
|
|
55
46
|
}
|
|
56
47
|
/** Posts to a server function, and reads its answer. */
|
|
57
|
-
async function post(prefix, id, init) {
|
|
58
|
-
|
|
48
|
+
async function post(prefix, id, init, key) {
|
|
49
|
+
const headers = new Headers(init.headers);
|
|
50
|
+
if (build !== void 0) headers.set("x-brumate-build", build);
|
|
51
|
+
const query = key ? `?__key=${encodeURIComponent(key)}` : "";
|
|
52
|
+
return answer(id, await fetch(`${prefix}/${encodeURIComponent(id)}${query}`, {
|
|
59
53
|
...init,
|
|
54
|
+
headers,
|
|
60
55
|
method: "POST"
|
|
61
56
|
}));
|
|
62
57
|
}
|
|
@@ -78,13 +73,16 @@ async function answer(id, response) {
|
|
|
78
73
|
return new Promise(() => {});
|
|
79
74
|
}
|
|
80
75
|
if (!response.ok) {
|
|
76
|
+
if (response.status === 409 && response.headers.get("x-brumate-build")) skew("call");
|
|
81
77
|
let message = `Server function "${id}" failed with status ${response.status}`;
|
|
82
78
|
try {
|
|
83
79
|
message = (await response.json()).error;
|
|
84
80
|
} catch {}
|
|
81
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
85
82
|
throw Object.assign(new Error(message), {
|
|
86
83
|
name: "ServerError",
|
|
87
|
-
status: response.status
|
|
84
|
+
status: response.status,
|
|
85
|
+
...retryAfter > 0 ? { retryAfter } : {}
|
|
88
86
|
});
|
|
89
87
|
}
|
|
90
88
|
return fromChunkStream(response.body);
|
|
@@ -108,6 +106,11 @@ function refreshMemos(ids) {
|
|
|
108
106
|
}
|
|
109
107
|
});
|
|
110
108
|
}
|
|
109
|
+
/** Gives a form a new key in its URL, for its next post. */
|
|
110
|
+
function renewKey(form, url) {
|
|
111
|
+
url.searchParams.set("__key", crypto.randomUUID());
|
|
112
|
+
form.setAttribute("action", `${url.pathname}${url.search}`);
|
|
113
|
+
}
|
|
111
114
|
/**
|
|
112
115
|
* Sends a form to the server function of its `$action`, and writes the
|
|
113
116
|
* result into the `$action` when it arrives. It is pending until then. See
|
|
@@ -119,10 +122,23 @@ function sendAction(form, submitter) {
|
|
|
119
122
|
const action = form.getAttribute("b-action");
|
|
120
123
|
return import("./runtime/client.js").then(({ asyncMemo, rpcPrefix, scopes, track }) => {
|
|
121
124
|
const scope = scopes.get(scopeId);
|
|
122
|
-
if (scope)
|
|
125
|
+
if (scope) {
|
|
126
|
+
const url = new URL(form.getAttribute("action") ?? "", location.href);
|
|
127
|
+
const key = url.searchParams.get("__key");
|
|
128
|
+
const result = submit(rpcPrefix, action, data, key);
|
|
129
|
+
if (key) result.then(() => renewKey(form, url), () => {});
|
|
130
|
+
const answered = result.catch((error) => {
|
|
131
|
+
if (error.status === 409 && build !== void 0) {
|
|
132
|
+
form.submit();
|
|
133
|
+
return new Promise(() => {});
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
136
|
+
});
|
|
137
|
+
asyncMemo(scope, slot, track(answered));
|
|
138
|
+
}
|
|
123
139
|
});
|
|
124
140
|
}
|
|
125
141
|
//#endregion
|
|
126
142
|
export { call, sendAction };
|
|
127
143
|
|
|
128
|
-
//# sourceMappingURL=rpc-
|
|
144
|
+
//# sourceMappingURL=rpc-ygMRPmN4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpc-ygMRPmN4.js","names":[],"sources":["../src/runtime/rpc.ts"],"sourcesContent":["import { toJSONAsync } from 'seroval';\nimport { build, skew } from './client.ts';\nimport type { Scope } from './client.ts';\nimport { callPlugins, serialOptions } from './serial.ts';\nimport { fromChunkStream } from './stream.ts';\n\n/**\n * Calls a server function. It is a separate module, so pages that never call\n * one never load seroval's serializer.\n *\n * Files and blobs in the arguments, anywhere in them, go as parts of\n * multipart form data. `signal` aborts the call.\n */\nexport async function call(\n prefix: string,\n id: string,\n args: unknown[],\n signal?: AbortSignal,\n): Promise<unknown> {\n // The plugin of uploads takes each file and blob in the arguments, wherever it is.\n const files: Blob[] = [];\n const json = JSON.stringify(\n await toJSONAsync(args, { plugins: callPlugins(files), ...serialOptions() }),\n );\n let init: RequestInit;\n if (files.length > 0) {\n const form = new FormData();\n form.set('args', json);\n // A blob of another DOM is copied, because form data takes only its own.\n const blobs = await Promise.all(\n files.map((file: Blob) =>\n // Typed as a Blob, so the check narrows a blob of another DOM to never.\n file instanceof Blob\n ? file\n : (file as Blob)\n .arrayBuffer()\n .then((data) => new Blob([data], { type: (file as Blob).type })),\n ),\n );\n for (const [index, blob] of blobs.entries()) {\n form.set(`file${index}`, blob, (files[index] as Partial<File>).name ?? 'blob');\n }\n init = { headers: { 'x-brumate-args': 'form' }, body: form };\n } else {\n init = { headers: { 'content-type': 'application/json' }, body: json };\n }\n return post(prefix, id, { ...init, signal });\n}\n\n/**\n * Sends a form to a server function, and returns its result. The form data\n * goes as it is, files included, as when the browser posts the form.\n */\nexport async function submit(\n prefix: string,\n id: string,\n form: FormData,\n key?: string | null,\n): Promise<unknown> {\n return post(prefix, id, { headers: { 'x-brumate-result': '1' }, body: form }, key);\n}\n\n/** Posts to a server function, and reads its answer. */\nasync function post(\n prefix: string,\n id: string,\n init: RequestInit,\n key?: string | null,\n): Promise<unknown> {\n const headers = new Headers(init.headers);\n // The build of the page, so the server can tell a call from before a deploy.\n if (build !== undefined) {\n headers.set('x-brumate-build', build);\n }\n // The key of a form of a function that `idempotent` made.\n const query = key ? `?__key=${encodeURIComponent(key)}` : '';\n return answer(\n id,\n await fetch(`${prefix}/${encodeURIComponent(id)}${query}`, {\n ...init,\n headers,\n method: 'POST',\n }),\n );\n}\n\n/** Reads the answer of a server function: its result, a redirect or an error. */\nasync function answer(id: string, response: Response): Promise<unknown> {\n // The server functions whose memos load again, from `refresh` on the server.\n const refreshed = response.headers.get('x-brumate-refresh');\n if (refreshed) {\n const ids = refreshed.split(',');\n void refreshMemos(ids);\n document.dispatchEvent(new CustomEvent('brumate:refresh', { detail: ids }));\n }\n const location = response.headers.get('x-brumate-redirect');\n if (location !== null) {\n // The loader navigates on the client when it can. Without client navigation, the page loads in full.\n const redirect = new CustomEvent('brumate:redirect', { detail: location, cancelable: true });\n if (document.dispatchEvent(redirect)) {\n window.location.assign(location);\n }\n // The page is leaving, so the call never settles.\n return new Promise(() => {});\n }\n if (!response.ok) {\n // The site changed, and this page is from before. The next page loads in full.\n if (response.status === 409 && response.headers.get('x-brumate-build')) {\n skew('call');\n }\n let message = `Server function \"${id}\" failed with status ${response.status}`;\n try {\n message = ((await response.json()) as { error: string }).error;\n } catch {\n // The body is not the error of a server function.\n }\n const retryAfter = Number(response.headers.get('retry-after'));\n throw Object.assign(new Error(message), {\n name: 'ServerError',\n status: response.status,\n // The seconds to wait, for a call that a rate limit refused.\n ...(retryAfter > 0 ? { retryAfter } : {}),\n });\n }\n // Promises and async iterables in the result settle as the rest of the answer arrives.\n return fromChunkStream(response.body!);\n}\n\n// The code below reads the core with `import()`, not a static import: a module that imports\n// the core statically would make the package build move the core into a chunk of its own, behind\n// a module that only re-exports it, which a page loads one after the other. The core is loaded\n// already when it runs, so the import costs no request. It names the exports it uses, so a build\n// keeps only them.\n\n/**\n * Loads again the memos that call these server functions, after a server\n * function named them with `refresh`. Each component on the page knows its\n * own memos, from its client module. It is here, and not in the core, because\n * only the answer of a server call starts it.\n */\nexport function refreshMemos(ids: string[]): Promise<void> {\n return import('./client.ts').then(({ descendants, loadModule, loadPart, scopes }) => {\n for (const root of scopes.values()) {\n if (!root.m) {\n continue;\n }\n void loadModule(root.m).then(async (module) => {\n const entries = ids.flatMap((id) => module.refresh?.[id] ?? []);\n if (entries.length === 0) {\n return;\n }\n const updates = await loadPart(module, 'update');\n for (const [kind, name] of entries) {\n for (const target of kind === root.k ? [root] : descendants(root, kind)) {\n if (scopes.has(target.id)) {\n (updates[name] as (scope: Scope) => void)(target);\n }\n }\n }\n });\n }\n });\n}\n\n/** Gives a form a new key in its URL, for its next post. */\nfunction renewKey(form: HTMLFormElement, url: URL): void {\n url.searchParams.set('__key', crypto.randomUUID());\n form.setAttribute('action', `${url.pathname}${url.search}`);\n}\n\n/**\n * Sends a form to the server function of its `$action`, and writes the\n * result into the `$action` when it arrives. It is pending until then. See\n * `submitAction` in the core.\n */\nexport function sendAction(form: HTMLFormElement, submitter: HTMLElement | null): Promise<void> {\n const [scopeId, slot] = form.getAttribute('b-result')!.split(':').map(Number) as [number, number];\n const data = new FormData(form, submitter);\n const action = form.getAttribute('b-action')!;\n return import('./client.ts').then(({ asyncMemo, rpcPrefix, scopes, track }) => {\n const scope = scopes.get(scopeId);\n if (scope) {\n // A form of a function that `idempotent` made sends its key, and gets a new one once the\n // server answered, so a post that the user means again runs again.\n const url = new URL(form.getAttribute('action') ?? '', location.href);\n const key = url.searchParams.get('__key');\n const result = submit(rpcPrefix, action, data, key);\n if (key) {\n void result.then(\n () => renewKey(form, url),\n () => {},\n );\n }\n const answered = result.catch((error: unknown) => {\n // The site changed since the page loaded. The form posts again without scripts, and the\n // page that answers is of the new build.\n if ((error as { status?: number }).status === 409 && build !== undefined) {\n form.submit();\n return new Promise(() => {});\n }\n throw error;\n });\n asy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,CAAC;IAC7B;IACA,MAAM;GACR,CAAC;GACD,UAAU,OAAO,MAAM,MAAM,QAAQ,CAAC;EACxC;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/runtime/batch.d.ts
|
|
2
|
+
export interface BatchOptions<K> {
|
|
3
|
+
/**
|
|
4
|
+
* What makes two calls the same key. Defaults to the key itself, and to
|
|
5
|
+
* its JSON for an object.
|
|
6
|
+
*/
|
|
7
|
+
key?: (key: K) => unknown;
|
|
8
|
+
/** The most keys in one call. A larger batch becomes several calls. */
|
|
9
|
+
limit?: number;
|
|
10
|
+
/** How long a batch gathers calls, in milliseconds. Defaults to 0, until the next task. */
|
|
11
|
+
wait?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Gives a function of one key, whose calls in the same moment become one
|
|
15
|
+
* call of `readMany` with every distinct key. Each call gets its value from
|
|
16
|
+
* `lookup`, with what `readMany` returned and its key.
|
|
17
|
+
*
|
|
18
|
+
* A failed read rejects only the calls that it read for, and a `lookup` that
|
|
19
|
+
* throws rejects only the calls of its key.
|
|
20
|
+
*/
|
|
21
|
+
export declare function batched<K, R, V>(readMany: (keys: K[]) => R | Promise<R>, lookup: (found: R, key: K) => V, options?: BatchOptions<K>): (key: K) => Promise<Awaited<V>>;
|
|
22
|
+
//#endregion
|
|
23
|
+
//# sourceMappingURL=batch.d.ts.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
//#region src/runtime/batch.ts
|
|
2
|
+
/** True while the server answers a request, from `request.ts`. A symbol of the registry, so the browser has none. */
|
|
3
|
+
const IN_REQUEST = Symbol.for("brumate.inRequest");
|
|
4
|
+
/** True on the server, or in a test while server code runs. */
|
|
5
|
+
function onServer() {
|
|
6
|
+
const inRequest = globalThis[IN_REQUEST];
|
|
7
|
+
return typeof document === "undefined" || inRequest?.() === true;
|
|
8
|
+
}
|
|
9
|
+
function identity(key) {
|
|
10
|
+
return key !== null && typeof key === "object" ? JSON.stringify(key) : key;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Gives a function of one key, whose calls in the same moment become one
|
|
14
|
+
* call of `readMany` with every distinct key. Each call gets its value from
|
|
15
|
+
* `lookup`, with what `readMany` returned and its key.
|
|
16
|
+
*
|
|
17
|
+
* A failed read rejects only the calls that it read for, and a `lookup` that
|
|
18
|
+
* throws rejects only the calls of its key.
|
|
19
|
+
*/
|
|
20
|
+
function batched(readMany, lookup, options = {}) {
|
|
21
|
+
const keyOf = options.key ?? identity;
|
|
22
|
+
const limit = Math.max(1, options.limit ?? Infinity);
|
|
23
|
+
let pending = /* @__PURE__ */ new Map();
|
|
24
|
+
let timer;
|
|
25
|
+
const read = async (entries) => {
|
|
26
|
+
let found;
|
|
27
|
+
try {
|
|
28
|
+
found = await readMany(entries.map((entry) => entry.key));
|
|
29
|
+
} catch (error) {
|
|
30
|
+
for (const entry of entries) for (const waiter of entry.waiters) waiter.reject(error);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
for (const entry of entries) try {
|
|
34
|
+
const value = lookup(found, entry.key);
|
|
35
|
+
for (const waiter of entry.waiters) waiter.resolve(value);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
for (const waiter of entry.waiters) waiter.reject(error);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const flush = () => {
|
|
41
|
+
timer = void 0;
|
|
42
|
+
const entries = [...pending.values()];
|
|
43
|
+
pending = /* @__PURE__ */ new Map();
|
|
44
|
+
for (let start = 0; start < entries.length; start += limit) read(entries.slice(start, start + limit));
|
|
45
|
+
};
|
|
46
|
+
return (key) => {
|
|
47
|
+
if (onServer()) return (async () => lookup(await readMany([key]), key))();
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const id = keyOf(key);
|
|
50
|
+
let entry = pending.get(id);
|
|
51
|
+
if (!entry) {
|
|
52
|
+
entry = {
|
|
53
|
+
key,
|
|
54
|
+
waiters: []
|
|
55
|
+
};
|
|
56
|
+
pending.set(id, entry);
|
|
57
|
+
}
|
|
58
|
+
entry.waiters.push({
|
|
59
|
+
resolve,
|
|
60
|
+
reject
|
|
61
|
+
});
|
|
62
|
+
timer ??= setTimeout(flush, options.wait ?? 0);
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
export { batched };
|
|
68
|
+
|
|
69
|
+
//# sourceMappingURL=batch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batch.js","names":[],"sources":["../../src/runtime/batch.ts"],"sourcesContent":["// Reads of many keys at once. In the browser, the calls of one moment, such\n// as the rows of a list that renders, become one call of a server function\n// with every key. The server renders the rows of a list one after another,\n// so there each call reads its own key at once.\n\nexport interface BatchOptions<K> {\n /**\n * What makes two calls the same key. Defaults to the key itself, and to\n * its JSON for an object.\n */\n key?: (key: K) => unknown;\n /** The most keys in one call. A larger batch becomes several calls. */\n limit?: number;\n /** How long a batch gathers calls, in milliseconds. Defaults to 0, until the next task. */\n wait?: number;\n}\n\ninterface Waiter<V> {\n resolve: (value: V) => void;\n reject: (error: unknown) => void;\n}\n\n/** True while the server answers a request, from `request.ts`. A symbol of the registry, so the browser has none. */\nconst IN_REQUEST = Symbol.for('brumate.inRequest');\n\n/** True on the server, or in a test while server code runs. */\nfunction onServer(): boolean {\n const inRequest = (globalThis as Record<symbol, (() => boolean) | undefined>)[IN_REQUEST];\n return typeof document === 'undefined' || inRequest?.() === true;\n}\n\nfunction identity(key: unknown): unknown {\n return key !== null && typeof key === 'object' ? JSON.stringify(key) : key;\n}\n\n/**\n * Gives a function of one key, whose calls in the same moment become one\n * call of `readMany` with every distinct key. Each call gets its value from\n * `lookup`, with what `readMany` returned and its key.\n *\n * A failed read rejects only the calls that it read for, and a `lookup` that\n * throws rejects only the calls of its key.\n */\nexport function batched<K, R, V>(\n readMany: (keys: K[]) => R | Promise<R>,\n lookup: (found: R, key: K) => V,\n options: BatchOptions<K> = {},\n): (key: K) => Promise<Awaited<V>> {\n const keyOf = options.key ?? identity;\n const limit = Math.max(1, options.limit ?? Infinity);\n let pending = new Map<unknown, { key: K; waiters: Waiter<Awaited<V>>[] }>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const read = async (entries: { key: K; waiters: Waiter<Awaited<V>>[] }[]): Promise<void> => {\n let found: R;\n try {\n found = await readMany(entries.map((entry) => entry.key));\n } catch (error) {\n for (const entry of entries) {\n for (const waiter of entry.waiters) {\n waiter.reject(error);\n }\n }\n return;\n }\n for (const entry of entries) {\n try {\n // A promise that `lookup` returns settles each call by itself.\n const value = lookup(found, entry.key) as Awaited<V>;\n for (const waiter of entry.waiters) {\n waiter.resolve(value);\n }\n } catch (error) {\n for (const waiter of entry.waiters) {\n waiter.reject(error);\n }\n }\n }\n };\n\n const flush = (): void => {\n timer = undefined;\n const entries = [...pending.values()];\n pending = new Map();\n for (let start = 0; start < entries.length; start += limit) {\n void read(entries.slice(start, start + limit));\n }\n };\n\n return (key) => {\n if (onServer()) {\n // One read for the key, at once, so it reads the event of the request and shares the\n // result of equal calls in the render.\n return (async () => lookup(await readMany([key]), key))() as Promise<Awaited<V>>;\n }\n return new Promise<Awaited<V>>((resolve, reject) => {\n const id = keyOf(key);\n let entry = pending.get(id);\n if (!entry) {\n entry = { key, waiters: [] };\n pending.set(id, entry);\n }\n entry.waiters.push({ resolve, reject });\n timer ??= setTimeout(flush, options.wait ?? 0);\n });\n };\n}\n"],"mappings":";;AAuBA,MAAM,aAAa,OAAO,IAAI,mBAAmB;;AAGjD,SAAS,WAAoB;CAC3B,MAAM,YAAa,WAA2D;CAC9E,OAAO,OAAO,aAAa,eAAe,YAAY,MAAM;AAC9D;AAEA,SAAS,SAAS,KAAuB;CACvC,OAAO,QAAQ,QAAQ,OAAO,QAAQ,WAAW,KAAK,UAAU,GAAG,IAAI;AACzE;;;;;;;;;AAUA,SAAgB,QACd,UACA,QACA,UAA2B,CAAC,GACK;CACjC,MAAM,QAAQ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H;AACF"}
|
package/dist/runtime/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
export { ClientModule, Component, CoreOptions, DEVTOOLS, DevtoolsHooks, ElementReference, FunctionReference, HiddenBody, Part, type Raw, Scope, action, addHead, addPortal, addStyle, affix, afterInsert, asyncMemo, attr, attribute, attrs, branch, cells, classAttribute, component, consumeContext, content, createContext, createScope, descendants, dispose, dynamic, effect, elementAt, escape, fill, forget, get, guess, handle, handlerProp, hooks, init, insert, leavePage, leaveRoutes, list, loadModule, loadPart, loader, makeId, memo, offscreen, pending, portalTo, produce, prop, provideValue, raw, rekey, remount, removeRoot, removeScope, reset, rpc, rpcPrefix, scopeOf, scopes, set, setItem, setOwner, setSlots, setVar, spread, submitAction, text, title, track, update, updateContext, vars, writeText };
|
|
1
|
+
import { $ as offscreen, A as dispose, At as updated, B as handlerProp, C as children, Ct as text, D as createScope, Dt as update, E as content, Et as track, F as fill, G as leaveRoutes, H as init, I as forget, J as loadModule, K as list, L as get, M as effect, N as elementAt, O as deferInBrowser, Ot as updateContext, P as fail, Q as memo, R as guess, S as cells, St as submitAction, T as consumeContext, Tt as title, U as insert, V as hooks, W as leavePage, X as loader, Y as loadPart, Z as makeId, _ as attrs, _t as setSlots, a as DevtoolsHooks, at as remount, b as branch, bt as spread, c as Part, ct as reset, d as addHead, dt as scopeOf, et as pending, f as addPortal, ft as scopes, g as attr, gt as setOwner, h as asyncMemo, ht as setItem, i as DEVTOOLS, it as rekey, j as dynamic, jt as writeText, k as descendants, kt as updateRoute, l as Scope, lt as rpc, m as afterInsert, mt as setGlobal, n as Component, nt as prop, o as HiddenBody, ot as removeRoot, p as addStyle, pt as set, q as listOf, r as CoreOptions, rt as provideValue, s as LoadReason, st as removeScope, t as ClientModule, tt as portalTo, u as action, ut as rpcPrefix, v as binding, vt as setVar, w as component, wt as timed, x as build, xt as spreadProps, y as bindings, yt as skew, z as handle } from "../client-D0CqSxoO.js";
|
|
2
|
+
import { S as vars, _ as raw, a as attribute, c as classAttribute, g as onAttribute, h as mergeAttributes, i as affix, t as Raw, u as escape } from "../html-Bq1rFxX_.js";
|
|
3
|
+
import { i as FunctionReference, l as unbind, r as ElementReference, t as produce } from "../produce-D0V0ICkz.js";
|
|
4
|
+
import { c as routeContext, o as createContext, s as navigationContext } from "../context-btHuB01Z.js";
|
|
5
|
+
export { ClientModule, Component, CoreOptions, DEVTOOLS, DevtoolsHooks, ElementReference, FunctionReference, HiddenBody, LoadReason, Part, type Raw, Scope, action, addHead, addPortal, addStyle, affix, afterInsert, asyncMemo, attr, attribute, attrs, binding, bindings, branch, build, cells, children, classAttribute, component, consumeContext, content, createContext, createScope, deferInBrowser, descendants, dispose, dynamic, effect, elementAt, escape, fail, fill, forget, get, guess, handle, handlerProp, hooks, init, insert, leavePage, leaveRoutes, list, listOf, loadModule, loadPart, loader, makeId, memo, mergeAttributes, navigationContext, offscreen, onAttribute, pending, portalTo, produce, prop, provideValue, raw, rekey, remount, removeRoot, removeScope, reset, routeContext, rpc, rpcPrefix, scopeOf, scopes, set, setGlobal, setItem, setOwner, setSlots, setVar, skew, spread, spreadProps, submitAction, text, timed, title, track, unbind, update, updateContext, updateRoute, updated, vars, writeText };
|