rosetack 0.1.0 → 0.1.2

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 (52) hide show
  1. package/deploy/k8s/rosetack.yaml +107 -0
  2. package/dist-cli/compiler.mjs +2783 -0
  3. package/dist-cli/edge.mjs +332 -0
  4. package/dist-cli/rosetack.mjs +4230 -0
  5. package/dist-cli/runtime.mjs +703 -0
  6. package/dist-cli/test.mjs +3202 -0
  7. package/pack.mjs +49 -0
  8. package/package.json +25 -7
  9. package/src/FRAMEWORK_VERSION +1 -1
  10. package/src/cli/edge.ts +67 -25
  11. package/src/cli/index.ts +858 -94
  12. package/src/cli/prompt.ts +127 -0
  13. package/src/cli/shell.ts +133 -30
  14. package/src/cli/test.ts +400 -0
  15. package/src/compiler/errors.ts +74 -0
  16. package/src/compiler/index.ts +1955 -264
  17. package/src/runtime/index.ts +465 -66
  18. package/src/types/rosetack.d.ts +151 -0
  19. package/.github/workflows/ci.yml +0 -72
  20. package/.github/workflows/release.yml +0 -122
  21. package/benchmark.ts +0 -227
  22. package/example/public/favicon.ico +0 -0
  23. package/example/public/logo.svg +0 -148
  24. package/example/public/rose-mark-black.png +0 -0
  25. package/example/public/rose-mark.png +0 -0
  26. package/example/public/rose-mono.png +0 -0
  27. package/example/rosetack.config.js +0 -10
  28. package/example/src/locales/en.json +0 -8
  29. package/example/src/locales/zh.json +0 -8
  30. package/example/src/pages/404.rose +0 -15
  31. package/example/src/pages/500.rose +0 -10
  32. package/example/src/pages/[lang]/about.rose +0 -40
  33. package/example/src/pages/_layout.rose +0 -33
  34. package/example/src/pages/_middleware.rose +0 -37
  35. package/example/src/pages/about.rose +0 -67
  36. package/example/src/pages/admin.rose +0 -27
  37. package/example/src/pages/api/hello.rose +0 -19
  38. package/example/src/pages/api/login.rose +0 -55
  39. package/example/src/pages/api/posts.rose +0 -80
  40. package/example/src/pages/api/secret.rose +0 -14
  41. package/example/src/pages/blog/[id].rose +0 -25
  42. package/example/src/pages/broken.rose +0 -16
  43. package/example/src/pages/fresh.rose +0 -22
  44. package/example/src/pages/garden.rose +0 -27
  45. package/example/src/pages/index.rose +0 -84
  46. package/example/src/pages/sign.rose +0 -45
  47. package/example/src/pages/thorn.rose +0 -23
  48. package/example/src/pages/vault.rose +0 -14
  49. package/go.mod +0 -3
  50. package/main.go +0 -470
  51. package/tools/release-notes.mjs +0 -113
  52. package/tsconfig.json +0 -17
@@ -11,7 +11,7 @@ type SignalEntry = { value: unknown; subs: Set<Subscriber> };
11
11
 
12
12
  let currentEffect: (() => void) | null = null;
13
13
 
14
- // ponytail: global signal map, shared across all inlined modules
14
+ // Trade-off: global signal map, shared across all inlined modules
15
15
  let signalMap: Map<string, SignalEntry> =
16
16
  (globalThis as any).__rosetack_signalMap ?? new Map();
17
17
  (globalThis as any).__rosetack_signalMap = signalMap;
@@ -87,10 +87,90 @@ export function esc(v: unknown): string {
87
87
  return String(v).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
88
88
  }
89
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: the eager version
113
+ // crashed `{#if user()}{user().name}{/if}` …
114
+ let snap: { html: string; closes: Close[] } | null = null;
115
+ closes.push(() => {
116
+ if (!cond()) {
117
+ snap = null;
118
+ return null;
119
+ }
120
+ if (!snap) {
121
+ const c: Close[] = [];
122
+ snap = { html: String(fn(scope, c)), closes: c };
123
+ }
124
+ return snap;
125
+ });
126
+ const r = closes[i]() as { html: string } | null;
127
+ return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
128
+ }
129
+
130
+ export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
131
+ const i = closes.length;
132
+ closes.push(() => (items() as unknown[]).map((v) => {
133
+ const c: Close[] = [];
134
+ return { html: String(fn(v, c)), closes: c, scope: v };
135
+ }));
136
+ let h = `<!--\u27e6l:${i}\u27e7-->`;
137
+ for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
138
+ return h + `<!--\u27e6/l:${i}\u27e7-->`;
139
+ }
140
+
141
+ export function headMark(closes: Close[], fn: Close): string {
142
+ const i = closes.push(fn) - 1;
143
+ return `<!--\u27e6h:${i}\u27e7-->` + fn() + `<!--\u27e6/h:${i}\u27e7-->`;
144
+ }
145
+
146
+ /**
147
+ * P1-2 (bug report): TRUSTED HTML - the explicit reverse of esc(). `{@html x}`
148
+ * emits the value verbatim, so a CMS's rich text renders as markup instead of
149
+ * as escaped source.
150
+ *
151
+ * The markers are an {#if} block's on purpose: wire() already knows how to
152
+ * adopt the server's nodes in place (identity preserved - an embedded iframe
153
+ * does not reload) and to swap the range for a fresh parse when the value
154
+ * changes. Reusing that machinery costs this function and nothing else: no
155
+ * new marker kind, no new wire branch, no bytes in a document that never
156
+ * uses it. The close returns the same {html, closes} shape an {#if} block
157
+ * does, with an EMPTY closes array - trusted HTML is opaque markup, the
158
+ * compiler never scans inside it, so there are no inner markers to wire.
159
+ * `arg` is the enclosing block's scope value, exactly as textMark takes it:
160
+ * a `{@html row.body}` inside an {#each} resolves against the row.
161
+ */
162
+ export function rawMark(closes: Close[], fn: Close, arg?: unknown): string {
163
+ const i = closes.push((s?: unknown) => ({ html: String((fn as (a?: unknown) => unknown)(s) ?? ''), closes: [] })) - 1;
164
+ const r = closes[i](arg) as { html: string };
165
+ return `<!--\u27e6i:${i}\u27e7-->` + r.html + `<!--\u27e6/i:${i}\u27e7-->`;
166
+ }
167
+
90
168
  // === Reactive DOM wiring (client) ===
91
169
 
92
170
  const MARK_RE = /^\u27e6([milh]):(\d+)\u27e7$/;
93
- const END_RE = /^\u27e6\/([ilh]):(\d+)\u27e7$/;
171
+ // `m` ends a text marker whose value is followed by literal text:
172
+ // the pair bounds exactly the value, so patching it cannot eat the prose.
173
+ const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
94
174
 
95
175
  // Comments already handled by a nested wire() pass (e.g. inside an adopted {#if} block)
96
176
  // must not be re-processed by the outer pass with the wrong closes array.
@@ -109,50 +189,63 @@ export function tpl(html: string): DocumentFragment {
109
189
  // head changes and user-authored <head> content is never touched.
110
190
  const HEAD_ATTR = 'data-rosetack-head';
111
191
 
192
+ // The delegated-event handler registry: every compiled module registers its handlers here
193
+ // (Object.assign(handlers, { ...
194
+ export const handlers: Record<string, (e: Event) => void> =
195
+ (globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
196
+
112
197
  /**
113
- * Apply one rendered <head> block to the document: <title> replaces the title,
114
- * <meta>/<link>/<base> are matched by name/property/rel/charset and updated
115
- * in place (or created). `provided` accumulates the keys of every block in the
116
- * route's head (a page renders inside its layouts, so several blocks apply per
117
- * navigation); keys it stops providing are dropped from the document.
198
+ * Apply one route's whole <head> (every block of its chain, page first) to the
199
+ * document: <title> replaces the title, <meta>/<link>/<base> are matched by
200
+ * name/property/rel/charset. First occurrence of a key wins, so a page
201
+ * overrides its layouts - the same rule the server's mergeHeadBlocks applies,
202
+ * which is why the two halves agree without talking to each other.
203
+ *
204
+ * The managed set is REBUILT from the block rather than patched element by
205
+ * element: a route's head is the whole truth, so anything the previous route
206
+ * provided and this one does not is dropped, and a key that moved tags is
207
+ * replaced instead of duplicated. It is also a third of the code.
118
208
  */
119
- export function applyHead(html: string, provided: Set<string>): void {
209
+ export function applyHead(html: string): void {
210
+ const seen = new Set<string>();
211
+ // tag -> how many unkeyed elements of that tag came before (the server's
212
+ // mergeHeadBlocks counts the same way over the same block order)
213
+ const positional = new Map<string, number>();
120
214
  const frag = tpl(html);
215
+ const title = frag.querySelector('title');
216
+ if (title) {
217
+ // Manage the title element directly: the document.title setter would update the FIRST
218
+ // title element in tree order …
219
+ let cur = document.head.querySelector('title');
220
+ if (!cur) {
221
+ cur = document.createElement('title');
222
+ document.head.appendChild(cur);
223
+ }
224
+ cur.textContent = title.textContent ?? '';
225
+ }
226
+ for (const el of Array.from(document.head.querySelectorAll(`[${HEAD_ATTR}]`))) el.remove();
121
227
  for (const el of Array.from(frag.children)) {
228
+ if (el.tagName === 'TITLE') continue;
122
229
  const tag = el.tagName.toLowerCase();
123
- if (tag === 'title') {
124
- // Manage the title element directly: the document.title setter would update the FIRST
125
- // title element in tree order …
126
- let titleEl = document.head.querySelector('title');
127
- if (!titleEl) {
128
- titleEl = document.createElement('title');
129
- document.head.appendChild(titleEl);
130
- }
131
- titleEl.textContent = el.textContent ?? '';
132
- continue;
133
- }
134
- if (tag !== 'meta' && tag !== 'link' && tag !== 'base') continue;
135
- const key = el.getAttribute('name')
230
+ // Bug report 2026.9.22 11:46: a head element with no name/property/rel/ charset
231
+ // attribute used to be dropped here in silence …
232
+ const identity = el.getAttribute('name')
136
233
  ?? el.getAttribute('property')
137
234
  ?? el.getAttribute('rel')
138
235
  ?? el.getAttribute('charset');
139
- if (!key) continue;
140
- const managed = `${tag}:${key}`;
141
- provided.add(managed);
142
- let target = document.head.querySelector(`[${HEAD_ATTR}="${managed}"]`);
143
- if (!target) {
144
- target = document.createElement(tag);
145
- target.setAttribute(HEAD_ATTR, managed);
146
- document.head.appendChild(target);
236
+ let managed: string;
237
+ if (identity) managed = `${tag}:${identity}`;
238
+ else if (el.id) managed = `${tag}:${el.id}`;
239
+ else {
240
+ const n = positional.get(tag) ?? 0;
241
+ positional.set(tag, n + 1);
242
+ managed = `${tag}:#${n}`;
147
243
  }
148
- for (const a of Array.from(el.attributes)) target.setAttribute(a.name, a.value);
149
- target.textContent = el.textContent;
244
+ if (seen.has(managed)) continue; // first block wins: page over layout
245
+ seen.add(managed);
246
+ el.setAttribute(HEAD_ATTR, managed);
247
+ document.head.appendChild(el);
150
248
  }
151
- // Drop managed meta/link/base the new head no longer provides. The title
152
- // persists across routes that don't declare one (standard SPA behavior).
153
- document.head.querySelectorAll(`[${HEAD_ATTR}]`).forEach((el) => {
154
- if (!provided.has(el.getAttribute(HEAD_ATTR)!)) el.remove();
155
- });
156
249
  }
157
250
 
158
251
  /** Drop every rosetack-managed head element (routes without <head> blocks). */
@@ -181,19 +274,42 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
181
274
  const walker = document.createTreeWalker(holder, NodeFilter.SHOW_COMMENT);
182
275
  while (walker.nextNode()) comments.push(walker.currentNode as Comment);
183
276
 
277
+ // Comments that live INSIDE an {#if}/{#each}/slot block belong to that block's OWN wire
278
+ // pass …
279
+ const nested = new Set<Comment>();
280
+ const open: number[] = []; // positions of the open {#if}/{#each} starts
281
+ for (let i = 0; i < comments.length; i++) {
282
+ const m = (comments[i].nodeValue ?? '').match(MARK_RE);
283
+ if (m && (m[1] === 'i' || m[1] === 'l')) {
284
+ open.push(i);
285
+ continue;
286
+ }
287
+ const em = (comments[i].nodeValue ?? '').match(END_RE);
288
+ if (!em) continue;
289
+ const key = em[1] + em[2];
290
+ let at = -1;
291
+ for (let k = open.length - 1; k >= 0; k--) {
292
+ const om = (comments[open[k]].nodeValue ?? '').match(MARK_RE)!;
293
+ if (om[1] + om[2] === key) { at = k; break; }
294
+ }
295
+ if (at < 0) continue; // an end with no open block: nothing to pair with
296
+ for (let k = open[at] + 1; k < i; k++) nested.add(comments[k]);
297
+ open.length = at; // pop this block and any inner block left unclosed
298
+ }
299
+
184
300
  const ends = new Map<number, Comment>();
185
301
  for (const c of comments) {
302
+ if (nested.has(c)) continue;
186
303
  const m = (c.nodeValue ?? '').match(END_RE);
187
304
  if (m) ends.set(+m[2], c);
188
305
  }
189
306
 
190
- // Head blocks are collected during the walk and applied afterwards in REVERSE document
191
- // order: a page renders inside its layout's <slot/> …
307
+ // Head blocks are collected during the walk and applied afterwards as ONE effect over the
308
+ // whole route's head: the blocks render in document order …
192
309
  const headBlocks: Array<{ idx: number; start: Comment; end: Comment; nodes: ChildNode[] }> = [];
193
- const headProvided = new Set<string>();
194
310
 
195
311
  for (const c of comments) {
196
- if (wired.has(c) || !c.parentNode) continue;
312
+ if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
197
313
  wired.add(c);
198
314
  const m = (c.nodeValue ?? '').match(MARK_RE);
199
315
  if (!m) continue;
@@ -214,13 +330,23 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
214
330
  }
215
331
  headBlocks.push({ idx, start: c, end, nodes });
216
332
  } else if (kind === 'm') {
217
- // Text: update the text node that follows the marker comment
333
+ // Text: update the text node that follows the marker comment. When the marker is a
334
+ // PAIR (value followed by literal text) …
218
335
  let target = c.nextSibling;
219
336
  if (!target || target.nodeType !== 3) {
220
337
  target = document.createTextNode('');
221
338
  c.parentNode!.insertBefore(target, c.nextSibling);
222
339
  }
223
340
  const tn = target as Text;
341
+ const end = ends.get(idx);
342
+ if (end) {
343
+ let n: ChildNode | null = tn.nextSibling;
344
+ while (n && n !== end) {
345
+ const nx = n.nextSibling;
346
+ n.remove();
347
+ n = nx;
348
+ }
349
+ }
224
350
  weff(() => {
225
351
  tn.nodeValue = String((closes[idx] as (s?: unknown) => unknown)(scope));
226
352
  });
@@ -238,7 +364,12 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
238
364
  st.__st = undefined;
239
365
  }
240
366
  const r = (closes[idx] as (s?: unknown) => unknown)(scope) as { html: string; closes: unknown[] } | null;
241
- if (!r) return;
367
+ if (!r) {
368
+ // Hidden. The client has now evaluated this block once, so from here on whatever
369
+ // sits between the anchors is client-rendered: a block the server left hidden …
370
+ st.__ever = true;
371
+ return;
372
+ }
242
373
  // First run adopts the server-rendered content (move out, wire, move back -
243
374
  // identity preserved); later runs clone the block template.
244
375
  let frag: DocumentFragment;
@@ -254,7 +385,9 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
254
385
  n = nx;
255
386
  }
256
387
  }
257
- const disp = wire(frag, r.closes, scope);
388
+ // r.scope is set by a named slot's block: its content is scoped to the object the child
389
+ // passed in, exactly like a list item.
390
+ const disp = wire(frag, r.closes, (r as { scope?: unknown }).scope ?? scope);
258
391
  const nodes = Array.from(frag.childNodes);
259
392
  const parent = anchor.parentNode!;
260
393
  for (const nd of nodes) parent.insertBefore(nd, anchor.nextSibling);
@@ -290,16 +423,22 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
290
423
  }
291
424
  }
292
425
 
293
- // Apply head blocks in reverse document order (page over layout), then drop the inert
294
- // placeholder nodes from the page body.
295
- for (let i = headBlocks.length - 1; i >= 0; i--) {
296
- const { idx, start, end, nodes } = headBlocks[i];
297
- weff(() => applyHead(String((closes[idx] as (s?: unknown) => unknown)(scope)), headProvided));
298
- nodes.forEach((nd) => nd.remove());
299
- start.remove();
300
- end.remove();
301
- }
302
- if (headBlocks.length === 0 && root.nodeType !== 11) clearHead();
426
+ // Apply head blocks, then drop the inert placeholder nodes from the page body. A
427
+ // top-level wire with no head blocks (route without <head>) clears the previous route's
428
+ // managed …
429
+ if (headBlocks.length > 0) {
430
+ const blocks = headBlocks;
431
+ weff(() => {
432
+ let html = '';
433
+ for (const b of blocks) html += String((closes[b.idx] as (s?: unknown) => unknown)(scope));
434
+ applyHead(html);
435
+ });
436
+ for (const b of blocks) {
437
+ b.nodes.forEach((nd) => nd.remove());
438
+ b.start.remove();
439
+ b.end.remove();
440
+ }
441
+ } else if (root.nodeType !== 11) clearHead();
303
442
 
304
443
  // Attributes: data-b="K:attrName"
305
444
  const els = (holder as Element).querySelectorAll('[data-b]');
@@ -328,7 +467,7 @@ export function resetEffects(): void {
328
467
 
329
468
  // === Server Data Fetching ($data) ===
330
469
 
331
- // ponytail: cache keyed by function source, cleared per request/navigation.
470
+ // Trade-off: cache keyed by function source, cleared per request/navigation.
332
471
  // Upgrade path: explicit keys if two $data calls share identical source.
333
472
  let dataCache = new Map<string, Promise<unknown>>();
334
473
 
@@ -347,6 +486,30 @@ export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
347
486
  export function clearRequestState(): void {
348
487
  signalMap.clear();
349
488
  dataCache.clear();
489
+ pendingDeltas.clear();
490
+ }
491
+
492
+ // === Request query (P0-1) === The parsed query string of the request being rendered
493
+ // (?page=2&q=x -> {page:'2',q:'x'}) …
494
+ let requestQuery: Record<string, string> = {};
495
+ let prefetchOverride: Record<string, string> | null = null;
496
+
497
+ export function $query(): Record<string, string> {
498
+ if (prefetchOverride) return prefetchOverride;
499
+ if (typeof location === 'undefined') return requestQuery;
500
+ const q: Record<string, string> = {};
501
+ new URLSearchParams(location.search).forEach((v, k) => { q[k] = v; });
502
+ return q;
503
+ }
504
+
505
+ /** The per-request query object - the servers call this before every render. */
506
+ export function setRequestQuery(q: Record<string, string>): void {
507
+ requestQuery = q;
508
+ }
509
+
510
+ /** The query of the route a prefetch is rendering, or null outside one. */
511
+ export function setPrefetchOverride(q: Record<string, string> | null): void {
512
+ prefetchOverride = q;
350
513
  }
351
514
 
352
515
  // === Request context === A per-request bag: pages/_middleware.rose fills it
@@ -376,7 +539,7 @@ export function resetRequestContext(): void {
376
539
  * the captured disposers so the NEXT resetEffects() disposes them (a prefetch
377
540
  * render's cleanups firing early would dispose a route that was never
378
541
  * painted, and dropping them would leak the painted route's timers).
379
- * Concurrent prefetches are queued by the caller (ponytail: hover prefetches
542
+ * Concurrent prefetches are queued by the caller (trade-off: hover prefetches
380
543
  * are rare and cheap).
381
544
  */
382
545
  export async function isolateStateAsync<T>(
@@ -384,6 +547,8 @@ export async function isolateStateAsync<T>(
384
547
  ): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
385
548
  const savedSignals = signalMap;
386
549
  const savedData = dataCache;
550
+ const savedDeltas = new Map(pendingDeltas); // a prefetch render must not consume a delta
551
+ pendingDeltas.clear();
387
552
  const savedMounts = mountQueue.splice(0, mountQueue.length);
388
553
  const savedCleanups = new Set(cleanups);
389
554
  cleanups.clear();
@@ -400,6 +565,8 @@ export async function isolateStateAsync<T>(
400
565
  } finally {
401
566
  signalMap = savedSignals;
402
567
  dataCache = savedData;
568
+ pendingDeltas.clear();
569
+ savedDeltas.forEach((d, k) => pendingDeltas.set(k, d)); // restore what was pending
403
570
  mountQueue.splice(0, 0, ...savedMounts); // prepend what was queued before
404
571
  cleanups.clear();
405
572
  savedCleanups.forEach((fn: Cleanup) => cleanups.add(fn));
@@ -478,22 +645,55 @@ export function adoptCleanups(fns: Iterable<Cleanup>): void {
478
645
  for (const fn of fns) cleanups.add(fn);
479
646
  }
480
647
 
481
- // === i18n: localized routes (innovation #27) === Every JSON file in src/locales/ is a
482
- // language: { "key": "string" }.
648
+ // === i18n: localized routes === Every JSON file in src/locales/ is a language: { "key":
649
+ // "string" }.
483
650
  let LOCALES: Record<string, Record<string, string>> = {};
484
651
  let DEFAULT_LOCALE = 'en';
652
+ // The locales this build did NOT bake in: they live at /locales/<lang>.json and
653
+ // ensureLocale() fetches one on first use.
654
+ let LOCALE_PACKS: string[] = [];
485
655
 
486
656
  export function setLocales(dicts: Record<string, Record<string, string>>, def: string): void {
487
657
  LOCALES = dicts;
488
658
  DEFAULT_LOCALE = def;
489
659
  }
490
660
 
661
+ /** The locales the build left out of this bundle (generated code calls this). */
662
+ export function setLocalePacks(langs: string[]): void {
663
+ LOCALE_PACKS = langs;
664
+ }
665
+
666
+ /** Merge a dictionary that arrived at runtime - a fetched pack, or an app's own import(). */
667
+ export function loadLocale(lang: string, dict: Record<string, string>): void {
668
+ LOCALES[lang] = { ...LOCALES[lang], ...dict };
669
+ }
670
+
671
+ /**
672
+ * Resolve once `lang`'s dictionary is present: immediately for an inline
673
+ * locale, after one fetch for a runtime pack, never for an unknown one (the
674
+ * URL is the contract - the server 404s it). A failed fetch leaves the locale
675
+ * unresolved and $t falls back to the default language; the next navigation
676
+ * retries. This is the seam a bundled-per-locale app can bypass entirely by
677
+ * calling loadLocale() itself.
678
+ */
679
+ export async function ensureLocale(lang: string): Promise<void> {
680
+ if (LOCALES[lang] || !LOCALE_PACKS.includes(lang)) return;
681
+ try {
682
+ const res = await fetch(`/locales/${encodeURIComponent(lang)}.json`);
683
+ if (res.ok) loadLocale(lang, await res.json());
684
+ } catch {
685
+ // offline, or the pack is missing: the inline dictionaries still render
686
+ }
687
+ }
688
+
491
689
  export function localeList(): string[] {
492
690
  return Object.keys(LOCALES);
493
691
  }
494
692
 
495
693
  export function isLocale(lang: string): boolean {
496
- return Object.prototype.hasOwnProperty.call(LOCALES, lang);
694
+ // A pack counts as a known locale BEFORE it loads: the client router must
695
+ // not 404 /ar/about while /locales/ar.json is still in flight.
696
+ return Object.hasOwn(LOCALES, lang) || LOCALE_PACKS.includes(lang);
497
697
  }
498
698
 
499
699
  /**
@@ -513,22 +713,70 @@ export function bestLocale(header: string | null | undefined): string | null {
513
713
  return null;
514
714
  }
515
715
 
716
+ /**
717
+ * Reading direction of a locale. The set of right-to-left scripts is closed
718
+ * (Arabic, Hebrew and their relatives), so a base-tag test covers every
719
+ * language that uses them - no per-app config, and the document's <html dir>
720
+ * is server-rendered correct for no-JS visitors. A regex LITERAL, not a
721
+ * string .split(): esbuild drops side-effect-free initializers, so an app
722
+ * whose scripts never call localeDir ships neither it nor the table.
723
+ */
724
+ const RTL_RE = /^(ar|fa|he|ur|ps|sd|ug|yi|ckb|dv|ks|prs|haz|mzn|nqo)/;
725
+ /** 'rtl' for a right-to-left locale, '' otherwise - '' is the html default. */
726
+ export function localeDir(lang: string): string {
727
+ return RTL_RE.test(lang) ? 'rtl' : '';
728
+ }
729
+
730
+ // --- ICU MessageFormat, the subset real apps use --------------------- {count, plural, =0
731
+ // {No signatures yet} one {# item} other {# items}} {n, selectordinal …
732
+ const ICU_RE = /\{([\w$]+),\s*(plural|selectordinal|select),\s*((?:\s*[=\w]+\s*\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g;
733
+ const BRANCH_RE = /([=\w]+)\s*\{((?:[^{}]|\{[^{}]*\})*)\}/g;
734
+
735
+ /** The CLDR category of `n` in `locale`, or null where Intl has no answer. */
736
+ function pluralCategory(locale: string, ordinal: boolean, n: number): string | null {
737
+ try {
738
+ return new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined).select(n);
739
+ } catch {
740
+ return null; // no Intl.PluralRules, or an invalid tag: the English-ish fallback
741
+ }
742
+ }
743
+
744
+ /** Expand every ICU block of a message; leave the rest (and {name} holes) alone. */
745
+ function expandIcu(msg: string, vars: Record<string, string | number> | undefined, locale: string): string {
746
+ return msg.replace(ICU_RE, (whole, arg: string, kind: string, branchText: string) => {
747
+ const branches: Record<string, string> = {};
748
+ for (const m of branchText.matchAll(BRANCH_RE)) branches[m[1]] = m[2];
749
+ if (!branches.other) return whole; // no fallback arm: not valid ICU, render it verbatim
750
+ const v = vars?.[arg];
751
+ if (kind === 'select') return branches[typeof v === 'string' && branches[v] ? v : 'other'];
752
+ const num = typeof v === 'number' ? v : Number(v);
753
+ // An =N arm wins over the category; a value with no number in it has no category at
754
+ // all, so it takes the other arm - and # prints the value as given …
755
+ const cat = isFinite(num)
756
+ ? (branches['=' + num] ? '=' + num : pluralCategory(locale, kind === 'selectordinal', num) ?? 'other')
757
+ : 'other';
758
+ return (branches[cat] ?? branches.other).replace(/#/g, String(v));
759
+ });
760
+ }
761
+
516
762
  /**
517
763
  * Translate a key for the current language. The [lang] route param arrives
518
764
  * as state before the render (the same seeding as any dynamic param), and
519
765
  * reading it through the signal getter makes $t reactive: switching locale
520
766
  * re-runs the marker, so only the translated nodes repaint.
521
767
  */
522
- export function $t(key: string, vars?: Record<string, string>): string {
768
+ export function $t(key: string, vars?: Record<string, string | number>): string {
523
769
  const [lang] = state('lang', DEFAULT_LOCALE);
524
770
  const dict = LOCALES[lang()] ?? LOCALES[DEFAULT_LOCALE] ?? {};
525
- let s = Object.prototype.hasOwnProperty.call(dict, key) ? dict[key] : key;
526
- if (vars) for (const k in vars) s = s.split(`{${k}}`).join(vars[k]);
527
- return s;
771
+ const msg = dict[key];
772
+ let out = expandIcu(typeof msg === 'string' ? msg : key, vars, lang());
773
+ if (vars) for (const k in vars) out = out.split(`{${k}}`).join(String(vars[k]));
774
+ return out;
528
775
  }
529
776
 
530
- // --- Phase 2: the shared server store ---------------------------------------- Module
531
- // scope (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds …
777
+ // --- the shared server store ---------------------------------------- Module scope
778
+ // (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds its
779
+ // own …
532
780
 
533
781
  const STORES = new Map<string, { value: unknown }>();
534
782
  let storeTransport: ((name: string, value: unknown) => void) | null = null;
@@ -579,8 +827,124 @@ export function $store<T>(name: string, initial: T): { get(): T; set(v: T): void
579
827
  };
580
828
  }
581
829
 
582
- // --- Phase 1: cookie helpers ------------------------------------------------- Sessions
583
- // are the first thing every real app needs and the easiest thing to get subtly wrong …
830
+ // --- server action errors, guards and incremental patches -----------
831
+ //
832
+ // The action model's three gaps, closed with one request-scoped mechanism.
833
+ //
834
+ // 1. A standardized failure object. An action that cannot do its job (bad
835
+ // input, not signed in, a duplicate) throws ActionError; the dispatch
836
+ // catches it, seeds the page's state with it and re-renders, so the page
837
+ // answers with the failure VISIBLE (status = the error's code) instead of
838
+ // a 500 or a silent no-op. A bug still propagates to the 500 page.
839
+ // 2. A guard. `export async function beforeAction(name, form)` runs before
840
+ // every action of its page and vetoes with an ActionError - the
841
+ // action-level permission check (a redirect stays the middleware's job).
842
+ // 3. Incremental patches. A patch value may be an OPERATION ($append and
843
+ // friends) instead of a whole replacement, so growing a large list costs
844
+ // one row instead of a second copy of the list.
845
+
846
+ export class ActionError extends Error {
847
+ /** the HTTP status the response carries (400/401/403/409/422/...) */
848
+ code: number;
849
+ /** the form field the failure belongs to, when it belongs to one */
850
+ field?: string;
851
+ constructor(message: string, code = 400, field?: string) {
852
+ super(message);
853
+ this.name = 'ActionError';
854
+ this.code = code;
855
+ this.field = field;
856
+ }
857
+ }
858
+
859
+ /** The JSON-safe shape the dispatch seeds into state (what `$actionError()` returns). */
860
+ export type ActionErrorInfo = { action: string; message: string; code: number; field?: string };
861
+
862
+ /**
863
+ * The failure of the action that produced the response being rendered, or
864
+ * null. It is ordinary state under the key `actionError`, so the client's
865
+ * resumeState() restores it and the post-adopt re-render sees exactly what
866
+ * the server saw - one read, both sides, no hydration payload.
867
+ *
868
+ * Read it as data (`{#if $actionError()}<p>{$actionError().message}</p>{/if}`)
869
+ * or let a {#boundary} contain it ($actionErrorOrThrow below).
870
+ */
871
+ export function $actionError(): ActionErrorInfo | null {
872
+ const e = signalMap.get('actionError');
873
+ if (!e) return null;
874
+ if (currentEffect) e.subs.add(currentEffect); // subscribe like a state read
875
+ return (e.value as ActionErrorInfo | null) ?? null;
876
+ }
877
+
878
+ /**
879
+ * What a {#boundary} whose content depends on an action calls first: when the
880
+ * action that produced this response failed, throw - the boundary's own catch
881
+ * turns it into the fallback, so the section degrades to the error message
882
+ * instead of rendering a widget built on work that never happened.
883
+ */
884
+ export function $actionErrorOrThrow(): void {
885
+ const info = $actionError();
886
+ if (info) throw new ActionError(info.message, info.code, info.field);
887
+ }
888
+
889
+ /** The {#boundary} fallback: the action's own message when the failure is a business one. */
890
+ export function $boundaryFallback(err: unknown): string {
891
+ if (err instanceof ActionError) return `<p class="rosetack-action-error">${esc(err.message)}</p>`;
892
+ return '<p>This section failed to render.</p>';
893
+ }
894
+
895
+ // An incremental patch: an action's return value may map a key to an OPERATION instead of a
896
+ // whole replacement value …
897
+ export type StateDeltaOp = 'append' | 'prepend' | 'merge';
898
+
899
+ export class StateDelta {
900
+ constructor(public op: StateDeltaOp, public value: unknown) {}
901
+ }
902
+
903
+ /** Append (or prepend) items to a list-valued state key. */
904
+ export const $append = (value: unknown): StateDelta => new StateDelta('append', value);
905
+ export const $prepend = (value: unknown): StateDelta => new StateDelta('prepend', value);
906
+ /** Shallow-merge an object into an object-valued state key. */
907
+ export const $merge = (value: Record<string, unknown>): StateDelta => new StateDelta('merge', value);
908
+
909
+ const pendingDeltas = new Map<string, StateDelta>();
910
+
911
+ /** Record the deltas of the action that just ran (the dispatch calls this). */
912
+ export function setStateDelta(key: string, delta: StateDelta): void {
913
+ pendingDeltas.set(key, delta);
914
+ }
915
+
916
+ /**
917
+ * Apply every pending delta to the live state and clear them. The generated
918
+ * render calls this once, right after its state declarations - and only the
919
+ * SSR side ever emits the call: a delta is recorded by a server dispatch, so
920
+ * on the client (post-adopt re-render, client-side navigation, refresh) the
921
+ * map is empty and this is a no-op. That is also why a delta can never apply
922
+ * twice: the value it produced is what the state script carried, and the
923
+ * client resumes THAT instead of recomputing it.
924
+ */
925
+ export function applyStateDeltas(): void {
926
+ if (pendingDeltas.size === 0) return;
927
+ for (const [key, delta] of [...pendingDeltas]) {
928
+ pendingDeltas.delete(key);
929
+ applyStateDelta(key, delta);
930
+ }
931
+ }
932
+
933
+ /** Apply one delta to the live state. */
934
+ export function applyStateDelta(key: string, delta: StateDelta): void {
935
+ const cur = signalMap.get(key)?.value;
936
+ if (delta.op === 'merge') {
937
+ setState(key, { ...(cur as Record<string, unknown> | undefined), ...(delta.value as Record<string, unknown>) });
938
+ return;
939
+ }
940
+ const list = (v: unknown): unknown[] => (v == null ? [] : Array.isArray(v) ? v : [v]);
941
+ const merged =
942
+ delta.op === 'append' ? [...list(cur), ...list(delta.value)] : [...list(delta.value), ...list(cur)];
943
+ setState(key, merged);
944
+ }
945
+
946
+ // --- cookie helpers ------------------------------------------------- Sessions are the
947
+ // first thing every real app needs and the easiest thing to get subtly wrong …
584
948
 
585
949
  /**
586
950
  * Parse the cookies of a request (server) or of this document (client, where
@@ -622,3 +986,38 @@ export function $sessionCookie(
622
986
  secure || sameSite === 'None' ? 'Secure' : '',
623
987
  ].filter(Boolean).join('; ');
624
988
  }
989
+
990
+ // === Client observability: the web-vitals hook === A framework that sells TTFB, one
991
+ // request and zero hydration owes the app a way to prove it in production.
992
+ export function reportVitals(): void {
993
+ if (typeof window === 'undefined' || typeof performance === 'undefined') return;
994
+ const live: Record<string, number> = {};
995
+ (window as unknown as { __rosetack_vitals?: Record<string, number> }).__rosetack_vitals = live;
996
+ const send = (name: string, value: number) => {
997
+ live[name] = value;
998
+ window.dispatchEvent(new CustomEvent('rosetack:vitals', { detail: { name, value, route: location.pathname } }));
999
+ };
1000
+ const nav = performance.getEntriesByType?.('navigation')?.[0] as PerformanceNavigationTiming | undefined;
1001
+ if (nav) send('ttfb', Math.round(nav.responseStart));
1002
+ const paints = performance.getEntriesByType?.('paint') ?? [];
1003
+ const fcp = paints.find((p) => p.name === 'first-contentful-paint');
1004
+ if (fcp) send('fcp', Math.round(fcp.startTime));
1005
+ const PO = (window as unknown as { PerformanceObserver?: typeof PerformanceObserver }).PerformanceObserver;
1006
+ if (!PO) return; // a browser without observers still gets ttfb/fcp above
1007
+ let cls = 0;
1008
+ let inp = 0;
1009
+ const flush = () => {
1010
+ if (cls) send('cls', Math.round(cls * 1000) / 1000);
1011
+ if (inp) send('inp', Math.round(inp));
1012
+ };
1013
+ document.addEventListener('visibilitychange', () => {
1014
+ if (document.visibilityState === 'hidden') flush();
1015
+ });
1016
+ new PO((list) => {
1017
+ for (const e of list.getEntries() as Array<PerformanceEntry & { value?: number; duration?: number; interactionId?: number }>) {
1018
+ if (e.entryType === 'layout-shift' && !(e as unknown as { hadRecentInput?: boolean }).hadRecentInput) cls += e.value ?? 0;
1019
+ if (e.entryType === 'event' && e.interactionId) inp = Math.max(inp, e.duration ?? 0);
1020
+ if (e.entryType === 'largest-contentful-paint') send('lcp', Math.round(e.startTime));
1021
+ }
1022
+ }).observe({ entryTypes: ['layout-shift', 'event', 'largest-contentful-paint'] });
1023
+ }