rosetack 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/k8s/rosetack.yaml +107 -0
  4. package/deploy/netlify/functions/rosetack.ts +38 -0
  5. package/deploy/netlify.toml +17 -0
  6. package/devtools/devtools.html +7 -0
  7. package/devtools/devtools.js +1 -0
  8. package/devtools/manifest.json +8 -0
  9. package/devtools/panel.html +28 -0
  10. package/devtools/panel.js +54 -0
  11. package/dist-cli/compiler.mjs +1346 -492
  12. package/dist-cli/edge.mjs +152 -41
  13. package/dist-cli/rosetack.mjs +1974 -606
  14. package/dist-cli/runtime.mjs +205 -40
  15. package/dist-cli/test.mjs +1425 -508
  16. package/package.json +4 -3
  17. package/src/FRAMEWORK_VERSION +1 -1
  18. package/src/cli/edge.ts +76 -61
  19. package/src/cli/index.ts +516 -293
  20. package/src/cli/prompt.ts +130 -0
  21. package/src/cli/shell.ts +113 -65
  22. package/src/cli/test.ts +9 -70
  23. package/src/compiler/errors.ts +74 -0
  24. package/src/compiler/index.ts +1514 -839
  25. package/src/runtime/index.ts +255 -150
  26. package/src/types/rosetack.d.ts +18 -59
  27. package/templates/admin/package.json +14 -0
  28. package/templates/admin/rosetack.config.js +1 -0
  29. package/templates/admin/src/pages/_middleware.rose +33 -0
  30. package/templates/admin/src/pages/api/items.rose +37 -0
  31. package/templates/admin/src/pages/api/login.rose +25 -0
  32. package/templates/admin/src/pages/index.rose +79 -0
  33. package/templates/api/package.json +14 -0
  34. package/templates/api/rosetack.config.js +1 -0
  35. package/templates/api/src/pages/api/health.rose +7 -0
  36. package/templates/api/src/pages/api/items.rose +46 -0
  37. package/templates/api/src/pages/api/login.rose +24 -0
  38. package/templates/api/src/pages/index.rose +25 -0
  39. package/templates/blog/package.json +14 -0
  40. package/templates/blog/rosetack.config.js +1 -0
  41. package/templates/blog/src/pages/404.rose +2 -0
  42. package/templates/blog/src/pages/_layout.rose +42 -0
  43. package/templates/blog/src/pages/_middleware.rose +74 -0
  44. package/templates/blog/src/pages/admin.rose +85 -0
  45. package/templates/blog/src/pages/api/login.rose +46 -0
  46. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  47. package/templates/blog/src/pages/api/posts.rose +72 -0
  48. package/templates/blog/src/pages/index.rose +31 -0
  49. package/templates/blog/src/pages/post/[id].rose +36 -0
  50. package/templates/site/package.json +14 -0
  51. package/templates/site/rosetack.config.js +1 -0
  52. package/templates/site/src/pages/404.rose +2 -0
  53. package/templates/site/src/pages/_layout.rose +40 -0
  54. package/templates/site/src/pages/about.rose +6 -0
  55. package/templates/site/src/pages/index.rose +13 -0
  56. package/templates/site/src/pages/pricing.rose +8 -0
@@ -1,9 +1,4 @@
1
- /**
2
- * rosetack Runtime - Zero-hydration, compile-time reactivity
3
- * Target: < 2KB gzipped
4
- */
5
-
6
- // === Reactive Primitives ===
1
+ // rosetack Runtime - Zero-hydration, compile-time reactivity Target: < 2KB gzipped
7
2
 
8
3
  type Subscriber = () => void;
9
4
  type Cleanup = () => void;
@@ -11,12 +6,10 @@ type SignalEntry = { value: unknown; subs: Set<Subscriber> };
11
6
 
12
7
  let currentEffect: (() => void) | null = null;
13
8
 
14
- // Trade-off: global signal map, shared across all inlined modules
15
9
  let signalMap: Map<string, SignalEntry> =
16
10
  (globalThis as any).__rosetack_signalMap ?? new Map();
17
11
  (globalThis as any).__rosetack_signalMap = signalMap;
18
12
 
19
- // One get-or-create helper shared by state / setState / resumeState.
20
13
  function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subscriber> } {
21
14
  const e = signalMap.get(key) ?? { value: initial, subs: new Set<Subscriber>() };
22
15
  signalMap.set(key, e);
@@ -24,6 +17,7 @@ function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subsc
24
17
  }
25
18
 
26
19
  export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
20
+ ownerKeys()?.add(key);
27
21
  const e = entry(key, initial);
28
22
 
29
23
  const getter = () => {
@@ -49,16 +43,51 @@ export function setState<T>(key: string, value: T): void {
49
43
  e.subs.forEach((fn: Subscriber) => fn());
50
44
  }
51
45
 
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
46
  const cleanups = new Set<Cleanup>();
55
47
 
48
+ let fxOwner: object | null = null;
49
+ const fxByOwner = new WeakMap<object, Set<Cleanup>>();
50
+ const keysByOwner = new WeakMap<object, Set<string>>();
51
+ const fxSet = (): Set<Cleanup> => {
52
+ if (!fxOwner) return cleanups;
53
+ let s = fxByOwner.get(fxOwner);
54
+ if (!s) { s = new Set(); fxByOwner.set(fxOwner, s); }
55
+ return s;
56
+ };
57
+ const ownerKeys = (): Set<string> | null => {
58
+ if (!fxOwner) return null;
59
+ let s = keysByOwner.get(fxOwner);
60
+ if (!s) { s = new Set(); keysByOwner.set(fxOwner, s); }
61
+ return s;
62
+ };
63
+
64
+ // Attribute everything the current render creates to `container` (null = the document's global bookkeeping).
65
+ export function setFxOwner(container: object | null): void {
66
+ fxOwner = container;
67
+ }
68
+
69
+ // Dispose everything ONE container created - its effects, its onCleanups, the state keys its render seeded.
70
+ export function resetContainerFx(container: object): void {
71
+ const set = fxByOwner.get(container);
72
+ if (set) {
73
+ set.forEach((fn: Cleanup) => fn());
74
+ fxByOwner.delete(container);
75
+ }
76
+ const keys = keysByOwner.get(container);
77
+ if (keys) {
78
+ keys.forEach((k: string) => signalMap.delete(k));
79
+ keysByOwner.delete(container);
80
+ }
81
+ dataCache.clear();
82
+ pendingDeltas.clear();
83
+ }
84
+
56
85
  export function effect(fn: () => void): Cleanup {
57
86
  const wrapped: Subscriber = () => {
58
87
  try {
59
88
  fn();
60
89
  } catch {
61
- // subscriber may be stale; ignore
90
+
62
91
  }
63
92
  };
64
93
  const prev = currentEffect;
@@ -67,14 +96,12 @@ export function effect(fn: () => void): Cleanup {
67
96
  currentEffect = prev;
68
97
  const cleanup: Cleanup = () => {
69
98
  signalMap.forEach((e: { subs: Set<Subscriber> }) => e.subs.delete(wrapped));
70
- cleanups.delete(cleanup);
99
+ fxSet().delete(cleanup);
71
100
  };
72
- cleanups.add(cleanup);
101
+ fxSet().add(cleanup);
73
102
  return cleanup;
74
103
  }
75
104
 
76
- // === HTML escaping (server-side interpolation safety) ===
77
-
78
105
  const ESC_MAP: Record<string, string> = {
79
106
  '&': '&amp;',
80
107
  '<': '&lt;',
@@ -87,19 +114,16 @@ export function esc(v: unknown): string {
87
114
  return String(v).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
88
115
  }
89
116
 
90
- // === Generated-code marker helpers === Every reactive marker in every generated module is
91
- // emitted through these five functions …
92
-
93
117
  type Close = (s?: unknown) => unknown;
94
118
 
95
119
  export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unknown): string {
96
120
  const i = closes.push(fn) - 1;
97
- return `<!--\u27e6m:${i}\u27e7-->` + esc(closes[i](arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
121
+ return `<!--\u27e6m:${i}\u27e7-->` + esc(fn(arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
98
122
  }
99
123
 
100
124
  export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
101
125
  const i = closes.push(fn) - 1;
102
- return `${name}="${esc(closes[i](arg))}" data-b="${i}:${name}"`;
126
+ return `${name}="${esc(fn(arg))}" data-b="${i}:${name}"`;
103
127
  }
104
128
 
105
129
  export function ifMark(
@@ -108,28 +132,25 @@ export function ifMark(
108
132
  fn: (s: unknown, c: Close[]) => unknown,
109
133
  scope?: unknown
110
134
  ): 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
135
  let snap: { html: string; closes: Close[] } | null = null;
115
- closes.push(() => {
116
- if (!cond()) return null;
136
+ const i = closes.push(() => {
137
+ if (!cond()) {
138
+ snap = null;
139
+ return null;
140
+ }
117
141
  if (!snap) {
118
- const c: Close[] = [];
119
- snap = { html: String(fn(scope, c)), closes: c };
142
+ snap = { html: String(fn(scope, closes)), closes };
120
143
  }
121
144
  return snap;
122
- });
145
+ }) - 1;
123
146
  const r = closes[i]() as { html: string } | null;
124
147
  return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
125
148
  }
126
149
 
127
150
  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
- }));
151
+ const i = closes.push(() => (items() as unknown[]).map((v) => {
152
+ return { html: String(fn(v, closes)), closes, scope: v };
153
+ })) - 1;
133
154
  let h = `<!--\u27e6l:${i}\u27e7-->`;
134
155
  for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
135
156
  return h + `<!--\u27e6/l:${i}\u27e7-->`;
@@ -140,15 +161,54 @@ export function headMark(closes: Close[], fn: Close): string {
140
161
  return `<!--\u27e6h:${i}\u27e7-->` + fn() + `<!--\u27e6/h:${i}\u27e7-->`;
141
162
  }
142
163
 
143
- // === Reactive DOM wiring (client) ===
164
+ /**
165
+ * P1-2 (bug report): TRUSTED HTML - the explicit reverse of esc(). `{@html x}`
166
+ * emits the value verbatim, so a CMS's rich text renders as markup instead of
167
+ * as escaped source.
168
+ *
169
+ * The markers are an {#if} block's on purpose: wire() already knows how to
170
+ * adopt the server's nodes in place (identity preserved - an embedded iframe
171
+ * does not reload) and to swap the range for a fresh parse when the value
172
+ * changes. Reusing that machinery costs this function and nothing else: no
173
+ * new marker kind, no new wire branch, no bytes in a document that never
174
+ * uses it. The close returns the same {html, closes} shape an {#if} block
175
+ * does, with the RENDER's array - trusted html is usually opaque markup
176
+ * with no markers inside, but when a loader's value was itself rendered
177
+ * inside this same pass (a theme skin built from another composable) the
178
+ * markers it carries belong to this array, and a nested wire() pass must be
179
+ * able to resolve them. `arg` is the enclosing block's scope value, exactly
180
+ * as textMark takes it: a `{@html row.body}` inside an {#each} resolves
181
+ * against the row.
182
+ */
183
+ export function rawMark(closes: Close[], fn: Close, arg?: unknown): string {
184
+ const i = closes.push((s?: unknown) => ({ html: String((fn as (a?: unknown) => unknown)(s) ?? ''), closes })) - 1;
185
+ const r = closes[i](arg) as { html: string };
186
+ return `<!--\u27e6i:${i}\u27e7-->` + r.html + `<!--\u27e6/i:${i}\u27e7-->`;
187
+ }
188
+
189
+ /**
190
+ * A named slot's block. The child rendered its slot content into the
191
+ * render's shared array scoped to the slot object; the block wraps it in
192
+ * markers from the SAME index space, so the ids stay unique across the whole
193
+ * composition (a plain <slot/> inlines the children html directly and needs
194
+ * none of this). Lives here rather than in the compiler's emitted helper
195
+ * string so the array is the one the rest of the render uses.
196
+ */
197
+ export function slotBlockMark(
198
+ closes: Close[],
199
+ hit: { o: Record<string, unknown>; fn: (o: unknown, c: Close[]) => unknown } | null
200
+ ): string {
201
+ if (!hit) return '';
202
+ const i = closes.push(() => {
203
+ if (!hit) return null;
204
+ return { html: String(hit.fn(hit.o, closes)), closes, scope: hit.o };
205
+ }) - 1;
206
+ return `<!--\u27e6i:${i}\u27e7-->` + String(hit.fn(hit.o, closes)) + `<!--\u27e6/i:${i}\u27e7-->`;
207
+ }
144
208
 
145
209
  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
210
  const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
149
211
 
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
212
  const wired = new WeakSet<Node>();
153
213
 
154
214
  /** Parse an html string into a DocumentFragment. */
@@ -158,14 +218,8 @@ export function tpl(html: string): DocumentFragment {
158
218
  return t.content;
159
219
  }
160
220
 
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
221
  const HEAD_ATTR = 'data-rosetack-head';
166
222
 
167
- // The delegated-event handler registry: every compiled module registers its handlers here
168
- // (Object.assign(handlers, { ...
169
223
  export const handlers: Record<string, (e: Event) => void> =
170
224
  (globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
171
225
 
@@ -183,11 +237,10 @@ export const handlers: Record<string, (e: Event) => void> =
183
237
  */
184
238
  export function applyHead(html: string): void {
185
239
  const seen = new Set<string>();
240
+ const positional = new Map<string, number>();
186
241
  const frag = tpl(html);
187
242
  const title = frag.querySelector('title');
188
243
  if (title) {
189
- // Manage the title element directly: the document.title setter would update the FIRST
190
- // title element in tree order …
191
244
  let cur = document.head.querySelector('title');
192
245
  if (!cur) {
193
246
  cur = document.createElement('title');
@@ -198,13 +251,20 @@ export function applyHead(html: string): void {
198
251
  for (const el of Array.from(document.head.querySelectorAll(`[${HEAD_ATTR}]`))) el.remove();
199
252
  for (const el of Array.from(frag.children)) {
200
253
  if (el.tagName === 'TITLE') continue;
201
- const key = el.getAttribute('name')
254
+ const tag = el.tagName.toLowerCase();
255
+ const identity = el.getAttribute('name')
202
256
  ?? el.getAttribute('property')
203
257
  ?? el.getAttribute('rel')
204
258
  ?? 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
259
+ let managed: string;
260
+ if (identity) managed = `${tag}:${identity}`;
261
+ else if (el.id) managed = `${tag}:${el.id}`;
262
+ else {
263
+ const n = positional.get(tag) ?? 0;
264
+ positional.set(tag, n + 1);
265
+ managed = `${tag}:#${n}`;
266
+ }
267
+ if (seen.has(managed)) continue;
208
268
  seen.add(managed);
209
269
  el.setAttribute(HEAD_ATTR, managed);
210
270
  document.head.appendChild(el);
@@ -224,7 +284,6 @@ export function clearHead(): void {
224
284
  export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Cleanup {
225
285
  let holder: Node = root;
226
286
  if (root.nodeType === 11) {
227
- // DocumentFragment: wrap so querySelectorAll sees the root element too
228
287
  const div = document.createElement('div');
229
288
  div.appendChild(root);
230
289
  holder = div;
@@ -237,20 +296,33 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
237
296
  const walker = document.createTreeWalker(holder, NodeFilter.SHOW_COMMENT);
238
297
  while (walker.nextNode()) comments.push(walker.currentNode as Comment);
239
298
 
240
- // Comments that live INSIDE an {#if}/{#each}/slot block belong to that block's OWN wire
241
- // pass …
242
299
  const nested = new Set<Comment>();
300
+ const headPair = new Set<Comment>();
301
+ const open: number[] = [];
243
302
  for (let i = 0; i < comments.length; i++) {
244
303
  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
- }
304
+ if (m && (m[1] === 'i' || m[1] === 'l' || m[1] === 'h')) {
305
+ open.push(i);
306
+ continue;
307
+ }
308
+ const em = (comments[i].nodeValue ?? '').match(END_RE);
309
+ if (!em) continue;
310
+ const key = em[1] + em[2];
311
+ let at = -1;
312
+ for (let k = open.length - 1; k >= 0; k--) {
313
+ const om = (comments[open[k]].nodeValue ?? '').match(MARK_RE)!;
314
+ if (om[1] + om[2] === key) { at = k; break; }
315
+ }
316
+ if (at < 0) continue;
317
+ const om = (comments[open[at]].nodeValue ?? '').match(MARK_RE)!;
318
+ if (om[1] === 'h') {
319
+ headPair.add(comments[open[at]]);
320
+ headPair.add(comments[i]);
252
321
  }
322
+ for (let k = open[at] + 1; k < i; k++) nested.add(comments[k]);
323
+ open.length = at;
253
324
  }
325
+ for (const c of headPair) nested.delete(c);
254
326
 
255
327
  const ends = new Map<number, Comment>();
256
328
  for (const c of comments) {
@@ -259,21 +331,21 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
259
331
  if (m) ends.set(+m[2], c);
260
332
  }
261
333
 
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
334
  const headBlocks: Array<{ idx: number; start: Comment; end: Comment; nodes: ChildNode[] }> = [];
265
335
 
336
+ const ownsHead = root === document.getElementById('app');
337
+
266
338
  for (const c of comments) {
267
339
  if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
268
- wired.add(c);
269
340
  const m = (c.nodeValue ?? '').match(MARK_RE);
270
341
  if (!m) continue;
271
342
  const kind = m[1];
272
343
  const idx = +m[2];
273
344
 
345
+ if (kind === 'h' && !ownsHead) continue;
346
+ wired.add(c);
347
+
274
348
  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
349
  const end = ends.get(idx);
278
350
  if (!end) continue;
279
351
  const nodes: ChildNode[] = [];
@@ -285,8 +357,6 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
285
357
  }
286
358
  headBlocks.push({ idx, start: c, end, nodes });
287
359
  } 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
360
  let target = c.nextSibling;
291
361
  if (!target || target.nodeType !== 3) {
292
362
  target = document.createTextNode('');
@@ -306,8 +376,6 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
306
376
  tn.nodeValue = String((closes[idx] as (s?: unknown) => unknown)(scope));
307
377
  });
308
378
  } 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
379
  const anchor = c;
312
380
  const end = ends.get(idx);
313
381
  if (!end) continue;
@@ -319,9 +387,10 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
319
387
  st.__st = undefined;
320
388
  }
321
389
  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.
390
+ if (!r) {
391
+ st.__ever = true;
392
+ return;
393
+ }
325
394
  let frag: DocumentFragment;
326
395
  if (st.__ever) {
327
396
  frag = tpl(r.html);
@@ -335,16 +404,13 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
335
404
  n = nx;
336
405
  }
337
406
  }
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
407
  const disp = wire(frag, r.closes, (r as { scope?: unknown }).scope ?? scope);
341
408
  const nodes = Array.from(frag.childNodes);
342
409
  const parent = anchor.parentNode!;
343
- for (const nd of nodes) parent.insertBefore(nd, anchor.nextSibling);
410
+ for (const nd of nodes) parent.insertBefore(nd, end);
344
411
  st.__st = { nodes, disp };
345
412
  });
346
413
  } else {
347
- // List: rebuild items between the start and end anchors
348
414
  const start = c;
349
415
  const end = ends.get(idx);
350
416
  if (!end) continue;
@@ -373,24 +439,22 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
373
439
  }
374
440
  }
375
441
 
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();
442
+ if (root === document.getElementById('app')) {
443
+ if (headBlocks.length > 0) {
444
+ const blocks = headBlocks;
445
+ weff(() => {
446
+ let html = '';
447
+ for (const b of blocks) html += String((closes[b.idx] as (s?: unknown) => unknown)(scope));
448
+ applyHead(html);
449
+ });
450
+ for (const b of blocks) {
451
+ b.nodes.forEach((nd) => nd.remove());
452
+ b.start.remove();
453
+ b.end.remove();
454
+ }
455
+ } else if (root.nodeType !== 11) clearHead();
456
+ }
392
457
 
393
- // Attributes: data-b="K:attrName"
394
458
  const els = (holder as Element).querySelectorAll('[data-b]');
395
459
  els.forEach((el) => {
396
460
  const spec = el.getAttribute('data-b')!;
@@ -415,10 +479,6 @@ export function resetEffects(): void {
415
479
  cleanups.clear();
416
480
  }
417
481
 
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
482
  let dataCache = new Map<string, Promise<unknown>>();
423
483
 
424
484
  export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
@@ -431,16 +491,33 @@ export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
431
491
  return p as Promise<T>;
432
492
  }
433
493
 
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
494
  export function clearRequestState(): void {
437
495
  signalMap.clear();
438
496
  dataCache.clear();
439
497
  pendingDeltas.clear();
440
498
  }
441
499
 
442
- // === Request context === A per-request bag: pages/_middleware.rose fills it
443
- // (getContext().user = ...) and $data, server actions and api handlers read it.
500
+ let requestQuery: Record<string, string> = {};
501
+ let prefetchOverride: Record<string, string> | null = null;
502
+
503
+ export function $query(): Record<string, string> {
504
+ if (prefetchOverride) return prefetchOverride;
505
+ if (typeof location === 'undefined') return requestQuery;
506
+ const q: Record<string, string> = {};
507
+ new URLSearchParams(location.search).forEach((v, k) => { q[k] = v; });
508
+ return q;
509
+ }
510
+
511
+ /** The per-request query object - the servers call this before every render. */
512
+ export function setRequestQuery(q: Record<string, string>): void {
513
+ requestQuery = q;
514
+ }
515
+
516
+ /** The query of the route a prefetch is rendering, or null outside one. */
517
+ export function setPrefetchOverride(q: Record<string, string> | null): void {
518
+ prefetchOverride = q;
519
+ }
520
+
444
521
  let requestContext: Record<string, unknown> = {};
445
522
 
446
523
  export function getContext(): Record<string, unknown> {
@@ -474,7 +551,7 @@ export async function isolateStateAsync<T>(
474
551
  ): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
475
552
  const savedSignals = signalMap;
476
553
  const savedData = dataCache;
477
- const savedDeltas = new Map(pendingDeltas); // a prefetch render must not consume a delta
554
+ const savedDeltas = new Map(pendingDeltas);
478
555
  pendingDeltas.clear();
479
556
  const savedMounts = mountQueue.splice(0, mountQueue.length);
480
557
  const savedCleanups = new Set(cleanups);
@@ -493,8 +570,8 @@ export async function isolateStateAsync<T>(
493
570
  signalMap = savedSignals;
494
571
  dataCache = savedData;
495
572
  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
573
+ savedDeltas.forEach((d, k) => pendingDeltas.set(k, d));
574
+ mountQueue.splice(0, 0, ...savedMounts);
498
575
  cleanups.clear();
499
576
  savedCleanups.forEach((fn: Cleanup) => cleanups.add(fn));
500
577
  }
@@ -506,8 +583,6 @@ export function restoreState(entries: Map<string, SignalEntry>): void {
506
583
  entries.forEach((e: SignalEntry, k: string) => signalMap.set(k, e));
507
584
  }
508
585
 
509
- // === Serialization (for zero-hydration resume) ===
510
-
511
586
  export function serializeState(): string {
512
587
  const obj: Record<string, unknown> = {};
513
588
  signalMap.forEach((v: { value: unknown }, k: string) => (obj[k] = v.value));
@@ -525,8 +600,6 @@ export function resumeState(json: string): void {
525
600
  }
526
601
  }
527
602
 
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
603
  let refreshHook: (() => Promise<void>) | null = null;
531
604
 
532
605
  export function setRefreshHook(fn: () => Promise<void>): void {
@@ -537,12 +610,10 @@ export function refresh(): Promise<void> {
537
610
  return refreshHook ? refreshHook() : Promise.resolve();
538
611
  }
539
612
 
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
613
  const mountQueue: Array<() => void> = [];
543
614
 
544
615
  export function onMount(fn: () => void): void {
545
- if (typeof document === 'undefined') return; // server render: nothing mounts
616
+ if (typeof document === 'undefined') return;
546
617
  mountQueue.push(fn);
547
618
  }
548
619
 
@@ -559,7 +630,7 @@ export function flushMounts(): void {
559
630
 
560
631
  /** Register a disposer for the current render (the effects' cleanup channel). */
561
632
  export function onCleanup(fn: Cleanup): void {
562
- cleanups.add(fn);
633
+ fxSet().add(fn);
563
634
  }
564
635
 
565
636
  /**
@@ -572,12 +643,8 @@ export function adoptCleanups(fns: Iterable<Cleanup>): void {
572
643
  for (const fn of fns) cleanups.add(fn);
573
644
  }
574
645
 
575
- // === i18n: localized routes === Every JSON file in src/locales/ is a language: { "key":
576
- // "string" }.
577
646
  let LOCALES: Record<string, Record<string, string>> = {};
578
647
  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
648
  let LOCALE_PACKS: string[] = [];
582
649
 
583
650
  export function setLocales(dicts: Record<string, Record<string, string>>, def: string): void {
@@ -618,8 +685,6 @@ export function localeList(): string[] {
618
685
  }
619
686
 
620
687
  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
688
  return Object.hasOwn(LOCALES, lang) || LOCALE_PACKS.includes(lang);
624
689
  }
625
690
 
@@ -640,6 +705,42 @@ export function bestLocale(header: string | null | undefined): string | null {
640
705
  return null;
641
706
  }
642
707
 
708
+ /** The signal `redirect()` throws. */
709
+ export class RoseRedirect extends Error {
710
+ readonly __rosetack = 'redirect';
711
+ constructor(readonly path: string, readonly status = 307) {
712
+ super(`redirect to ${path}`);
713
+ }
714
+ }
715
+
716
+ /** The signal `notFound()` throws. */
717
+ export class RoseNotFound extends Error {
718
+ readonly __rosetack = 'notFound';
719
+ constructor() {
720
+ super('notFound()');
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Send the visitor somewhere else: the response becomes a 30x with this
726
+ * Location. Call it from a page's `$data` body (a wall, a renamed slug, a
727
+ * canonical URL) or from an api handler. A route that calls it is buffered by
728
+ * the compiler, so the status can still be set.
729
+ */
730
+ export function redirect(path: string, status = 307): never {
731
+ throw new RoseRedirect(path, status);
732
+ }
733
+
734
+ /**
735
+ * Answer 404 with the app's own 404 route (pages/404.rose) instead of the
736
+ * built-in page. Call it from a page's `$data` body when the slug resolves to
737
+ * nothing - the status is a real 404 and the body is the app's design, which
738
+ * is the one thing a middleware wall cannot do from outside the render.
739
+ */
740
+ export function notFound(): never {
741
+ throw new RoseNotFound();
742
+ }
743
+
643
744
  /**
644
745
  * Reading direction of a locale. The set of right-to-left scripts is closed
645
746
  * (Arabic, Hebrew and their relatives), so a base-tag test covers every
@@ -654,8 +755,6 @@ export function localeDir(lang: string): string {
654
755
  return RTL_RE.test(lang) ? 'rtl' : '';
655
756
  }
656
757
 
657
- // --- ICU MessageFormat, the subset real apps use --------------------- {count, plural, =0
658
- // {No signatures yet} one {# item} other {# items}} {n, selectordinal …
659
758
  const ICU_RE = /\{([\w$]+),\s*(plural|selectordinal|select),\s*((?:\s*[=\w]+\s*\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g;
660
759
  const BRANCH_RE = /([=\w]+)\s*\{((?:[^{}]|\{[^{}]*\})*)\}/g;
661
760
 
@@ -664,7 +763,7 @@ function pluralCategory(locale: string, ordinal: boolean, n: number): string | n
664
763
  try {
665
764
  return new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined).select(n);
666
765
  } catch {
667
- return null; // no Intl.PluralRules, or an invalid tag: the English-ish fallback
766
+ return null;
668
767
  }
669
768
  }
670
769
 
@@ -673,12 +772,10 @@ function expandIcu(msg: string, vars: Record<string, string | number> | undefine
673
772
  return msg.replace(ICU_RE, (whole, arg: string, kind: string, branchText: string) => {
674
773
  const branches: Record<string, string> = {};
675
774
  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
775
+ if (!branches.other) return whole;
677
776
  const v = vars?.[arg];
678
777
  if (kind === 'select') return branches[typeof v === 'string' && branches[v] ? v : 'other'];
679
778
  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
779
  const cat = isFinite(num)
683
780
  ? (branches['=' + num] ? '=' + num : pluralCategory(locale, kind === 'selectordinal', num) ?? 'other')
684
781
  : 'other';
@@ -701,10 +798,6 @@ export function $t(key: string, vars?: Record<string, string | number>): string
701
798
  return out;
702
799
  }
703
800
 
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
801
  const STORES = new Map<string, { value: unknown }>();
709
802
  let storeTransport: ((name: string, value: unknown) => void) | null = null;
710
803
 
@@ -754,22 +847,6 @@ export function $store<T>(name: string, initial: T): { get(): T; set(v: T): void
754
847
  };
755
848
  }
756
849
 
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
850
  export class ActionError extends Error {
774
851
  /** the HTTP status the response carries (400/401/403/409/422/...) */
775
852
  code: number;
@@ -798,7 +875,7 @@ export type ActionErrorInfo = { action: string; message: string; code: number; f
798
875
  export function $actionError(): ActionErrorInfo | null {
799
876
  const e = signalMap.get('actionError');
800
877
  if (!e) return null;
801
- if (currentEffect) e.subs.add(currentEffect); // subscribe like a state read
878
+ if (currentEffect) e.subs.add(currentEffect);
802
879
  return (e.value as ActionErrorInfo | null) ?? null;
803
880
  }
804
881
 
@@ -819,8 +896,6 @@ export function $boundaryFallback(err: unknown): string {
819
896
  return '<p>This section failed to render.</p>';
820
897
  }
821
898
 
822
- // An incremental patch: an action's return value may map a key to an OPERATION instead of a
823
- // whole replacement value …
824
899
  export type StateDeltaOp = 'append' | 'prepend' | 'merge';
825
900
 
826
901
  export class StateDelta {
@@ -870,9 +945,6 @@ export function applyStateDelta(key: string, delta: StateDelta): void {
870
945
  setState(key, merged);
871
946
  }
872
947
 
873
- // --- cookie helpers ------------------------------------------------- Sessions are the
874
- // first thing every real app needs and the easiest thing to get subtly wrong …
875
-
876
948
  /**
877
949
  * Parse the cookies of a request (server) or of this document (client, where
878
950
  * HttpOnly cookies are invisible by design - that is the point of HttpOnly).
@@ -913,3 +985,36 @@ export function $sessionCookie(
913
985
  secure || sameSite === 'None' ? 'Secure' : '',
914
986
  ].filter(Boolean).join('; ');
915
987
  }
988
+
989
+ export function reportVitals(): void {
990
+ if (typeof window === 'undefined' || typeof performance === 'undefined') return;
991
+ const live: Record<string, number> = {};
992
+ (window as unknown as { __rosetack_vitals?: Record<string, number> }).__rosetack_vitals = live;
993
+ const send = (name: string, value: number) => {
994
+ live[name] = value;
995
+ window.dispatchEvent(new CustomEvent('rosetack:vitals', { detail: { name, value, route: location.pathname } }));
996
+ };
997
+ const nav = performance.getEntriesByType?.('navigation')?.[0] as PerformanceNavigationTiming | undefined;
998
+ if (nav) send('ttfb', Math.round(nav.responseStart));
999
+ const paints = performance.getEntriesByType?.('paint') ?? [];
1000
+ const fcp = paints.find((p) => p.name === 'first-contentful-paint');
1001
+ if (fcp) send('fcp', Math.round(fcp.startTime));
1002
+ const PO = (window as unknown as { PerformanceObserver?: typeof PerformanceObserver }).PerformanceObserver;
1003
+ if (!PO) return;
1004
+ let cls = 0;
1005
+ let inp = 0;
1006
+ const flush = () => {
1007
+ if (cls) send('cls', Math.round(cls * 1000) / 1000);
1008
+ if (inp) send('inp', Math.round(inp));
1009
+ };
1010
+ document.addEventListener('visibilitychange', () => {
1011
+ if (document.visibilityState === 'hidden') flush();
1012
+ });
1013
+ new PO((list) => {
1014
+ for (const e of list.getEntries() as Array<PerformanceEntry & { value?: number; duration?: number; interactionId?: number }>) {
1015
+ if (e.entryType === 'layout-shift' && !(e as unknown as { hadRecentInput?: boolean }).hadRecentInput) cls += e.value ?? 0;
1016
+ if (e.entryType === 'event' && e.interactionId) inp = Math.max(inp, e.duration ?? 0);
1017
+ if (e.entryType === 'largest-contentful-paint') send('lcp', Math.round(e.startTime));
1018
+ }
1019
+ }).observe({ entryTypes: ['layout-shift', 'event', 'largest-contentful-paint'] });
1020
+ }