@ogygia/router 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stream.js CHANGED
@@ -1,29 +1,8 @@
1
+ import { STALE, scope } from "@ogygia/machine";
2
+ import { body_end, cleanup_failed, head_end } from "@ogygia/core/internal/server";
1
3
  import { LATE_BOOT_SCRIPT, lateChunk } from "@ogygia/core/plugin";
2
4
  import { escapeText } from "@ogygia/core/plugin/utils";
3
5
  // src/stream.ts
4
- /**
5
- * STREAMED PAGES — `page(async function* (c, data) { yield region(...); ... })`.
6
- *
7
- * "The next state of a slot is a region" is the house law (`query.live` yields regions over the
8
- * push channel); this is the same vocabulary on the INITIAL response: the FIRST yield renders in
9
- * the document and the page flushes immediately; every later yield rides down the SAME response
10
- * as an inert `<template data-og-late>` chunk that swaps into the slot as it parses. One
11
- * connection, closed when the generator ends — no SSE, no second round trip, and no Svelte
12
- * streaming needed: each yield is an ordinary synchronous render, only the DOCUMENT is chunked.
13
- *
14
- * Islands inside late chunks need no orchestration: `<ogygia-region>` is a custom element, so
15
- * the moment swapped content lands in the DOM it upgrades, connects, and wakes on its own
16
- * schedule — the runtime never has to be told.
17
- *
18
- * Swapping is driven by ONE small classic inline script in the head (module scripts don't run
19
- * until parsing ENDS, which for a streamed document is the very thing we're not waiting for).
20
- * The slot, chunk and boot script are core's late wire (`ogygia/plugin`): core's `<Region
21
- * of={promise}>` emits the same slots and its runtime applies the same chunks. SPA navigations
22
- * fetch the COMPLETED stream, so there the runtime applies remaining templates after the body swap.
23
- *
24
- * Streaming's honest trades (documented): status/title/headers flush with the first yield — a
25
- * late error can't change an already-sent 200, and Server-Timing set after the flush is lost.
26
- */
27
6
  /** The slot id for the page position (one streamed slot per page in v1). */
28
7
  const PAGE_SLOT_ID = "pg";
29
8
  /** Bake ANY yielded value to html: a string passes through, an inline region carries its html,
@@ -45,7 +24,6 @@ async function bake_yield(v) {
45
24
  function is_stream_slot(v) {
46
25
  return Object.prototype.toString.call(v) === "[object AsyncGeneratorFunction]";
47
26
  }
48
- const HEAD_CLOSE_RE = /<\/head>/i;
49
27
  const NO_TRANSFORM_RE = /no-transform/i;
50
28
  /** Adapt a page GENERATOR's remaining yields into page-slot chunks (bake included). */
51
29
  async function* page_slot_chunks(rest) {
@@ -58,26 +36,45 @@ async function* page_slot_chunks(rest) {
58
36
  };
59
37
  }
60
38
  }
61
- function stream_document(full_html, res, rest, error_slot = "pg") {
62
- const with_boot = full_html.replace(HEAD_CLOSE_RE, LATE_BOOT_SCRIPT + "</head>");
63
- const cut = with_boot.lastIndexOf("</body>");
39
+ /**
40
+ * Turns a fully rendered document (first yield in place) and the remaining chunks into a streamed
41
+ * Response: everything up to `</body>` flushes now, each later chunk follows as an inert
42
+ * `<template>` that core's late boot script swaps into its slot as it parses, then the tail. The
43
+ * status and headers go out with the first flush, so a later throw cannot change them: it becomes
44
+ * an error card in `error_slot`. The stream ends when the visitor leaves (the body is cancelled)
45
+ * or `request` ends, and its chunk source is ended with it.
46
+ */
47
+ function stream_document(full_html, res, rest, error_slot = "pg", request) {
48
+ const at = head_end(full_html);
49
+ const with_boot = at === -1 ? full_html : `${full_html.slice(0, at)}${LATE_BOOT_SCRIPT}${full_html.slice(at)}`;
50
+ const cut = body_end(with_boot);
64
51
  const head_part = cut === -1 ? with_boot : with_boot.slice(0, cut);
65
52
  const tail_part = cut === -1 ? "" : with_boot.slice(cut);
66
53
  const enc = new TextEncoder();
67
- const body = new ReadableStream({ async start(controller) {
68
- controller.enqueue(enc.encode(head_part));
69
- try {
70
- for (;;) {
71
- const n = await rest.next();
72
- if (n.done) break;
73
- controller.enqueue(enc.encode(lateChunk(n.value.slot, n.value.html)));
54
+ const owner = scope(request);
55
+ owner.defer(() => void rest.return(void 0).catch(cleanup_failed));
56
+ const body = new ReadableStream({
57
+ async start(controller) {
58
+ controller.enqueue(enc.encode(head_part));
59
+ try {
60
+ for (;;) {
61
+ const n = await owner.task(() => rest.next());
62
+ if (n === STALE) return;
63
+ if (n.done) break;
64
+ controller.enqueue(enc.encode(lateChunk(n.value.slot, n.value.html)));
65
+ }
66
+ } catch (e) {
67
+ if (owner.closed) return;
68
+ controller.enqueue(enc.encode(lateChunk(error_slot, error_card_html(e))));
74
69
  }
75
- } catch (e) {
76
- controller.enqueue(enc.encode(lateChunk(error_slot, error_card_html(e))));
70
+ controller.enqueue(enc.encode(tail_part));
71
+ controller.close();
72
+ owner.close();
73
+ },
74
+ cancel() {
75
+ owner.close();
77
76
  }
78
- controller.enqueue(enc.encode(tail_part));
79
- controller.close();
80
- } });
77
+ });
81
78
  const headers = new Headers(res.headers);
82
79
  headers.delete("content-length");
83
80
  const cc = headers.get("cache-control");
@@ -113,6 +110,54 @@ async function* late_region_chunks(list) {
113
110
  };
114
111
  }
115
112
  }
113
+ /**
114
+ * Every late chunk of the document, until nothing new registers. A chunk bakes its region as its
115
+ * promise settles, and a region baked there may hold a `<Region of={promise}>` of its own: it
116
+ * registers then, after the document's list was taken. So after each chunk the request's late
117
+ * regions are taken again (`take`), and whatever registered joins as one more source, in
118
+ * completion order with the rest. It ends only when every source ended and a last take finds
119
+ * none: no slot is left that nothing fills.
120
+ */
121
+ async function* until_drained(first, take) {
122
+ const sources = [];
123
+ const nexts = /* @__PURE__ */ new Map();
124
+ const add = (source) => {
125
+ const i = sources.push(source) - 1;
126
+ nexts.set(i, source.next().then((r) => ({
127
+ i,
128
+ r
129
+ })));
130
+ };
131
+ const take_more = () => {
132
+ const more = take();
133
+ if (more?.length) add(late_region_chunks(more));
134
+ };
135
+ add(first);
136
+ try {
137
+ for (;;) {
138
+ if (nexts.size === 0) {
139
+ take_more();
140
+ if (nexts.size === 0) return;
141
+ }
142
+ const { i, r } = await Promise.race(nexts.values());
143
+ if (r.done) {
144
+ nexts.delete(i);
145
+ continue;
146
+ }
147
+ nexts.set(i, sources[i].next().then((res) => ({
148
+ i,
149
+ r: res
150
+ })));
151
+ yield r.value;
152
+ take_more();
153
+ }
154
+ } finally {
155
+ end_all(sources);
156
+ }
157
+ }
158
+ function end_all(sources) {
159
+ for (const s of sources) s.return(void 0).catch(cleanup_failed);
160
+ }
116
161
  /** Interleave chunk sources by READINESS (a page generator + the late-region pool run together;
117
162
  * whichever has a chunk ready streams next). Ends when every source ends. */
118
163
  async function* merge_chunks(...sources) {
@@ -120,16 +165,20 @@ async function* merge_chunks(...sources) {
120
165
  i,
121
166
  r
122
167
  }))]));
123
- while (nexts.size) {
124
- const { i, r } = await Promise.race(nexts.values());
125
- if (r.done) nexts.delete(i);
126
- else {
127
- nexts.set(i, sources[i].next().then((res) => ({
128
- i,
129
- r: res
130
- })));
131
- yield r.value;
168
+ try {
169
+ while (nexts.size) {
170
+ const { i, r } = await Promise.race(nexts.values());
171
+ if (r.done) nexts.delete(i);
172
+ else {
173
+ nexts.set(i, sources[i].next().then((res) => ({
174
+ i,
175
+ r: res
176
+ })));
177
+ yield r.value;
178
+ }
132
179
  }
180
+ } finally {
181
+ end_all(sources);
133
182
  }
134
183
  }
135
- export { PAGE_SLOT_ID, bake_yield, error_card_html, is_stream_slot, late_region_chunks, merge_chunks, page_slot_chunks, stream_document };
184
+ export { PAGE_SLOT_ID, bake_yield, error_card_html, is_stream_slot, late_region_chunks, merge_chunks, page_slot_chunks, stream_document, until_drained };
package/dist/view.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { StandardIssue, StandardResult, StandardSchemaV1, StandardSchemaV1 as StandardSchemaV1$1 } from "@ogygia/core/plugin/utils";
2
2
  export type InferOutput<S> = S extends StandardSchemaV1$1<infer O> ? O : never;
3
- /** Route params derived from the pattern string via template literals — `/docs/[slug]` → { slug: string },
4
- * `/[[lang]]` → { lang?: string }, `/[...rest]` → { rest: string }, `/[id].json` → { id: string }. No codegen. */
5
3
  export type Simplify<T> = { [K in keyof T]: T[K]; } & {};
6
4
  type SegParam<S extends string> = S extends `[[${infer O}]]` ? { [K in O]?: string; } : S extends `[...${infer R}]` ? { [K in R]: string; } : S extends `${string}[${infer N}]${string}` ? { [K in N]: string; } : {};
7
5
  type ParamsAcc<P extends string> = P extends `${infer A}/${infer B}` ? SegParam<A> & ParamsAcc<B> : SegParam<P>;
6
+ /** A route's params, read from its pattern: `/docs/[slug]` → `{ slug: string }`, `/[[lang]]` →
7
+ * `{ lang?: string }`, `/[...rest]` → `{ rest: string }`, `/[id].json` → `{ id: string }`. */
8
8
  export type Params<P extends string> = Simplify<ParamsAcc<P>>;
9
9
  /** The params object `href` accepts for a pattern — every param, as a string or number. */
10
10
  export type HrefParams<P extends string> = { [K in keyof Params<P>]: string | number; };
package/dist/visitor.d.ts CHANGED
@@ -5,4 +5,14 @@ export interface AnonymousVisitorOptions {
5
5
  /** Cookie lifetime in days (default 365). */
6
6
  days?: number;
7
7
  }
8
+ /**
9
+ * A visitor resolver for logged-out traffic, so experiments, flags and rollouts stay sticky for
10
+ * anonymous visitors too (with no identity, a split falls back to control). It mints a random id
11
+ * into a first-party cookie on first sight and returns it as `{ vid }` after that. It is never
12
+ * `sub`, a signed-in user's id that `mount()` signs onward to peers: the cookie is whatever the
13
+ * browser sends. The id is not a fingerprint and carries nothing; clearing the cookie rotates it.
14
+ *
15
+ * routes(table, { visitor: anonymousVisitor() })
16
+ * routes(table, { visitor: (c) => session(c) ?? anon(c) })
17
+ */
8
18
  export declare function anonymousVisitor(opts?: AnonymousVisitorOptions): (c: Ctx) => Visitor | undefined;
package/dist/visitor.js CHANGED
@@ -1,16 +1,14 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { random } from "@ogygia/machine";
2
2
  // src/visitor.ts
3
3
  /**
4
- * Anonymous visitor identity — sticky experiments/flags/rollouts for LOGGED-OUT traffic.
5
- * Without an identity, splits degrade to control (nothing to hash on); this resolver mints a
6
- * random id into a cookie on first sight and returns it as `{ sub }` forever after, so a
7
- * rollout percentage holds for anonymous visitors too.
4
+ * A visitor resolver for logged-out traffic, so experiments, flags and rollouts stay sticky for
5
+ * anonymous visitors too (with no identity, a split falls back to control). It mints a random id
6
+ * into a first-party cookie on first sight and returns it as `{ vid }` after that. It is never
7
+ * `sub`, a signed-in user's id that `mount()` signs onward to peers: the cookie is whatever the
8
+ * browser sends. The id is not a fingerprint and carries nothing; clearing the cookie rotates it.
8
9
  *
9
- * routes(table, { visitor: anonymousVisitor() }) // anonymous-only
10
- * routes(table, { visitor: (c) => session(c) ?? anon(c) }) // session first
11
- *
12
- * The id is random (not a fingerprint), first-party, and carries nothing — rotate it by
13
- * clearing the cookie. GDPR-wise it is a functional identifier; consult your own counsel.
10
+ * routes(table, { visitor: anonymousVisitor() })
11
+ * routes(table, { visitor: (c) => session(c) ?? anon(c) })
14
12
  */
15
13
  function anonymousVisitor(opts = {}) {
16
14
  const name = opts.cookie ?? "og-vid";
@@ -18,10 +16,10 @@ function anonymousVisitor(opts = {}) {
18
16
  return (c) => {
19
17
  const existing = c.cookies?.get(name);
20
18
  if (existing) return {
21
- sub: existing,
19
+ vid: existing,
22
20
  anonymous: true
23
21
  };
24
- const id = randomUUID();
22
+ const id = random.uuid();
25
23
  if (c.cookies?.set) c.cookies.set(name, id, {
26
24
  path: "/",
27
25
  maxAge: max_age,
@@ -30,7 +28,7 @@ function anonymousVisitor(opts = {}) {
30
28
  });
31
29
  else c.setHeaders?.({ "set-cookie": `${name}=${id}; Path=/; Max-Age=${max_age}; HttpOnly; SameSite=Lax` });
32
30
  return {
33
- sub: id,
31
+ vid: id,
34
32
  anonymous: true
35
33
  };
36
34
  };
package/dist/vite.d.ts CHANGED
@@ -1,2 +1,8 @@
1
- import { OgygiaPlugin } from "@ogygia/core/vite";
1
+ import { OgygiaPlugin } from "@ogygia/compiler/vite";
2
+ /**
3
+ * The server router's plugin, listed beside `ogygia()` in vite.config. A `routes()` table renders
4
+ * pages outside Kit's routes, so nothing file-derived links their components' CSS: this tells the
5
+ * build that every module importing `@ogygia/router` is a page module, and every component it can
6
+ * reach gets its whole-tree CSS linked when it renders.
7
+ */
2
8
  export declare function router(): OgygiaPlugin;
package/dist/vite.js CHANGED
@@ -1,11 +1,10 @@
1
- import { definePlugin } from "@ogygia/core/vite";
1
+ import { definePlugin } from "@ogygia/compiler/vite";
2
2
  // src/vite.ts
3
3
  /**
4
- * `router()` — the server router, listed beside `ogygia()` in vite.config. A `routes()` table
5
- * renders pages outside Kit's routes, so nothing file-derived links their components' CSS: listing the
6
- * plugin tells the build that every module importing `@ogygia/router` is a page module, and every
7
- * component it can reach gets its whole-tree CSS linked when it renders. It also makes the package the
8
- * app's own code to the build (server-inlined: it ships `.svelte`).
4
+ * The server router's plugin, listed beside `ogygia()` in vite.config. A `routes()` table renders
5
+ * pages outside Kit's routes, so nothing file-derived links their components' CSS: this tells the
6
+ * build that every module importing `@ogygia/router` is a page module, and every component it can
7
+ * reach gets its whole-tree CSS linked when it renders.
9
8
  */
10
9
  function router() {
11
10
  return definePlugin({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ogygia/router",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "The server router for ogygia: Kit's routing model as values (routes, layouts, loads, actions, endpoints, streamed pages), with a typed fetch client",
5
5
  "keywords": [
6
6
  "ogygia",
@@ -22,6 +22,7 @@
22
22
  "README.md"
23
23
  ],
24
24
  "type": "module",
25
+ "sideEffects": false,
25
26
  "exports": {
26
27
  ".": {
27
28
  "types": "./dist/index.d.ts",
@@ -40,15 +41,20 @@
40
41
  "publishConfig": {
41
42
  "access": "public"
42
43
  },
44
+ "dependencies": {
45
+ "@ogygia/machine": "^0.14.0"
46
+ },
43
47
  "devDependencies": {
44
- "@ogygia/core": "0.12.0",
48
+ "@ogygia/compiler": "0.14.0",
49
+ "@ogygia/config": "0.0.0",
50
+ "@ogygia/core": "0.14.0",
45
51
  "@ogygia/tooling": "0.0.0",
46
52
  "@playwright/test": "1.62.1",
47
53
  "@sveltejs/kit": "^2.70.2",
48
54
  "@sveltejs/vite-plugin-svelte": "^7.2.0",
49
55
  "@types/node": "^26.1.2",
50
56
  "@typescript/native": "npm:typescript@^7.0.2",
51
- "svelte": "5.56.8",
57
+ "svelte": "5.57.3",
52
58
  "svelte-check": "^4.7.4",
53
59
  "tsdown": "^0.23.4",
54
60
  "typescript": "^6.0.3",
@@ -56,7 +62,8 @@
56
62
  "vitest": "^4.1.12"
57
63
  },
58
64
  "peerDependencies": {
59
- "@ogygia/core": "^0.12.0",
65
+ "@ogygia/compiler": "^0.14.0",
66
+ "@ogygia/core": "^0.14.0",
60
67
  "@sveltejs/kit": ">=2.70.2 <4",
61
68
  "svelte": "^5.56.8"
62
69
  },