rosetack 0.0.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/deploy/Dockerfile.node +25 -0
- package/deploy/Dockerfile.static +34 -0
- package/deploy/api/rosetack.ts +29 -0
- package/deploy/docker-compose.yml +33 -0
- package/deploy/fly.toml +28 -0
- package/deploy/vercel.json +13 -0
- package/dist-cli/compiler.mjs +2302 -0
- package/dist-cli/edge.mjs +297 -0
- package/dist-cli/rosetack.mjs +3411 -0
- package/dist-cli/runtime.mjs +619 -0
- package/dist-cli/test.mjs +2696 -0
- package/pack.mjs +49 -0
- package/package.json +50 -11
- package/src/FRAMEWORK_VERSION +1 -0
- package/src/cli/edge.ts +162 -0
- package/src/cli/index.ts +1233 -0
- package/src/cli/shell.ts +337 -0
- package/src/cli/test.ts +400 -0
- package/src/compiler/index.ts +3076 -0
- package/src/runtime/index.ts +915 -0
- package/src/types/rosetack.d.ts +142 -0
- package/README.md +0 -3
- package/index.js +0 -12
|
@@ -0,0 +1,915 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rosetack Runtime - Zero-hydration, compile-time reactivity
|
|
3
|
+
* Target: < 2KB gzipped
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// === Reactive Primitives ===
|
|
7
|
+
|
|
8
|
+
type Subscriber = () => void;
|
|
9
|
+
type Cleanup = () => void;
|
|
10
|
+
type SignalEntry = { value: unknown; subs: Set<Subscriber> };
|
|
11
|
+
|
|
12
|
+
let currentEffect: (() => void) | null = null;
|
|
13
|
+
|
|
14
|
+
// Trade-off: global signal map, shared across all inlined modules
|
|
15
|
+
let signalMap: Map<string, SignalEntry> =
|
|
16
|
+
(globalThis as any).__rosetack_signalMap ?? new Map();
|
|
17
|
+
(globalThis as any).__rosetack_signalMap = signalMap;
|
|
18
|
+
|
|
19
|
+
// One get-or-create helper shared by state / setState / resumeState.
|
|
20
|
+
function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subscriber> } {
|
|
21
|
+
const e = signalMap.get(key) ?? { value: initial, subs: new Set<Subscriber>() };
|
|
22
|
+
signalMap.set(key, e);
|
|
23
|
+
return e;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
|
|
27
|
+
const e = entry(key, initial);
|
|
28
|
+
|
|
29
|
+
const getter = () => {
|
|
30
|
+
if (currentEffect) e.subs.add(currentEffect);
|
|
31
|
+
return e.value as T;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const setter = (v: T) => {
|
|
35
|
+
e.value = v;
|
|
36
|
+
e.subs.forEach((fn: Subscriber) => fn());
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
return [getter, setter];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function hasState(key: string): boolean {
|
|
43
|
+
return signalMap.has(key);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function setState<T>(key: string, value: T): void {
|
|
47
|
+
const e = entry(key, value);
|
|
48
|
+
e.value = value;
|
|
49
|
+
e.subs.forEach((fn: Subscriber) => fn());
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Effects are tracked so client-side navigation can dispose the old ones.
|
|
53
|
+
// Each cleanup removes itself, so locally disposed effects do not leak.
|
|
54
|
+
const cleanups = new Set<Cleanup>();
|
|
55
|
+
|
|
56
|
+
export function effect(fn: () => void): Cleanup {
|
|
57
|
+
const wrapped: Subscriber = () => {
|
|
58
|
+
try {
|
|
59
|
+
fn();
|
|
60
|
+
} catch {
|
|
61
|
+
// subscriber may be stale; ignore
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const prev = currentEffect;
|
|
65
|
+
currentEffect = wrapped;
|
|
66
|
+
fn();
|
|
67
|
+
currentEffect = prev;
|
|
68
|
+
const cleanup: Cleanup = () => {
|
|
69
|
+
signalMap.forEach((e: { subs: Set<Subscriber> }) => e.subs.delete(wrapped));
|
|
70
|
+
cleanups.delete(cleanup);
|
|
71
|
+
};
|
|
72
|
+
cleanups.add(cleanup);
|
|
73
|
+
return cleanup;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// === HTML escaping (server-side interpolation safety) ===
|
|
77
|
+
|
|
78
|
+
const ESC_MAP: Record<string, string> = {
|
|
79
|
+
'&': '&',
|
|
80
|
+
'<': '<',
|
|
81
|
+
'>': '>',
|
|
82
|
+
'"': '"',
|
|
83
|
+
"'": ''',
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export function esc(v: unknown): string {
|
|
87
|
+
return String(v).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// === Generated-code marker helpers === Every reactive marker in every generated module is
|
|
91
|
+
// emitted through these five functions …
|
|
92
|
+
|
|
93
|
+
type Close = (s?: unknown) => unknown;
|
|
94
|
+
|
|
95
|
+
export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unknown): string {
|
|
96
|
+
const i = closes.push(fn) - 1;
|
|
97
|
+
return `<!--\u27e6m:${i}\u27e7-->` + esc(closes[i](arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
|
|
101
|
+
const i = closes.push(fn) - 1;
|
|
102
|
+
return `${name}="${esc(closes[i](arg))}" data-b="${i}:${name}"`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function ifMark(
|
|
106
|
+
closes: Close[],
|
|
107
|
+
cond: Close,
|
|
108
|
+
fn: (s: unknown, c: Close[]) => unknown,
|
|
109
|
+
scope?: unknown
|
|
110
|
+
): string {
|
|
111
|
+
const i = closes.length;
|
|
112
|
+
// The content renders the FIRST time the block shows, never before, and is then memoized
|
|
113
|
+
// for this render: a block that never shows costs nothing and a block that shows renders …
|
|
114
|
+
let snap: { html: string; closes: Close[] } | null = null;
|
|
115
|
+
closes.push(() => {
|
|
116
|
+
if (!cond()) return null;
|
|
117
|
+
if (!snap) {
|
|
118
|
+
const c: Close[] = [];
|
|
119
|
+
snap = { html: String(fn(scope, c)), closes: c };
|
|
120
|
+
}
|
|
121
|
+
return snap;
|
|
122
|
+
});
|
|
123
|
+
const r = closes[i]() as { html: string } | null;
|
|
124
|
+
return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
|
|
128
|
+
const i = closes.length;
|
|
129
|
+
closes.push(() => (items() as unknown[]).map((v) => {
|
|
130
|
+
const c: Close[] = [];
|
|
131
|
+
return { html: String(fn(v, c)), closes: c, scope: v };
|
|
132
|
+
}));
|
|
133
|
+
let h = `<!--\u27e6l:${i}\u27e7-->`;
|
|
134
|
+
for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
|
|
135
|
+
return h + `<!--\u27e6/l:${i}\u27e7-->`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function headMark(closes: Close[], fn: Close): string {
|
|
139
|
+
const i = closes.push(fn) - 1;
|
|
140
|
+
return `<!--\u27e6h:${i}\u27e7-->` + fn() + `<!--\u27e6/h:${i}\u27e7-->`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// === Reactive DOM wiring (client) ===
|
|
144
|
+
|
|
145
|
+
const MARK_RE = /^\u27e6([milh]):(\d+)\u27e7$/;
|
|
146
|
+
// `m` ends a text marker whose value is followed by literal text:
|
|
147
|
+
// the pair bounds exactly the value, so patching it cannot eat the prose.
|
|
148
|
+
const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
|
|
149
|
+
|
|
150
|
+
// Comments already handled by a nested wire() pass (e.g. inside an adopted {#if} block)
|
|
151
|
+
// must not be re-processed by the outer pass with the wrong closes array.
|
|
152
|
+
const wired = new WeakSet<Node>();
|
|
153
|
+
|
|
154
|
+
/** Parse an html string into a DocumentFragment. */
|
|
155
|
+
export function tpl(html: string): DocumentFragment {
|
|
156
|
+
const t = document.createElement('template');
|
|
157
|
+
t.innerHTML = html;
|
|
158
|
+
return t.content;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// === Document head (<head> blocks) ===
|
|
162
|
+
|
|
163
|
+
// Marks the head elements rosetack manages, so stale ones can be removed when a route's
|
|
164
|
+
// head changes and user-authored <head> content is never touched.
|
|
165
|
+
const HEAD_ATTR = 'data-rosetack-head';
|
|
166
|
+
|
|
167
|
+
// The delegated-event handler registry: every compiled module registers its handlers here
|
|
168
|
+
// (Object.assign(handlers, { ...
|
|
169
|
+
export const handlers: Record<string, (e: Event) => void> =
|
|
170
|
+
(globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Apply one route's whole <head> (every block of its chain, page first) to the
|
|
174
|
+
* document: <title> replaces the title, <meta>/<link>/<base> are matched by
|
|
175
|
+
* name/property/rel/charset. First occurrence of a key wins, so a page
|
|
176
|
+
* overrides its layouts - the same rule the server's mergeHeadBlocks applies,
|
|
177
|
+
* which is why the two halves agree without talking to each other.
|
|
178
|
+
*
|
|
179
|
+
* The managed set is REBUILT from the block rather than patched element by
|
|
180
|
+
* element: a route's head is the whole truth, so anything the previous route
|
|
181
|
+
* provided and this one does not is dropped, and a key that moved tags is
|
|
182
|
+
* replaced instead of duplicated. It is also a third of the code.
|
|
183
|
+
*/
|
|
184
|
+
export function applyHead(html: string): void {
|
|
185
|
+
const seen = new Set<string>();
|
|
186
|
+
const frag = tpl(html);
|
|
187
|
+
const title = frag.querySelector('title');
|
|
188
|
+
if (title) {
|
|
189
|
+
// Manage the title element directly: the document.title setter would update the FIRST
|
|
190
|
+
// title element in tree order …
|
|
191
|
+
let cur = document.head.querySelector('title');
|
|
192
|
+
if (!cur) {
|
|
193
|
+
cur = document.createElement('title');
|
|
194
|
+
document.head.appendChild(cur);
|
|
195
|
+
}
|
|
196
|
+
cur.textContent = title.textContent ?? '';
|
|
197
|
+
}
|
|
198
|
+
for (const el of Array.from(document.head.querySelectorAll(`[${HEAD_ATTR}]`))) el.remove();
|
|
199
|
+
for (const el of Array.from(frag.children)) {
|
|
200
|
+
if (el.tagName === 'TITLE') continue;
|
|
201
|
+
const key = el.getAttribute('name')
|
|
202
|
+
?? el.getAttribute('property')
|
|
203
|
+
?? el.getAttribute('rel')
|
|
204
|
+
?? el.getAttribute('charset');
|
|
205
|
+
if (!key) continue;
|
|
206
|
+
const managed = `${el.tagName.toLowerCase()}:${key}`;
|
|
207
|
+
if (seen.has(managed)) continue; // first block wins: page over layout
|
|
208
|
+
seen.add(managed);
|
|
209
|
+
el.setAttribute(HEAD_ATTR, managed);
|
|
210
|
+
document.head.appendChild(el);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Drop every rosetack-managed head element (routes without <head> blocks). */
|
|
215
|
+
export function clearHead(): void {
|
|
216
|
+
document.head.querySelectorAll(`[${HEAD_ATTR}]`).forEach((el) => el.remove());
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Wire reactive markers inside `root` to the closures in `closes`.
|
|
221
|
+
* Works on the live SSR DOM (adoption) and on freshly parsed fragments.
|
|
222
|
+
* Returns a disposer for every effect it created.
|
|
223
|
+
*/
|
|
224
|
+
export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Cleanup {
|
|
225
|
+
let holder: Node = root;
|
|
226
|
+
if (root.nodeType === 11) {
|
|
227
|
+
// DocumentFragment: wrap so querySelectorAll sees the root element too
|
|
228
|
+
const div = document.createElement('div');
|
|
229
|
+
div.appendChild(root);
|
|
230
|
+
holder = div;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const created: Cleanup[] = [];
|
|
234
|
+
const weff = (fn: () => void) => created.push(effect(fn));
|
|
235
|
+
|
|
236
|
+
const comments: Comment[] = [];
|
|
237
|
+
const walker = document.createTreeWalker(holder, NodeFilter.SHOW_COMMENT);
|
|
238
|
+
while (walker.nextNode()) comments.push(walker.currentNode as Comment);
|
|
239
|
+
|
|
240
|
+
// Comments that live INSIDE an {#if}/{#each}/slot block belong to that block's OWN wire
|
|
241
|
+
// pass …
|
|
242
|
+
const nested = new Set<Comment>();
|
|
243
|
+
for (let i = 0; i < comments.length; i++) {
|
|
244
|
+
const m = (comments[i].nodeValue ?? '').match(MARK_RE);
|
|
245
|
+
if (!m || (m[1] !== 'i' && m[1] !== 'l')) continue;
|
|
246
|
+
for (let j = i + 1; j < comments.length; j++) {
|
|
247
|
+
const em = (comments[j].nodeValue ?? '').match(END_RE);
|
|
248
|
+
if (em && em[1] === m[1] && +em[2] === +m[2]) {
|
|
249
|
+
for (let k = i + 1; k < j; k++) nested.add(comments[k]);
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const ends = new Map<number, Comment>();
|
|
256
|
+
for (const c of comments) {
|
|
257
|
+
if (nested.has(c)) continue;
|
|
258
|
+
const m = (c.nodeValue ?? '').match(END_RE);
|
|
259
|
+
if (m) ends.set(+m[2], c);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Head blocks are collected during the walk and applied afterwards as ONE effect over the
|
|
263
|
+
// whole route's head: the blocks render in document order …
|
|
264
|
+
const headBlocks: Array<{ idx: number; start: Comment; end: Comment; nodes: ChildNode[] }> = [];
|
|
265
|
+
|
|
266
|
+
for (const c of comments) {
|
|
267
|
+
if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
|
|
268
|
+
wired.add(c);
|
|
269
|
+
const m = (c.nodeValue ?? '').match(MARK_RE);
|
|
270
|
+
if (!m) continue;
|
|
271
|
+
const kind = m[1];
|
|
272
|
+
const idx = +m[2];
|
|
273
|
+
|
|
274
|
+
if (kind === 'h') {
|
|
275
|
+
// Document head: the closure re-renders the <head> block (no inner
|
|
276
|
+
// markers), so one effect drives title/meta for this route.
|
|
277
|
+
const end = ends.get(idx);
|
|
278
|
+
if (!end) continue;
|
|
279
|
+
const nodes: ChildNode[] = [];
|
|
280
|
+
let n: ChildNode | null = c.nextSibling;
|
|
281
|
+
while (n && n !== end) {
|
|
282
|
+
const nx = n.nextSibling;
|
|
283
|
+
nodes.push(n);
|
|
284
|
+
n = nx;
|
|
285
|
+
}
|
|
286
|
+
headBlocks.push({ idx, start: c, end, nodes });
|
|
287
|
+
} else if (kind === 'm') {
|
|
288
|
+
// Text: update the text node that follows the marker comment. When the marker is a
|
|
289
|
+
// PAIR (value followed by literal text) …
|
|
290
|
+
let target = c.nextSibling;
|
|
291
|
+
if (!target || target.nodeType !== 3) {
|
|
292
|
+
target = document.createTextNode('');
|
|
293
|
+
c.parentNode!.insertBefore(target, c.nextSibling);
|
|
294
|
+
}
|
|
295
|
+
const tn = target as Text;
|
|
296
|
+
const end = ends.get(idx);
|
|
297
|
+
if (end) {
|
|
298
|
+
let n: ChildNode | null = tn.nextSibling;
|
|
299
|
+
while (n && n !== end) {
|
|
300
|
+
const nx = n.nextSibling;
|
|
301
|
+
n.remove();
|
|
302
|
+
n = nx;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
weff(() => {
|
|
306
|
+
tn.nodeValue = String((closes[idx] as (s?: unknown) => unknown)(scope));
|
|
307
|
+
});
|
|
308
|
+
} else if (kind === 'i') {
|
|
309
|
+
// Conditional block: first run adopts the server-rendered content in
|
|
310
|
+
// place (node identity preserved); later runs swap in a fresh clone.
|
|
311
|
+
const anchor = c;
|
|
312
|
+
const end = ends.get(idx);
|
|
313
|
+
if (!end) continue;
|
|
314
|
+
const st = anchor as unknown as { __st?: { nodes: Node[]; disp: Cleanup }; __ever?: boolean };
|
|
315
|
+
weff(() => {
|
|
316
|
+
if (st.__st) {
|
|
317
|
+
st.__st.nodes.forEach((n) => (n as ChildNode).remove());
|
|
318
|
+
st.__st.disp();
|
|
319
|
+
st.__st = undefined;
|
|
320
|
+
}
|
|
321
|
+
const r = (closes[idx] as (s?: unknown) => unknown)(scope) as { html: string; closes: unknown[] } | null;
|
|
322
|
+
if (!r) return;
|
|
323
|
+
// First run adopts the server-rendered content (move out, wire, move back -
|
|
324
|
+
// identity preserved); later runs clone the block template.
|
|
325
|
+
let frag: DocumentFragment;
|
|
326
|
+
if (st.__ever) {
|
|
327
|
+
frag = tpl(r.html);
|
|
328
|
+
} else {
|
|
329
|
+
st.__ever = true;
|
|
330
|
+
frag = document.createDocumentFragment();
|
|
331
|
+
let n = anchor.nextSibling;
|
|
332
|
+
while (n && n !== end) {
|
|
333
|
+
const nx = n.nextSibling;
|
|
334
|
+
frag.appendChild(n);
|
|
335
|
+
n = nx;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// r.scope is set by a named slot's block: its content is scoped to the object the child
|
|
339
|
+
// passed in, exactly like a list item.
|
|
340
|
+
const disp = wire(frag, r.closes, (r as { scope?: unknown }).scope ?? scope);
|
|
341
|
+
const nodes = Array.from(frag.childNodes);
|
|
342
|
+
const parent = anchor.parentNode!;
|
|
343
|
+
for (const nd of nodes) parent.insertBefore(nd, anchor.nextSibling);
|
|
344
|
+
st.__st = { nodes, disp };
|
|
345
|
+
});
|
|
346
|
+
} else {
|
|
347
|
+
// List: rebuild items between the start and end anchors
|
|
348
|
+
const start = c;
|
|
349
|
+
const end = ends.get(idx);
|
|
350
|
+
if (!end) continue;
|
|
351
|
+
const st = start as unknown as { __disp?: Cleanup };
|
|
352
|
+
weff(() => {
|
|
353
|
+
if (st.__disp) {
|
|
354
|
+
st.__disp();
|
|
355
|
+
st.__disp = undefined;
|
|
356
|
+
}
|
|
357
|
+
const items = (closes[idx] as (s?: unknown) => unknown)(scope) as Array<{ html: string; closes: unknown[]; scope?: unknown }>;
|
|
358
|
+
let n = start.nextSibling;
|
|
359
|
+
while (n && n !== end) {
|
|
360
|
+
const nx = n.nextSibling;
|
|
361
|
+
n.remove();
|
|
362
|
+
n = nx;
|
|
363
|
+
}
|
|
364
|
+
const parent = start.parentNode!;
|
|
365
|
+
const disps: Cleanup[] = [];
|
|
366
|
+
for (const r of items) {
|
|
367
|
+
const frag = tpl(r.html);
|
|
368
|
+
disps.push(wire(frag, r.closes, r.scope));
|
|
369
|
+
for (const nd of Array.from(frag.childNodes)) parent.insertBefore(nd, end);
|
|
370
|
+
}
|
|
371
|
+
st.__disp = () => disps.forEach((d) => d());
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Apply head blocks, then drop the inert placeholder nodes from the page body. A
|
|
377
|
+
// top-level wire with no head blocks (route without <head>) clears the previous route's
|
|
378
|
+
// managed …
|
|
379
|
+
if (headBlocks.length > 0) {
|
|
380
|
+
const blocks = headBlocks;
|
|
381
|
+
weff(() => {
|
|
382
|
+
let html = '';
|
|
383
|
+
for (const b of blocks) html += String((closes[b.idx] as (s?: unknown) => unknown)(scope));
|
|
384
|
+
applyHead(html);
|
|
385
|
+
});
|
|
386
|
+
for (const b of blocks) {
|
|
387
|
+
b.nodes.forEach((nd) => nd.remove());
|
|
388
|
+
b.start.remove();
|
|
389
|
+
b.end.remove();
|
|
390
|
+
}
|
|
391
|
+
} else if (root.nodeType !== 11) clearHead();
|
|
392
|
+
|
|
393
|
+
// Attributes: data-b="K:attrName"
|
|
394
|
+
const els = (holder as Element).querySelectorAll('[data-b]');
|
|
395
|
+
els.forEach((el) => {
|
|
396
|
+
const spec = el.getAttribute('data-b')!;
|
|
397
|
+
const sep = spec.indexOf(':');
|
|
398
|
+
const idx = +spec.slice(0, sep);
|
|
399
|
+
const attr = spec.slice(sep + 1);
|
|
400
|
+
el.removeAttribute('data-b');
|
|
401
|
+
weff(() => {
|
|
402
|
+
el.setAttribute(attr, String((closes[idx] as (s?: unknown) => unknown)(scope)));
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
if (holder !== root) {
|
|
407
|
+
while (holder.firstChild) root.appendChild(holder.firstChild);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return () => created.forEach((fn) => fn());
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export function resetEffects(): void {
|
|
414
|
+
cleanups.forEach((fn) => fn());
|
|
415
|
+
cleanups.clear();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// === Server Data Fetching ($data) ===
|
|
419
|
+
|
|
420
|
+
// Trade-off: cache keyed by function source, cleared per request/navigation.
|
|
421
|
+
// Upgrade path: explicit keys if two $data calls share identical source.
|
|
422
|
+
let dataCache = new Map<string, Promise<unknown>>();
|
|
423
|
+
|
|
424
|
+
export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
|
|
425
|
+
const key = fn.toString();
|
|
426
|
+
let p = dataCache.get(key);
|
|
427
|
+
if (!p) {
|
|
428
|
+
p = Promise.resolve(fn());
|
|
429
|
+
dataCache.set(key, p);
|
|
430
|
+
}
|
|
431
|
+
return p as Promise<T>;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Per-request isolation: state + data cache reset before each SSR render. The request
|
|
435
|
+
// context bag is NOT reset here: it is owned by the middleware pass (runMiddleware) …
|
|
436
|
+
export function clearRequestState(): void {
|
|
437
|
+
signalMap.clear();
|
|
438
|
+
dataCache.clear();
|
|
439
|
+
pendingDeltas.clear();
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// === Request context === A per-request bag: pages/_middleware.rose fills it
|
|
443
|
+
// (getContext().user = ...) and $data, server actions and api handlers read it.
|
|
444
|
+
let requestContext: Record<string, unknown> = {};
|
|
445
|
+
|
|
446
|
+
export function getContext(): Record<string, unknown> {
|
|
447
|
+
return requestContext;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Fresh bag for a new request - runMiddleware() calls this before the middleware. */
|
|
451
|
+
export function resetRequestContext(): void {
|
|
452
|
+
requestContext = {};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Run an async render against a THROWAWAY signal map + data cache + mount
|
|
457
|
+
* queue + cleanup set, returning the rendered result plus the signal entries,
|
|
458
|
+
* the onMount callbacks and the onCleanup disposers it produced.
|
|
459
|
+
*
|
|
460
|
+
* Used by link prefetch: rendering the hovered route ahead of navigation must
|
|
461
|
+
* not touch the live page's state (or queue its mounts / register its
|
|
462
|
+
* cleanups), but the paint that consumes the entry later needs exactly those
|
|
463
|
+
* things - compiled getters close over entry OBJECTS, so restoreState()
|
|
464
|
+
* transplants them wholesale instead of copying values, the captured mounts
|
|
465
|
+
* replay after the prefetched DOM is wired, and adoptCleanups() re-registers
|
|
466
|
+
* the captured disposers so the NEXT resetEffects() disposes them (a prefetch
|
|
467
|
+
* render's cleanups firing early would dispose a route that was never
|
|
468
|
+
* painted, and dropping them would leak the painted route's timers).
|
|
469
|
+
* Concurrent prefetches are queued by the caller (trade-off: hover prefetches
|
|
470
|
+
* are rare and cheap).
|
|
471
|
+
*/
|
|
472
|
+
export async function isolateStateAsync<T>(
|
|
473
|
+
fn: () => Promise<T>
|
|
474
|
+
): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
|
|
475
|
+
const savedSignals = signalMap;
|
|
476
|
+
const savedData = dataCache;
|
|
477
|
+
const savedDeltas = new Map(pendingDeltas); // a prefetch render must not consume a delta
|
|
478
|
+
pendingDeltas.clear();
|
|
479
|
+
const savedMounts = mountQueue.splice(0, mountQueue.length);
|
|
480
|
+
const savedCleanups = new Set(cleanups);
|
|
481
|
+
cleanups.clear();
|
|
482
|
+
signalMap = new Map();
|
|
483
|
+
dataCache = new Map();
|
|
484
|
+
try {
|
|
485
|
+
const result = await fn();
|
|
486
|
+
return {
|
|
487
|
+
result,
|
|
488
|
+
state: signalMap,
|
|
489
|
+
mounts: mountQueue.splice(0, mountQueue.length),
|
|
490
|
+
cleanups: new Set(cleanups),
|
|
491
|
+
};
|
|
492
|
+
} finally {
|
|
493
|
+
signalMap = savedSignals;
|
|
494
|
+
dataCache = savedData;
|
|
495
|
+
pendingDeltas.clear();
|
|
496
|
+
savedDeltas.forEach((d, k) => pendingDeltas.set(k, d)); // restore what was pending
|
|
497
|
+
mountQueue.splice(0, 0, ...savedMounts); // prepend what was queued before
|
|
498
|
+
cleanups.clear();
|
|
499
|
+
savedCleanups.forEach((fn: Cleanup) => cleanups.add(fn));
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** Adopt a prefetched route's signal entries (objects keep their subs). */
|
|
504
|
+
export function restoreState(entries: Map<string, SignalEntry>): void {
|
|
505
|
+
signalMap.clear();
|
|
506
|
+
entries.forEach((e: SignalEntry, k: string) => signalMap.set(k, e));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// === Serialization (for zero-hydration resume) ===
|
|
510
|
+
|
|
511
|
+
export function serializeState(): string {
|
|
512
|
+
const obj: Record<string, unknown> = {};
|
|
513
|
+
signalMap.forEach((v: { value: unknown }, k: string) => (obj[k] = v.value));
|
|
514
|
+
return JSON.stringify(obj);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export function resumeState(json: string): void {
|
|
518
|
+
try {
|
|
519
|
+
const obj = JSON.parse(json);
|
|
520
|
+
Object.entries(obj).forEach(([k, v]) => {
|
|
521
|
+
entry(k, v).value = v;
|
|
522
|
+
});
|
|
523
|
+
} catch {
|
|
524
|
+
// ignore corrupt state
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// === Client-side route refresh === The client entry registers the re-render here at boot;
|
|
529
|
+
// components import refresh() like state() and call it from any handler …
|
|
530
|
+
let refreshHook: (() => Promise<void>) | null = null;
|
|
531
|
+
|
|
532
|
+
export function setRefreshHook(fn: () => Promise<void>): void {
|
|
533
|
+
refreshHook = fn;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export function refresh(): Promise<void> {
|
|
537
|
+
return refreshHook ? refreshHook() : Promise.resolve();
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// === Lifecycle === Client-only. onMount queues a callback; the client entry flushes the
|
|
541
|
+
// queue after wire() completes - initial adoption, client-side navigation, prefetch paint …
|
|
542
|
+
const mountQueue: Array<() => void> = [];
|
|
543
|
+
|
|
544
|
+
export function onMount(fn: () => void): void {
|
|
545
|
+
if (typeof document === 'undefined') return; // server render: nothing mounts
|
|
546
|
+
mountQueue.push(fn);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Drop queued mounts - a failed render leaves stale callbacks behind. */
|
|
550
|
+
export function clearMounts(): void {
|
|
551
|
+
mountQueue.length = 0;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** Run and clear the queue; the client entry calls this after every wire(). */
|
|
555
|
+
export function flushMounts(): void {
|
|
556
|
+
const q = mountQueue.splice(0, mountQueue.length);
|
|
557
|
+
for (const fn of q) fn();
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/** Register a disposer for the current render (the effects' cleanup channel). */
|
|
561
|
+
export function onCleanup(fn: Cleanup): void {
|
|
562
|
+
cleanups.add(fn);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Adopt a prefetched route's captured onCleanup disposers after its cached
|
|
567
|
+
* paint lands: the next resetEffects() (before the following re-render) then
|
|
568
|
+
* disposes them like any live route's. Without this the prefetched paint's
|
|
569
|
+
* mounts would start timers nothing ever clears.
|
|
570
|
+
*/
|
|
571
|
+
export function adoptCleanups(fns: Iterable<Cleanup>): void {
|
|
572
|
+
for (const fn of fns) cleanups.add(fn);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// === i18n: localized routes === Every JSON file in src/locales/ is a language: { "key":
|
|
576
|
+
// "string" }.
|
|
577
|
+
let LOCALES: Record<string, Record<string, string>> = {};
|
|
578
|
+
let DEFAULT_LOCALE = 'en';
|
|
579
|
+
// The locales this build did NOT bake in: they live at /locales/<lang>.json and
|
|
580
|
+
// ensureLocale() fetches one on first use.
|
|
581
|
+
let LOCALE_PACKS: string[] = [];
|
|
582
|
+
|
|
583
|
+
export function setLocales(dicts: Record<string, Record<string, string>>, def: string): void {
|
|
584
|
+
LOCALES = dicts;
|
|
585
|
+
DEFAULT_LOCALE = def;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** The locales the build left out of this bundle (generated code calls this). */
|
|
589
|
+
export function setLocalePacks(langs: string[]): void {
|
|
590
|
+
LOCALE_PACKS = langs;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** Merge a dictionary that arrived at runtime - a fetched pack, or an app's own import(). */
|
|
594
|
+
export function loadLocale(lang: string, dict: Record<string, string>): void {
|
|
595
|
+
LOCALES[lang] = { ...LOCALES[lang], ...dict };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Resolve once `lang`'s dictionary is present: immediately for an inline
|
|
600
|
+
* locale, after one fetch for a runtime pack, never for an unknown one (the
|
|
601
|
+
* URL is the contract - the server 404s it). A failed fetch leaves the locale
|
|
602
|
+
* unresolved and $t falls back to the default language; the next navigation
|
|
603
|
+
* retries. This is the seam a bundled-per-locale app can bypass entirely by
|
|
604
|
+
* calling loadLocale() itself.
|
|
605
|
+
*/
|
|
606
|
+
export async function ensureLocale(lang: string): Promise<void> {
|
|
607
|
+
if (LOCALES[lang] || !LOCALE_PACKS.includes(lang)) return;
|
|
608
|
+
try {
|
|
609
|
+
const res = await fetch(`/locales/${encodeURIComponent(lang)}.json`);
|
|
610
|
+
if (res.ok) loadLocale(lang, await res.json());
|
|
611
|
+
} catch {
|
|
612
|
+
// offline, or the pack is missing: the inline dictionaries still render
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
export function localeList(): string[] {
|
|
617
|
+
return Object.keys(LOCALES);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
export function isLocale(lang: string): boolean {
|
|
621
|
+
// A pack counts as a known locale BEFORE it loads: the client router must
|
|
622
|
+
// not 404 /ar/about while /locales/ar.json is still in flight.
|
|
623
|
+
return Object.hasOwn(LOCALES, lang) || LOCALE_PACKS.includes(lang);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Best match for an Accept-Language header among the known locales, or null
|
|
628
|
+
* when it expresses no preference (absent, empty, or the `*` wildcard - which
|
|
629
|
+
* Node's own fetch sends by default). A caller negotiates only on a real
|
|
630
|
+
* preference; everything else serves the default locale's page in place.
|
|
631
|
+
*/
|
|
632
|
+
export function bestLocale(header: string | null | undefined): string | null {
|
|
633
|
+
for (const part of (header || '').split(',')) {
|
|
634
|
+
const tag = part.split(';')[0].trim().toLowerCase();
|
|
635
|
+
if (!tag || tag === '*') continue;
|
|
636
|
+
if (isLocale(tag)) return tag;
|
|
637
|
+
const base = tag.split('-')[0];
|
|
638
|
+
if (isLocale(base)) return base;
|
|
639
|
+
}
|
|
640
|
+
return null;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Reading direction of a locale. The set of right-to-left scripts is closed
|
|
645
|
+
* (Arabic, Hebrew and their relatives), so a base-tag test covers every
|
|
646
|
+
* language that uses them - no per-app config, and the document's <html dir>
|
|
647
|
+
* is server-rendered correct for no-JS visitors. A regex LITERAL, not a
|
|
648
|
+
* string .split(): esbuild drops side-effect-free initializers, so an app
|
|
649
|
+
* whose scripts never call localeDir ships neither it nor the table.
|
|
650
|
+
*/
|
|
651
|
+
const RTL_RE = /^(ar|fa|he|ur|ps|sd|ug|yi|ckb|dv|ks|prs|haz|mzn|nqo)/;
|
|
652
|
+
/** 'rtl' for a right-to-left locale, '' otherwise - '' is the html default. */
|
|
653
|
+
export function localeDir(lang: string): string {
|
|
654
|
+
return RTL_RE.test(lang) ? 'rtl' : '';
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// --- ICU MessageFormat, the subset real apps use --------------------- {count, plural, =0
|
|
658
|
+
// {No signatures yet} one {# item} other {# items}} {n, selectordinal …
|
|
659
|
+
const ICU_RE = /\{([\w$]+),\s*(plural|selectordinal|select),\s*((?:\s*[=\w]+\s*\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g;
|
|
660
|
+
const BRANCH_RE = /([=\w]+)\s*\{((?:[^{}]|\{[^{}]*\})*)\}/g;
|
|
661
|
+
|
|
662
|
+
/** The CLDR category of `n` in `locale`, or null where Intl has no answer. */
|
|
663
|
+
function pluralCategory(locale: string, ordinal: boolean, n: number): string | null {
|
|
664
|
+
try {
|
|
665
|
+
return new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined).select(n);
|
|
666
|
+
} catch {
|
|
667
|
+
return null; // no Intl.PluralRules, or an invalid tag: the English-ish fallback
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** Expand every ICU block of a message; leave the rest (and {name} holes) alone. */
|
|
672
|
+
function expandIcu(msg: string, vars: Record<string, string | number> | undefined, locale: string): string {
|
|
673
|
+
return msg.replace(ICU_RE, (whole, arg: string, kind: string, branchText: string) => {
|
|
674
|
+
const branches: Record<string, string> = {};
|
|
675
|
+
for (const m of branchText.matchAll(BRANCH_RE)) branches[m[1]] = m[2];
|
|
676
|
+
if (!branches.other) return whole; // no fallback arm: not valid ICU, render it verbatim
|
|
677
|
+
const v = vars?.[arg];
|
|
678
|
+
if (kind === 'select') return branches[typeof v === 'string' && branches[v] ? v : 'other'];
|
|
679
|
+
const num = typeof v === 'number' ? v : Number(v);
|
|
680
|
+
// An =N arm wins over the category; a value with no number in it has no category at
|
|
681
|
+
// all, so it takes the other arm - and # prints the value as given …
|
|
682
|
+
const cat = isFinite(num)
|
|
683
|
+
? (branches['=' + num] ? '=' + num : pluralCategory(locale, kind === 'selectordinal', num) ?? 'other')
|
|
684
|
+
: 'other';
|
|
685
|
+
return (branches[cat] ?? branches.other).replace(/#/g, String(v));
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Translate a key for the current language. The [lang] route param arrives
|
|
691
|
+
* as state before the render (the same seeding as any dynamic param), and
|
|
692
|
+
* reading it through the signal getter makes $t reactive: switching locale
|
|
693
|
+
* re-runs the marker, so only the translated nodes repaint.
|
|
694
|
+
*/
|
|
695
|
+
export function $t(key: string, vars?: Record<string, string | number>): string {
|
|
696
|
+
const [lang] = state('lang', DEFAULT_LOCALE);
|
|
697
|
+
const dict = LOCALES[lang()] ?? LOCALES[DEFAULT_LOCALE] ?? {};
|
|
698
|
+
const msg = dict[key];
|
|
699
|
+
let out = expandIcu(typeof msg === 'string' ? msg : key, vars, lang());
|
|
700
|
+
if (vars) for (const k in vars) out = out.split(`{${k}}`).join(String(vars[k]));
|
|
701
|
+
return out;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// --- the shared server store ---------------------------------------- Module scope
|
|
705
|
+
// (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds its
|
|
706
|
+
// own …
|
|
707
|
+
|
|
708
|
+
const STORES = new Map<string, { value: unknown }>();
|
|
709
|
+
let storeTransport: ((name: string, value: unknown) => void) | null = null;
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Install the cross-process transport. The generated server entry wires the
|
|
713
|
+
* cluster channel; a standalone process (dev, preview) installs none - one
|
|
714
|
+
* process is one copy, which is already correct. Pass null to detach.
|
|
715
|
+
*/
|
|
716
|
+
export function setStoreTransport(fn: ((name: string, value: unknown) => void) | null): void {
|
|
717
|
+
storeTransport = fn;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/** Apply a patch that arrived from another process (the transport's receiver
|
|
721
|
+
* calls this; a store nobody opened yet is ignored - it has no reader). */
|
|
722
|
+
export function applyStorePatch(name: string, value: unknown): void {
|
|
723
|
+
const entry = STORES.get(name);
|
|
724
|
+
if (entry) entry.value = value;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* A named store shared by every request in this process - and, through the
|
|
729
|
+
* transport, by every worker. Read it inside `$data` or a server action:
|
|
730
|
+
* those are the server-only paths. A bare read in a render body is a local
|
|
731
|
+
* snapshot, and on the client (where the store map is per page load and no
|
|
732
|
+
* patch ever arrives) that snapshot is the initial value.
|
|
733
|
+
*
|
|
734
|
+
* Values must be JSON-serializable: the transport serializes them, exactly
|
|
735
|
+
* like the state patch that already rides in every document.
|
|
736
|
+
*/
|
|
737
|
+
export function $store<T>(name: string, initial: T): { get(): T; set(v: T): void; update(fn: (v: T) => T): void } {
|
|
738
|
+
let entry = STORES.get(name);
|
|
739
|
+
if (!entry) {
|
|
740
|
+
entry = { value: initial };
|
|
741
|
+
STORES.set(name, entry);
|
|
742
|
+
}
|
|
743
|
+
const box = entry;
|
|
744
|
+
return {
|
|
745
|
+
get: () => box.value as T,
|
|
746
|
+
set: (v: T) => {
|
|
747
|
+
box.value = v;
|
|
748
|
+
storeTransport?.(name, v);
|
|
749
|
+
},
|
|
750
|
+
update: (fn: (v: T) => T) => {
|
|
751
|
+
box.value = fn(box.value as T);
|
|
752
|
+
storeTransport?.(name, box.value);
|
|
753
|
+
},
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// --- server action errors, guards and incremental patches -----------
|
|
758
|
+
//
|
|
759
|
+
// The action model's three gaps, closed with one request-scoped mechanism.
|
|
760
|
+
//
|
|
761
|
+
// 1. A standardized failure object. An action that cannot do its job (bad
|
|
762
|
+
// input, not signed in, a duplicate) throws ActionError; the dispatch
|
|
763
|
+
// catches it, seeds the page's state with it and re-renders, so the page
|
|
764
|
+
// answers with the failure VISIBLE (status = the error's code) instead of
|
|
765
|
+
// a 500 or a silent no-op. A bug still propagates to the 500 page.
|
|
766
|
+
// 2. A guard. `export async function beforeAction(name, form)` runs before
|
|
767
|
+
// every action of its page and vetoes with an ActionError - the
|
|
768
|
+
// action-level permission check (a redirect stays the middleware's job).
|
|
769
|
+
// 3. Incremental patches. A patch value may be an OPERATION ($append and
|
|
770
|
+
// friends) instead of a whole replacement, so growing a large list costs
|
|
771
|
+
// one row instead of a second copy of the list.
|
|
772
|
+
|
|
773
|
+
export class ActionError extends Error {
|
|
774
|
+
/** the HTTP status the response carries (400/401/403/409/422/...) */
|
|
775
|
+
code: number;
|
|
776
|
+
/** the form field the failure belongs to, when it belongs to one */
|
|
777
|
+
field?: string;
|
|
778
|
+
constructor(message: string, code = 400, field?: string) {
|
|
779
|
+
super(message);
|
|
780
|
+
this.name = 'ActionError';
|
|
781
|
+
this.code = code;
|
|
782
|
+
this.field = field;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** The JSON-safe shape the dispatch seeds into state (what `$actionError()` returns). */
|
|
787
|
+
export type ActionErrorInfo = { action: string; message: string; code: number; field?: string };
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* The failure of the action that produced the response being rendered, or
|
|
791
|
+
* null. It is ordinary state under the key `actionError`, so the client's
|
|
792
|
+
* resumeState() restores it and the post-adopt re-render sees exactly what
|
|
793
|
+
* the server saw - one read, both sides, no hydration payload.
|
|
794
|
+
*
|
|
795
|
+
* Read it as data (`{#if $actionError()}<p>{$actionError().message}</p>{/if}`)
|
|
796
|
+
* or let a {#boundary} contain it ($actionErrorOrThrow below).
|
|
797
|
+
*/
|
|
798
|
+
export function $actionError(): ActionErrorInfo | null {
|
|
799
|
+
const e = signalMap.get('actionError');
|
|
800
|
+
if (!e) return null;
|
|
801
|
+
if (currentEffect) e.subs.add(currentEffect); // subscribe like a state read
|
|
802
|
+
return (e.value as ActionErrorInfo | null) ?? null;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/**
|
|
806
|
+
* What a {#boundary} whose content depends on an action calls first: when the
|
|
807
|
+
* action that produced this response failed, throw - the boundary's own catch
|
|
808
|
+
* turns it into the fallback, so the section degrades to the error message
|
|
809
|
+
* instead of rendering a widget built on work that never happened.
|
|
810
|
+
*/
|
|
811
|
+
export function $actionErrorOrThrow(): void {
|
|
812
|
+
const info = $actionError();
|
|
813
|
+
if (info) throw new ActionError(info.message, info.code, info.field);
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/** The {#boundary} fallback: the action's own message when the failure is a business one. */
|
|
817
|
+
export function $boundaryFallback(err: unknown): string {
|
|
818
|
+
if (err instanceof ActionError) return `<p class="rosetack-action-error">${esc(err.message)}</p>`;
|
|
819
|
+
return '<p>This section failed to render.</p>';
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// An incremental patch: an action's return value may map a key to an OPERATION instead of a
|
|
823
|
+
// whole replacement value …
|
|
824
|
+
export type StateDeltaOp = 'append' | 'prepend' | 'merge';
|
|
825
|
+
|
|
826
|
+
export class StateDelta {
|
|
827
|
+
constructor(public op: StateDeltaOp, public value: unknown) {}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** Append (or prepend) items to a list-valued state key. */
|
|
831
|
+
export const $append = (value: unknown): StateDelta => new StateDelta('append', value);
|
|
832
|
+
export const $prepend = (value: unknown): StateDelta => new StateDelta('prepend', value);
|
|
833
|
+
/** Shallow-merge an object into an object-valued state key. */
|
|
834
|
+
export const $merge = (value: Record<string, unknown>): StateDelta => new StateDelta('merge', value);
|
|
835
|
+
|
|
836
|
+
const pendingDeltas = new Map<string, StateDelta>();
|
|
837
|
+
|
|
838
|
+
/** Record the deltas of the action that just ran (the dispatch calls this). */
|
|
839
|
+
export function setStateDelta(key: string, delta: StateDelta): void {
|
|
840
|
+
pendingDeltas.set(key, delta);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* Apply every pending delta to the live state and clear them. The generated
|
|
845
|
+
* render calls this once, right after its state declarations - and only the
|
|
846
|
+
* SSR side ever emits the call: a delta is recorded by a server dispatch, so
|
|
847
|
+
* on the client (post-adopt re-render, client-side navigation, refresh) the
|
|
848
|
+
* map is empty and this is a no-op. That is also why a delta can never apply
|
|
849
|
+
* twice: the value it produced is what the state script carried, and the
|
|
850
|
+
* client resumes THAT instead of recomputing it.
|
|
851
|
+
*/
|
|
852
|
+
export function applyStateDeltas(): void {
|
|
853
|
+
if (pendingDeltas.size === 0) return;
|
|
854
|
+
for (const [key, delta] of [...pendingDeltas]) {
|
|
855
|
+
pendingDeltas.delete(key);
|
|
856
|
+
applyStateDelta(key, delta);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** Apply one delta to the live state. */
|
|
861
|
+
export function applyStateDelta(key: string, delta: StateDelta): void {
|
|
862
|
+
const cur = signalMap.get(key)?.value;
|
|
863
|
+
if (delta.op === 'merge') {
|
|
864
|
+
setState(key, { ...(cur as Record<string, unknown> | undefined), ...(delta.value as Record<string, unknown>) });
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
const list = (v: unknown): unknown[] => (v == null ? [] : Array.isArray(v) ? v : [v]);
|
|
868
|
+
const merged =
|
|
869
|
+
delta.op === 'append' ? [...list(cur), ...list(delta.value)] : [...list(delta.value), ...list(cur)];
|
|
870
|
+
setState(key, merged);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// --- cookie helpers ------------------------------------------------- Sessions are the
|
|
874
|
+
// first thing every real app needs and the easiest thing to get subtly wrong …
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* Parse the cookies of a request (server) or of this document (client, where
|
|
878
|
+
* HttpOnly cookies are invisible by design - that is the point of HttpOnly).
|
|
879
|
+
*/
|
|
880
|
+
export function $cookies(request?: Request): Record<string, string> {
|
|
881
|
+
const raw = request
|
|
882
|
+
? request.headers.get('cookie')
|
|
883
|
+
: (typeof document !== 'undefined' ? document.cookie : '');
|
|
884
|
+
const out: Record<string, string> = {};
|
|
885
|
+
for (const part of (raw || '').split(';')) {
|
|
886
|
+
const eq = part.indexOf('=');
|
|
887
|
+
if (eq < 0) continue;
|
|
888
|
+
const k = part.slice(0, eq).trim();
|
|
889
|
+
if (k) out[k] = decodeURIComponent(part.slice(eq + 1).trim());
|
|
890
|
+
}
|
|
891
|
+
return out;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
* Build a Set-Cookie header VALUE for a session cookie with the safe
|
|
896
|
+
* defaults: HttpOnly, SameSite=Lax, Path=/, a 7-day Max-Age. `secure` is the
|
|
897
|
+
* one attribute a helper cannot infer (it depends on the deployment's TLS),
|
|
898
|
+
* so pass it when serving over https - and SameSite=None forces Secure,
|
|
899
|
+
* because every modern browser rejects that pairing otherwise.
|
|
900
|
+
*/
|
|
901
|
+
export function $sessionCookie(
|
|
902
|
+
name: string,
|
|
903
|
+
value: string,
|
|
904
|
+
opts: { path?: string; maxAge?: number; sameSite?: 'Strict' | 'Lax' | 'None'; secure?: boolean; httpOnly?: boolean } = {}
|
|
905
|
+
): string {
|
|
906
|
+
const { path = '/', maxAge = 60 * 60 * 24 * 7, sameSite = 'Lax', secure = false, httpOnly = true } = opts;
|
|
907
|
+
return [
|
|
908
|
+
`${name}=${encodeURIComponent(value)}`,
|
|
909
|
+
`Path=${path}`,
|
|
910
|
+
`Max-Age=${maxAge}`,
|
|
911
|
+
`SameSite=${sameSite}`,
|
|
912
|
+
httpOnly ? 'HttpOnly' : '',
|
|
913
|
+
secure || sameSite === 'None' ? 'Secure' : '',
|
|
914
|
+
].filter(Boolean).join('; ');
|
|
915
|
+
}
|