@ogygia/router 0.13.0 → 0.15.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.
@@ -1,21 +1,5 @@
1
- <script>
2
- /**
3
- * Renders a route's layout chain around its page. `chain` is the layout components from OUTERMOST to
4
- * innermost (app shell → section shell → …); each is an inert component that renders `{@render
5
- * children()}` and may read `data` (the cascaded load data at that level). At the bottom the PAGE
6
- * COMPONENT is rendered AS MARKUP (`<Page {...props} />`), not as a held region — so any import-
7
- * attribute mark on it (`with { wake }`, `with { render: 'deferred' }`, `with { region: 'raw' }`,
8
- * `with { keep }`) emits its shell exactly as it would at any other usage site. That is what makes
9
- * page-level interactivity/deferral work: the router is a normal placement site for the component.
10
- *
11
- * `fallback` (a deferred page's loading placeholder) is provided as the component's reserved
12
- * `ogygiaFallback` snippet — the router is the deferred page's use site, so it supplies the slot a
13
- * deferred component would otherwise get from its `{#snippet ogygiaFallback()}` child.
14
- *
15
- * Server-rendered inside document(); the layouts and the page are real regions, so islands inside
16
- * them wake and their CSS rides the response.
17
- */
18
- let { chain, component: Page, props, data, fallback: Fallback } = $props();
1
+ <script>let { chain, component: Page, props, data, fallback: Fallback } = $props();
2
+ export {};
19
3
  </script>
20
4
 
21
5
  {#snippet nest(i)}
@@ -1,19 +1,12 @@
1
+ import type { Component } from 'svelte';
2
+ type AnyComponent = Component<Record<string, unknown>>;
3
+ interface Props {
4
+ chain: AnyComponent[];
5
+ component: AnyComponent;
6
+ props: Record<string, unknown>;
7
+ data: unknown;
8
+ fallback?: AnyComponent;
9
+ }
10
+ declare const LayoutChain: Component<Props, {}, "">;
11
+ type LayoutChain = ReturnType<typeof LayoutChain>;
1
12
  export default LayoutChain;
2
- type LayoutChain = {
3
- $on?(type: string, callback: (e: any) => void): () => void;
4
- $set?(props: Partial<$$ComponentProps>): void;
5
- };
6
- declare const LayoutChain: import("svelte").Component<{
7
- chain: any;
8
- component: any;
9
- props: any;
10
- data: any;
11
- fallback: any;
12
- }, {}, "">;
13
- type $$ComponentProps = {
14
- chain: any;
15
- component: any;
16
- props: any;
17
- data: any;
18
- fallback: any;
19
- };
@@ -1,8 +1,4 @@
1
- <script>/**
2
- * The page component behind an html view (a resolver that answered `{ __oghtml, html }`, a mounted
3
- * document): the html is finished, this just drops it in. Static: ships as HTML, no client JS.
4
- */
5
- let { html } = $props();
1
+ <script>let { html } = $props();
6
2
  </script>
7
3
 
8
4
  {@html html}
@@ -4,7 +4,6 @@ export declare class ApiError extends Error {
4
4
  readonly body: unknown;
5
5
  constructor(status: number, body: unknown, message?: string);
6
6
  }
7
- /** keys of `App` that carry verb `M` — endpoint entries only (pages have no verb slots). */
8
7
  type KeysWith<App, M extends string> = { [K in keyof App & string]: App[K] extends Record<M, {
9
8
  out: unknown;
10
9
  }> ? K : never; }[keyof App & string];
@@ -14,7 +13,6 @@ type OutOf<App, K extends keyof App, M extends string> = App[K] extends Record<M
14
13
  type InOf<App, K extends keyof App, M extends string> = App[K] extends Record<M, {
15
14
  in: infer I;
16
15
  }> ? I : undefined;
17
- /** `params` is REQUIRED exactly when the pattern has any (same rule as `href`). */
18
16
  type ParamsOpt<K extends string> = {} extends Params<K> ? {
19
17
  params?: HrefParams<K>;
20
18
  } : {
@@ -29,7 +27,6 @@ type CallOpts<K extends string, In = undefined> = ParamsOpt<K> & BodyOpt<In> & {
29
27
  search?: Record<string, string | number>;
30
28
  headers?: Record<string, string>;
31
29
  };
32
- /** args tuple: the options object itself is omittable when nothing in it is required. */
33
30
  type CallArgs<K extends string, In = undefined> = {} extends Params<K> & (undefined extends In ? {} : {
34
31
  body: In;
35
32
  }) ? [opts?: CallOpts<K, In>] : [opts: CallOpts<K, In>];
@@ -46,5 +43,14 @@ export interface ApiClient<App> {
46
43
  put<K extends KeysWith<App, "put">>(path: K, ...args: CallArgs<K, InOf<App, K, "put">>): Promise<OutOf<App, K, "put">>;
47
44
  patch<K extends KeysWith<App, "patch">>(path: K, ...args: CallArgs<K, InOf<App, K, "patch">>): Promise<OutOf<App, K, "patch">>;
48
45
  }
46
+ /**
47
+ * A typed fetch client for a router's endpoints, from the app's `$infer` map. Paths are the keys
48
+ * that have the verb; `params` is required when the pattern has any; the body is the schema's
49
+ * input; the result is the handler's plain return (a raw `Response` return types as `unknown`).
50
+ * A non-2xx answer throws {@link ApiError}. It loads only the path grammar, so islands can use it.
51
+ *
52
+ * const cms = api<App>('https://cms.example.com');
53
+ * const post = await cms.get('/posts/[id]', { params: { id: '1' } });
54
+ */
49
55
  export declare function api<App>(base: string, opts?: ApiClientOptions): ApiClient<App>;
50
56
  export {};
@@ -1,25 +1,5 @@
1
1
  import { fill } from "./match.js";
2
2
  // src/client-api.ts
3
- /**
4
- * The typed API client — `$infer` for ENDPOINTS, consumed. The table already knows every
5
- * endpoint's path grammar, body schema, and (for PLAIN returns, which `finalize()` serializes
6
- * to JSON) its payload type; `api<App>()` hands all of that to the caller as a fetch client:
7
- *
8
- * export type App = typeof app.$infer; // the one map the app already exports
9
- * const cms = api<App>('https://cms.internal');
10
- * const post = await cms.get('/posts/[id]', { params: { id: '1' } }); // out: typed
11
- * await cms.post('/api/[id]', { params: { id }, body }); // body: schema-typed
12
- *
13
- * Paths are constrained to keys that HAVE the verb (page paths never carry one, so they are
14
- * excluded for free); `params` is required exactly when the pattern has any; a handler that
15
- * returned a raw `Response` types as `unknown` (its payload is inside the Response — write
16
- * plain returns for typed endpoints). Non-2xx answers throw {@link ApiError} carrying the
17
- * status and the parsed error body.
18
- *
19
- * BROWSER-SAFE by construction: this module imports only the light path grammar (match.ts) —
20
- * no svelte, no node builtins — so islands can import `@ogygia/router/api` directly. (Not
21
- * `/client`: that subpath is a plugin's browser realm, booted on every page.)
22
- */
23
3
  var ApiError = class extends Error {
24
4
  status;
25
5
  body;
@@ -29,16 +9,26 @@ var ApiError = class extends Error {
29
9
  this.body = body;
30
10
  }
31
11
  };
12
+ /**
13
+ * A typed fetch client for a router's endpoints, from the app's `$infer` map. Paths are the keys
14
+ * that have the verb; `params` is required when the pattern has any; the body is the schema's
15
+ * input; the result is the handler's plain return (a raw `Response` return types as `unknown`).
16
+ * A non-2xx answer throws {@link ApiError}. It loads only the path grammar, so islands can use it.
17
+ *
18
+ * const cms = api<App>('https://cms.example.com');
19
+ * const post = await cms.get('/posts/[id]', { params: { id: '1' } });
20
+ */
32
21
  function api(base, opts = {}) {
33
22
  const f = opts.fetch ?? fetch;
34
23
  const root = base.replace(TRAILING_SLASH_RE, "");
35
24
  const call = async (method, path, o = {}) => {
36
- let url = root + fill(path, o.params ?? {});
25
+ let search = "";
37
26
  if (o.search) {
38
27
  const qs = new URLSearchParams();
39
28
  for (const [k, v] of Object.entries(o.search)) qs.set(k, String(v));
40
- url += `?${qs}`;
29
+ search = `?${qs}`;
41
30
  }
31
+ const url = `${root}${fill(path, o.params ?? {})}${search}`;
42
32
  const has_body = o.body !== void 0;
43
33
  const res = await f(url, {
44
34
  method,
package/dist/ctx.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import { Simplify } from "./view.js";
2
2
  import { RequestEvent } from "@sveltejs/kit";
3
- /** The visitor's identity — plain claims (`sub`, roles, whatever the app's session carries). */
3
+ /** The visitor's identity — plain claims (`sub`, roles, whatever the app's session carries). A
4
+ * logged-out visitor has no `sub`: `anonymousVisitor()` gives `vid`, a random id from a cookie. */
4
5
  export type Visitor = Record<string, unknown> & {
5
6
  sub?: string;
7
+ vid?: string;
6
8
  };
7
9
  export interface Ctx<P = Record<string, string | undefined>, S = Record<string, string>, I = undefined> {
8
10
  /** Path params — pattern-typed, or the `params` schema's coerced output (404 on bad input). */
package/dist/ctx.js CHANGED
@@ -1,7 +1,7 @@
1
- import { json_response, redirect_response } from "./respond.js";
1
+ import { json_response, redirect_response, text_response } from "./respond.js";
2
2
  // src/ctx.ts
3
3
  /** Signature-bound claims attached by the federation handle after verification (fragment federation). */
4
- const CLAIMS = Symbol.for("ogygia.claims.v1");
4
+ const CLAIMS = Symbol.for("ogygia.claims");
5
5
  function make_ctx(params, url, request, event, href, routeId, visitor_resolver) {
6
6
  const search = {};
7
7
  for (const [k, v] of url.searchParams) if (!(k in search)) search[k] = v;
@@ -35,13 +35,7 @@ function make_ctx(params, url, request, event, href, routeId, visitor_resolver)
35
35
  event,
36
36
  json: (data, init) => json_response(data, init),
37
37
  redirect: (location, status = 303) => redirect_response(status, location),
38
- text: (body, init) => new Response(body, {
39
- ...init,
40
- headers: {
41
- "content-type": "text/plain; charset=utf-8",
42
- ...init?.headers
43
- }
44
- }),
38
+ text: (body, init) => text_response(body, init),
45
39
  href,
46
40
  state: {}
47
41
  };
package/dist/define.d.ts CHANGED
@@ -44,6 +44,8 @@ export interface LoadDef<Data = unknown, P extends string = string, Prm = LooseP
44
44
  }
45
45
  /** `load(fn)` / `load(pattern, fn)`. The returned function memoizes on `c` (run once per request);
46
46
  * the dispatcher's concurrent branch-load pass and any `await other_load(c)` share the same promise.
47
+ * A failed run is the request's too: every later call in it gets the same failure. A call made after
48
+ * the request ended rejects with the reason it ended.
47
49
  * In a page's `load` slot, `load(fn)` takes the page's params through its contextual return type
48
50
  * (like a verb wrapper); anywhere else they are loose. */
49
51
  export declare function load<Data, Prm = LooseParams, Srch = Record<string, string>>(run: (c: Ctx<Prm, Srch>) => Data | Promise<Data>): LoadDef<Awaited<Data>, string, Prm, Srch>;
@@ -64,14 +66,9 @@ export declare function action<Ret, P extends string, Srch = Record<string, stri
64
66
  /** Either load form `page()` / `layout()` accept: the `load()` value wrapper OR a bare typed fn. */
65
67
  export type LoadInput = LoadDef | ((c: Ctx) => unknown);
66
68
  export type ActionInput = ActionDef | ((c: Ctx) => unknown);
67
- /** A page's `load` slot, given the params and search its `c` reads: a `load()` wrapper (which takes
68
- * `P` from this) or a bare fn. */
69
69
  type PageLoad<P, S> = LoadDef<unknown, string, P, S> | ((c: Ctx<P, S>) => unknown);
70
- /** One of a page's `actions` (mirrors {@link PageLoad}). */
71
70
  type PageAction<P, S> = ActionDef<unknown, string, P, S> | ((c: Ctx<P, S>) => unknown);
72
- /** A page's `c.params`: its `params` schema's output, else the key's (`P`). */
73
71
  type PageParams<P, PS> = [PS] extends [StandardSchemaV1] ? InferOutput<PS> : P;
74
- /** A page's `c.search`: its `search` schema's output, else the raw query. */
75
72
  type PageSearch<SS> = [SS] extends [StandardSchemaV1] ? InferOutput<SS> : Record<string, string>;
76
73
  /** The `+page.server.ts`-shaped second argument to `page()`. Always an object (ruled). Route input is
77
74
  * declared here (`params`/`search` schemas — coerced, typed into `c`, shown in `$infer`); `load` and
@@ -195,7 +192,6 @@ export interface LayoutDef<Name extends string = string, Load = unknown> {
195
192
  /** phantom — carries the authored load type to `$infer`; never read at runtime */
196
193
  readonly __loadType?: Load;
197
194
  }
198
- /** Prepend a layout to one entry's chain, preserving all generics (endpoints pass through). */
199
195
  type WithLayout<D, Def extends LayoutDef> = D extends PageDef<infer L, infer Load, infer A, infer PS, infer SS, infer KP> ? PageDef<readonly [Def, ...L], Load, A, PS, SS, KP> : D;
200
196
  export interface LayoutFn<Def extends LayoutDef> {
201
197
  readonly __oglayout: Def;
@@ -227,7 +223,6 @@ export interface VerbEntry<Out = unknown, In = undefined, P = unknown> {
227
223
  params: P;
228
224
  };
229
225
  }
230
- /** Params a handler sees with no table key to type them (a wrapper outside a table): indexable. */
231
226
  type LooseParams = Record<string, string | undefined>;
232
227
  /** One verb slot of an endpoint object, as `RouteTable` accepts it: any handler, or a verb wrapper.
233
228
  * What a slot's `c` IS comes from its table key ({@link KeyedTable}). */
package/dist/define.js CHANGED
@@ -8,7 +8,19 @@ function memo_of(c) {
8
8
  name: "router load",
9
9
  key: ["def"],
10
10
  ignore: { c: "the request this memo is made for: one per request" },
11
- run: (i) => i.def.run(i.c)
11
+ run: async (i) => {
12
+ try {
13
+ return {
14
+ ok: true,
15
+ value: await i.def.run(i.c)
16
+ };
17
+ } catch (error) {
18
+ return {
19
+ ok: false,
20
+ error
21
+ };
22
+ }
23
+ }
12
24
  });
13
25
  request_scope(c.request).adopt(memo);
14
26
  return holder.__ogloads = memo;
@@ -19,7 +31,10 @@ function load(a, b) {
19
31
  const fn = ((c) => memo_of(c).get({
20
32
  def: fn,
21
33
  c
22
- }).then((v) => v === STALE ? Promise.reject(request_scope(c.request).signal.reason) : v));
34
+ }).then((v) => {
35
+ if (v === STALE) return Promise.reject(request_scope(c.request).signal.reason);
36
+ return v.ok ? v.value : Promise.reject(v.error);
37
+ }));
23
38
  fn.__ogload = true;
24
39
  fn.pattern = pattern;
25
40
  fn.run = run;
@@ -39,8 +54,6 @@ function to_load(input) {
39
54
  if (input.__ogload) return input;
40
55
  return load(input);
41
56
  }
42
- /** Normalize a bare function to an ActionDef; an `action()` wrapper passes through. Both take the
43
- * widest input (`never` params/search: a load typed for any page fits). */
44
57
  function to_action(input) {
45
58
  if (input.__ogaction) return input;
46
59
  return action(input);
package/dist/infer.d.ts CHANGED
@@ -3,48 +3,32 @@ import { ActionFailure } from "./respond.js";
3
3
  import { InferOutput, Params, Simplify, StandardSchemaV1 } from "./view.js";
4
4
  import { Snippet } from "svelte";
5
5
  type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
6
- /** The data a load contributes — a `load()` wrapper OR a bare function (both authoring forms). `{}`
7
- * when absent / non-object. LoadDef is checked first (it is itself callable). A `Response` arm is
8
- * the load's SHORT-CIRCUIT (the dispatcher returns it verbatim and never renders the component), so
9
- * it is excluded from `data` — the component only ever sees the non-Response arm. */
10
6
  type Obj<D> = D extends object ? D : {};
11
- type Data_<D> = Obj<Exclude<D, Response>>;
12
- type DataOf<L> = L extends LoadDef<infer D, string, never, never> ? Data_<D> : L extends ((c: never) => infer R) ? Data_<Awaited<R>> : {};
7
+ type DataWithoutShortCircuit<D> = Obj<Exclude<D, Response>>;
8
+ type DataOf<L> = L extends LoadDef<infer D, string, never, never> ? DataWithoutShortCircuit<D> : L extends ((c: never) => infer R) ? DataWithoutShortCircuit<Awaited<R>> : {};
13
9
  type LayoutData<L> = L extends LayoutDef<string, infer LD> ? DataOf<LD> : {};
14
- /** Merge a layout chain's data (outermost-first) — the whole tuple. */
15
10
  type ChainData<Ls extends readonly LayoutDef[]> = Ls extends readonly [infer H, ...infer R] ? LayoutData<H> & (R extends readonly LayoutDef[] ? ChainData<R> : {}) : {};
16
11
  type Layouts<V> = V extends PageDef<infer L, unknown, unknown, unknown, unknown> ? L : readonly [];
17
12
  type LoadType<V> = V extends PageDef<readonly LayoutDef[], infer Load, unknown, unknown, unknown> ? Load : undefined;
18
13
  type ActionsType<V> = V extends PageDef<readonly LayoutDef[], unknown, infer A, unknown, unknown> ? A : undefined;
19
14
  type ParamsSchemaType<V> = V extends PageDef<readonly LayoutDef[], unknown, unknown, infer PS, unknown> ? PS : undefined;
20
15
  type SearchSchemaType<V> = V extends PageDef<readonly LayoutDef[], unknown, unknown, unknown, infer SS> ? SS : undefined;
21
- /** A page's merged `data`: its layout chain's data ∧ its own load's data (Kit's PageData). */
22
16
  type PageData<V> = ChainData<Layouts<V>> & DataOf<LoadType<V>>;
23
- /** The `form` prop: union of the page's action returns, unwrapping `fail(status, F)` → `F`; `null`
24
- * when there are no actions (Kit's ActionData shape). Redirects throw, so contribute nothing. */
25
17
  type ActionData<R> = R extends ActionFailure<infer F> ? F : R;
26
18
  type FormOf<V> = ActionsType<V> extends Record<string, (c: never) => infer R> ? ActionData<Awaited<R>> | null : null;
27
- /** Path params: the `params` schema's output when present, else pattern-derived from the key. */
28
19
  type ParamsOf<K extends string, V> = ParamsSchemaType<V> extends StandardSchemaV1 ? InferOutput<ParamsSchemaType<V>> : Params<K>;
29
- /** Query params: the `search` schema's output when present, else `{}`. */
30
20
  type SearchOf<V> = SearchSchemaType<V> extends StandardSchemaV1 ? InferOutput<SearchSchemaType<V>> : {};
31
- /** Page entries: `{ [path]: { data, form, params, search } }` for every PageDef key. */
32
21
  type PageEntries<T> = { [K in keyof T & string as T[K] extends AnyPageDef ? K : never]: T[K] extends AnyPageDef ? {
33
22
  data: Simplify<PageData<T[K]>>;
34
23
  form: FormOf<T[K]>;
35
24
  params: Simplify<ParamsOf<K, T[K]>>;
36
25
  search: Simplify<SearchOf<T[K]>>;
37
26
  } : never; };
38
- /** Every prefix of a layout chain → `{ '(name)': { data: <prefix merge>, children } }`. `Acc` carries
39
- * the ancestor data as we descend; each layout's entry is its ancestors ∧ its own load. */
40
- type LayoutEntries<Ls extends readonly LayoutDef[], Acc = {}> = Ls extends readonly [infer H, ...infer R] ? H extends LayoutDef<infer Name, unknown> ? { [P in `(${Name})`]: {
41
- data: Simplify<Acc & LayoutData<H>>;
27
+ type LayoutEntries<Ls extends readonly LayoutDef[], AncestorData = {}> = Ls extends readonly [infer H, ...infer R] ? H extends LayoutDef<infer Name, unknown> ? { [P in `(${Name})`]: {
28
+ data: Simplify<AncestorData & LayoutData<H>>;
42
29
  children: Snippet;
43
- }; } & (R extends readonly LayoutDef[] ? LayoutEntries<R, Acc & LayoutData<H>> : {}) : {} : {};
44
- /** All layout entries across the table (a name repeats with the same prefix → intersection idempotent). */
30
+ }; } & (R extends readonly LayoutDef[] ? LayoutEntries<R, AncestorData & LayoutData<H>> : {}) : {} : {};
45
31
  type AllLayoutEntries<T> = UnionToIntersection<{ [K in keyof T]: T[K] extends AnyPageDef ? LayoutEntries<Layouts<T[K]>> : {}; }[keyof T]>;
46
- /** A handler's PAYLOAD type: a PLAIN return is the JSON body (`finalize()` serializes it); a
47
- * `Response` return erases to `unknown` (the payload type is inside the Response, unknowable). */
48
32
  type PayloadOf<R> = [R] extends [never] ? unknown : R extends Response ? unknown : R;
49
33
  type SlotOut<H> = H extends VerbEntry<infer O, unknown> ? PayloadOf<O> : H extends ((c: never) => infer R) ? PayloadOf<Awaited<R>> : unknown;
50
34
  type SlotIn<H> = H extends VerbEntry<unknown, infer I> ? I : undefined;
@@ -52,13 +36,16 @@ type SlotEntry<H> = {
52
36
  out: SlotOut<H>;
53
37
  in: SlotIn<H>;
54
38
  };
55
- /** One endpoint's verb map, lowercase-keyed: `{ get: { out, in }, post: … }` — plus `params` from
56
- * the table key. Pages never appear here (they carry `__ogkind`), so a key having `get`/`post`
57
- * is what the `api()` client constrains on. */
58
39
  type EndpointVerbs<V> = { [M in keyof V & string as V[M] extends undefined ? never : Lowercase<M>]: SlotEntry<V[M]>; };
59
40
  type EndpointEntries<T> = { [K in keyof T & string as T[K] extends AnyPageDef ? never : K]: T[K] extends AnyPageDef ? never : Simplify<EndpointVerbs<T[K]> & {
60
41
  params: Simplify<Params<K>>;
61
42
  }>; };
62
- /** The full `$infer` map: page paths ⊕ endpoint paths ⊕ layout `(name)`s. */
43
+ /**
44
+ * The `$infer` map an app exports (`export type App = typeof app.$infer`): `App['/docs/[slug]']`
45
+ * is a page's `{ data, form, params, search }`, `App['(name)']` a layout's `{ data, children }`, and
46
+ * an endpoint's key holds its lowercase verbs' `{ out, in }`. `data` merges the layout chain's loads
47
+ * with the page's own, as Kit's cascade does. It is computed from loads and schemas, never from
48
+ * components.
49
+ */
63
50
  export type InferMap<T extends TableShape> = Simplify<PageEntries<T> & EndpointEntries<T> & AllLayoutEntries<T>>;
64
51
  export {};
package/dist/match.d.ts CHANGED
@@ -1,13 +1,3 @@
1
- /**
2
- * Pattern compilation + matching for the ogygia router. Kit's route grammar, reused verbatim so
3
- * nothing new is learned:
4
- * /docs/[slug] — one required segment → { slug: string }
5
- * /docs/[...rest] — rest, may be empty → { rest: string }
6
- * /[[lang]]/docs — optional segment → { lang?: string }
7
- * Matching is trailing-slash-insensitive by default (refinement 1): `/docs/foo` and `/docs/foo/`
8
- * hit the same route with identical params. This module is pure — no rendering, no request — so the
9
- * whole match/specificity story is unit-testable by calling `compile()` + `match_path()` directly.
10
- */
11
1
  export interface ParamSpec {
12
2
  name: string;
13
3
  /** `[...rest]` — captures the remaining path (slashes included), may be '' */
@@ -20,11 +10,15 @@ export interface CompiledPattern {
20
10
  pattern: string;
21
11
  regex: RegExp;
22
12
  params: ParamSpec[];
23
- /** higher = more specific; used to order overlapping matches (static beats dynamic) */
24
- score: number;
25
13
  }
14
+ /**
15
+ * Compiles a route pattern in Kit's grammar (`/docs/[slug]`, `/files/[...rest]`, `/[[lang]]/docs`,
16
+ * and mixed segments like `/[id].json`) into a trailing-slash-insensitive regex and its params.
17
+ * Throws on a malformed pattern. A table's order is {@link compile_all}'s.
18
+ */
26
19
  export declare function compile(pattern: string): CompiledPattern;
27
- /** Compile a whole table's keys and sort most-specific-first, so the first match wins. */
20
+ /** Compile a whole table's keys and sort them in Kit's route order, so the first match is the
21
+ * route Kit would pick for the same files (test/router-route-order.test.ts). */
28
22
  export declare function compile_all(patterns: string[]): CompiledPattern[];
29
23
  export interface PathMatch {
30
24
  pattern: string;
@@ -32,6 +26,15 @@ export interface PathMatch {
32
26
  }
33
27
  /** Match one compiled pattern against a pathname. Returns params, or null if it doesn't match. */
34
28
  export declare function match_one(c: CompiledPattern, pathname: string): PathMatch | null;
29
+ /** Fills a pattern's `[param]`, `[[optional]]` and `[...rest]` tokens from `params`, URL-encoded
30
+ * as Kit's `resolve()` writes them: a rest value keeps its `/` (each segment encoded), and an
31
+ * empty optional or rest param that is a whole segment drops that segment. A missing `[param]`
32
+ * becomes empty. Throws on a value that would fill a whole segment with `.` or `..`: every URL
33
+ * parser drops that segment, so the URL would name another route (`%2e` is read as a dot too).
34
+ * Throws on an empty segment too, other than a dropped one or the last: a rest value with an
35
+ * empty piece (a leading, trailing or doubled `/`), or a param that fills its segment empty,
36
+ * would build `//host` (a URL of another origin) or a path that routes elsewhere.
37
+ * Tests: test/property-fill-match.test.ts, test/router-match.test.ts. */
35
38
  export declare function fill(pattern: string, params: Record<string, string | number>): string;
36
39
  /** First (most-specific) match in a pre-sorted list, or null. */
37
40
  export declare function match_path(sorted: CompiledPattern[], pathname: string): PathMatch | null;
package/dist/match.js CHANGED
@@ -3,20 +3,22 @@ const REGEX_SPECIAL_G = /[.*+?^${}()|[\]\\]/g;
3
3
  const escape_re = (s) => s.replace(REGEX_SPECIAL_G, "\\$&");
4
4
  const REST = /^\[\.\.\.([a-zA-Z_$][\w$]*)\]$/;
5
5
  const OPTIONAL = /^\[\[([a-zA-Z_$][\w$]*)\]\]$/;
6
- /** strips valid `[param]` groups so any leftover bracket flags a malformed segment */
7
- const STRIP_PARAMS = /\[[a-zA-Z_$][\w$]*\]/g;
6
+ const VALID_PARAM_GROUPS = /\[[a-zA-Z_$][\w$]*\]/g;
7
+ const INNER_PARAM = /\[([a-zA-Z_$][\w$]*)\]/g;
8
+ const has_stray_bracket = (seg) => {
9
+ const left = seg.replace(VALID_PARAM_GROUPS, "");
10
+ return left.includes("[") || left.includes("]");
11
+ };
8
12
  /**
9
- * Compile a pattern into a regex + its param specs + a specificity score. Throws on an obviously
10
- * malformed pattern (a rest segment that isn't last) — a loud build-time-ish error beats a route
11
- * that silently never matches.
13
+ * Compiles a route pattern in Kit's grammar (`/docs/[slug]`, `/files/[...rest]`, `/[[lang]]/docs`,
14
+ * and mixed segments like `/[id].json`) into a trailing-slash-insensitive regex and its params.
15
+ * Throws on a malformed pattern. A table's order is {@link compile_all}'s.
12
16
  */
13
- const INNER_PARAM = /\[([a-zA-Z_$][\w$]*)\]/g;
14
17
  function compile(pattern) {
15
18
  if (!pattern.startsWith("/")) throw new Error(`[@ogygia/router] route pattern must start with "/": ${JSON.stringify(pattern)}`);
16
19
  const segs = pattern.split("/").filter((s) => s !== "");
17
20
  const params = [];
18
- const digits = [];
19
- let rx = "";
21
+ const rx = [];
20
22
  segs.forEach((seg, i) => {
21
23
  let m;
22
24
  if (m = seg.match(REST)) {
@@ -25,62 +27,142 @@ function compile(pattern) {
25
27
  name: m[1],
26
28
  rest: true
27
29
  });
28
- rx += "(?:/(.*))?";
29
- digits.push(0);
30
+ rx.push("(?:/(.*))?");
30
31
  } else if (m = seg.match(OPTIONAL)) {
31
32
  params.push({
32
33
  name: m[1],
33
34
  optional: true
34
35
  });
35
- rx += "(?:/([^/]+))?";
36
- digits.push(1);
36
+ rx.push("(?:/([^/]+))?");
37
37
  } else {
38
- let inner = "/";
39
- let has_static = false;
40
- let has_param = false;
38
+ const pieces = [];
41
39
  let last = 0;
42
40
  INNER_PARAM.lastIndex = 0;
43
41
  let g;
44
42
  while (g = INNER_PARAM.exec(seg)) {
45
43
  const pre = seg.slice(last, g.index);
46
- if (pre) {
47
- inner += escape_re(pre);
48
- has_static = true;
49
- }
50
- inner += "([^/]+)";
51
- params.push({ name: g[1] });
52
- has_param = true;
44
+ if (pre) pieces.push({ text: pre });
45
+ pieces.push({ name: g[1] });
53
46
  last = INNER_PARAM.lastIndex;
54
47
  }
55
48
  const tail = seg.slice(last);
56
- if (tail) {
57
- inner += escape_re(tail);
58
- has_static = true;
59
- }
60
- const leftover = seg.replace(STRIP_PARAMS, "");
61
- if (leftover.includes("[") || leftover.includes("]") || !has_static && !has_param) throw new Error(`[@ogygia/router] malformed segment ${JSON.stringify(seg)} in ${pattern}`);
62
- rx += inner;
63
- digits.push(!has_param ? 4 : has_static ? 3 : 2);
49
+ if (tail) pieces.push({ text: tail });
50
+ let inner = "/";
51
+ let has_static = false;
52
+ let has_param = false;
53
+ let params_left = pieces.filter((p) => "name" in p).length;
54
+ pieces.forEach((p, j) => {
55
+ if ("text" in p) {
56
+ inner += escape_re(p.text);
57
+ has_static = true;
58
+ return;
59
+ }
60
+ params_left--;
61
+ const next = pieces[j + 1];
62
+ const group = params.length + 1;
63
+ let capture = "([^/])";
64
+ if (params_left === 0) capture = "([^/]+)";
65
+ else if (next && "text" in next) capture = `(?=([^/]+?)${escape_re(next.text)})\\${group}`;
66
+ inner += capture;
67
+ params.push({ name: p.name });
68
+ has_param = true;
69
+ });
70
+ if (has_stray_bracket(seg) || !has_static && !has_param) throw new Error(`[@ogygia/router] malformed segment ${JSON.stringify(seg)} in ${pattern}`);
71
+ rx.push(inner);
64
72
  }
65
73
  });
66
- if (rx === "") rx = "/?";
67
- const regex = new RegExp("^" + rx + "/?$");
68
- const trailing_rest = params.length > 0 && params[params.length - 1].rest === true;
69
- const eff = trailing_rest ? digits.slice(0, -1) : digits;
70
- let score = 0;
71
- for (const d of eff) score = score * 5 + d;
72
- score = score * 64 + eff.length;
73
- if (trailing_rest) score -= 1;
74
74
  return {
75
75
  pattern,
76
- regex,
77
- params,
78
- score
76
+ regex: new RegExp(`^${rx.length ? rx.join("") : "/?"}/?$`),
77
+ params
79
78
  };
80
79
  }
81
- /** Compile a whole table's keys and sort most-specific-first, so the first match wins. */
80
+ /** Compile a whole table's keys and sort them in Kit's route order, so the first match is the
81
+ * route Kit would pick for the same files (test/router-route-order.test.ts). */
82
82
  function compile_all(patterns) {
83
- return patterns.map(compile).sort((a, b) => b.score - a.score);
83
+ const segments = new Map(patterns.map((p) => [p, route_segments(p)]));
84
+ return patterns.map(compile).sort((a, b) => kit_order(a.pattern, segments.get(a.pattern), b.pattern, segments.get(b.pattern)));
85
+ }
86
+ const EMPTY_PART = {
87
+ type: "static",
88
+ content: ""
89
+ };
90
+ const PARAM_KIND = {
91
+ "[": "optional",
92
+ ".": "rest"
93
+ };
94
+ const NON_FINAL_OPTIONAL_G = /\[\[[^\]]+\]\](?!$)/g;
95
+ /** A pattern as Kit sorts it: its segments, each split into parts that alternate static (first,
96
+ * maybe '') and dynamic. An `[[optional]]` that is not last counts for nothing. */
97
+ function route_segments(pattern) {
98
+ return pattern.replace(NON_FINAL_OPTIONAL_G, "").split("/").filter(Boolean).map((segment) => {
99
+ const parts = [];
100
+ let i = 0;
101
+ for (;;) {
102
+ const start = segment.indexOf("[", i);
103
+ if (start === -1) {
104
+ parts.push({
105
+ type: "static",
106
+ content: segment.slice(i)
107
+ });
108
+ return parts;
109
+ }
110
+ parts.push({
111
+ type: "static",
112
+ content: segment.slice(i, start)
113
+ });
114
+ const type = PARAM_KIND[segment[start + 1]] ?? "required";
115
+ i = segment.indexOf(type === "optional" ? "]]" : "]", start) + (type === "optional" ? 2 : 1);
116
+ parts.push({
117
+ type,
118
+ content: segment.slice(start, i)
119
+ });
120
+ }
121
+ });
122
+ }
123
+ /** Kit's route comparator (`sort_routes`): segment by segment from the left, a static part beats a
124
+ * dynamic one and a required param beats an optional one, a shallower path beats a deeper one
125
+ * on a static difference, `[...rest]` ranks below anything with a static part after it, and a tie
126
+ * goes by route id (never by table order). Negative: `a` first. */
127
+ function kit_order(a_id, a, b_id, b) {
128
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
129
+ const seg_a = a[i] ?? [EMPTY_PART];
130
+ const seg_b = b[i] ?? [EMPTY_PART];
131
+ for (let j = 0; j < Math.max(seg_a.length, seg_b.length); j++) {
132
+ const pa = seg_a[j];
133
+ const pb = seg_b[j];
134
+ if (j % 2 === 1) {
135
+ if (!pa) return -1;
136
+ if (!pb) return 1;
137
+ const next_a = seg_a[j + 1].content || a[i + 1]?.[0].content;
138
+ const next_b = seg_b[j + 1].content || b[i + 1]?.[0].content;
139
+ if (pa.type === "rest" && pb.type === "rest") {
140
+ if (next_a && !next_b) return -1;
141
+ if (next_b && !next_a) return 1;
142
+ continue;
143
+ }
144
+ if (pa.type === "rest") return next_a && !next_b ? -1 : 1;
145
+ if (pb.type === "rest") return next_b && !next_a ? 1 : -1;
146
+ if (pa.type !== pb.type) {
147
+ if (pa.type === "required") return -1;
148
+ if (pb.type === "required") return 1;
149
+ }
150
+ } else if (pa.content !== pb.content) {
151
+ if (pa === EMPTY_PART) return -1;
152
+ if (pb === EMPTY_PART) return 1;
153
+ return static_order(pa.content, pb.content);
154
+ }
155
+ }
156
+ }
157
+ return a_id < b_id ? 1 : -1;
158
+ }
159
+ /** Lexicographic, except a longer static outranks its own prefix (`foobar` before `foo`). */
160
+ function static_order(a, b) {
161
+ for (let i = 0;; i++) if (a[i] !== b[i]) {
162
+ if (a[i] === void 0) return 1;
163
+ if (b[i] === void 0) return -1;
164
+ return a[i] < b[i] ? -1 : 1;
165
+ }
84
166
  }
85
167
  /** Match one compiled pattern against a pathname. Returns params, or null if it doesn't match. */
86
168
  function match_one(c, pathname) {
@@ -98,17 +180,42 @@ function match_one(c, pathname) {
98
180
  params
99
181
  };
100
182
  }
101
- /** Fill a pattern's `[param]` / `[...rest]` tokens from a params record (URL-encoded). Shared by
102
- * `href()` (router) and the typed `api()` client — one token grammar, one filler. */
103
183
  const fill_token = /\[(\.\.\.)?\[?([a-zA-Z_$][\w$]*)\]?\]/g;
184
+ /** A segment that is one `[[optional]]` or `[...rest]` token and nothing else. */
185
+ const DROPPABLE_SEGMENT_RE = /^\[(?:\.\.\.[a-zA-Z_$][\w$]*|\[[a-zA-Z_$][\w$]*\])\]$/;
186
+ /** Fills a pattern's `[param]`, `[[optional]]` and `[...rest]` tokens from `params`, URL-encoded
187
+ * as Kit's `resolve()` writes them: a rest value keeps its `/` (each segment encoded), and an
188
+ * empty optional or rest param that is a whole segment drops that segment. A missing `[param]`
189
+ * becomes empty. Throws on a value that would fill a whole segment with `.` or `..`: every URL
190
+ * parser drops that segment, so the URL would name another route (`%2e` is read as a dot too).
191
+ * Throws on an empty segment too, other than a dropped one or the last: a rest value with an
192
+ * empty piece (a leading, trailing or doubled `/`), or a param that fills its segment empty,
193
+ * would build `//host` (a URL of another origin) or a path that routes elsewhere.
194
+ * Tests: test/property-fill-match.test.ts, test/router-match.test.ts. */
104
195
  function fill(pattern, params) {
105
- return pattern.replace(fill_token, (_m, _rest, name) => {
106
- const val = params[name];
107
- return val == null ? "" : encodeURIComponent(String(val));
108
- });
196
+ const segs = [];
197
+ const parts = pattern.split("/");
198
+ for (let i = 0; i < parts.length; i++) {
199
+ const seg = parts[i];
200
+ const out = seg.replace(fill_token, (_m, rest, name) => {
201
+ const val = params[name] == null ? "" : String(params[name]);
202
+ if (!rest) return encodeURIComponent(val);
203
+ const pieces = val.split("/");
204
+ if (val !== "" && pieces.includes("")) throw new Error(`[@ogygia/router] the rest param "${name}" has an empty segment (${JSON.stringify(val)}): it would name another URL than ${pattern}`);
205
+ return pieces.map(encodeURIComponent).join("/");
206
+ });
207
+ if (out === "" && DROPPABLE_SEGMENT_RE.test(seg)) continue;
208
+ if (out === "" && seg !== "" && i < parts.length - 1) throw new Error(`[@ogygia/router] the segment "${seg}" fills empty, an empty segment: it would name another URL than ${pattern}`);
209
+ if (out !== seg && out.split("/").some((p) => p === "." || p === "..")) throw new Error(`[@ogygia/router] the segment "${seg}" fills as ${JSON.stringify(out)}, a dot segment a URL drops: it would name another route than ${pattern}`);
210
+ segs.push(out);
211
+ }
212
+ const filled = segs.join("/");
213
+ return filled === "" && pattern !== "" ? "/" : filled;
109
214
  }
215
+ const MAX_PATH = 8192;
110
216
  /** First (most-specific) match in a pre-sorted list, or null. */
111
217
  function match_path(sorted, pathname) {
218
+ if (pathname.length > MAX_PATH) return null;
112
219
  for (const c of sorted) {
113
220
  const hit = match_one(c, pathname);
114
221
  if (hit) return hit;
package/dist/respond.d.ts CHANGED
@@ -1,8 +1,3 @@
1
- /**
2
- * Router v2 control-flow values: the throwable `redirect()` / `error()` (Kit's exact idiom — thrown
3
- * from loads, actions, and handlers) and the returnable `fail()` (Kit's action-validation shape),
4
- * plus the small Response helpers the dispatcher shares. See internal/notes/router-v2.md.
5
- */
6
1
  declare const REDIRECT: unique symbol;
7
2
  declare const HTTP_ERROR: unique symbol;
8
3
  declare const ACTION_FAILURE: unique symbol;
@@ -33,6 +28,7 @@ export declare const is_redirect: (x: unknown) => x is Redirect;
33
28
  export declare const is_http_error: (x: unknown) => x is HttpError;
34
29
  export declare const is_action_failure: (x: unknown) => x is ActionFailure;
35
30
  export declare function json_response(data: unknown, init?: ResponseInit): Response;
31
+ export declare function text_response(body: string, init?: ResponseInit): Response;
36
32
  export declare function redirect_response(status: number, location: string): Response;
37
33
  /** An endpoint/miss return → a Response: Response passes through; null/undefined → 204; else JSON. */
38
34
  export declare function finalize(out: unknown): Response;
package/dist/respond.js CHANGED
@@ -1,9 +1,4 @@
1
1
  // src/respond.ts
2
- /**
3
- * Router v2 control-flow values: the throwable `redirect()` / `error()` (Kit's exact idiom — thrown
4
- * from loads, actions, and handlers) and the returnable `fail()` (Kit's action-validation shape),
5
- * plus the small Response helpers the dispatcher shares. See internal/notes/router-v2.md.
6
- */
7
2
  const REDIRECT = Symbol.for("ogygia.router.redirect");
8
3
  const HTTP_ERROR = Symbol.for("ogygia.router.error");
9
4
  const ACTION_FAILURE = Symbol.for("ogygia.router.fail");
@@ -36,15 +31,21 @@ function fail(status, data) {
36
31
  const is_redirect = (x) => typeof x === "object" && x !== null && REDIRECT in x;
37
32
  const is_http_error = (x) => typeof x === "object" && x !== null && HTTP_ERROR in x;
38
33
  const is_action_failure = (x) => typeof x === "object" && x !== null && ACTION_FAILURE in x;
39
- function json_response(data, init) {
40
- return new Response(JSON.stringify(data), {
34
+ function with_defaults(init, defaults) {
35
+ const headers = new Headers(init?.headers);
36
+ for (const [name, value] of defaults) if (!headers.has(name)) headers.set(name, value);
37
+ return {
41
38
  ...init,
42
- headers: {
43
- "content-type": "application/json",
44
- "cache-control": "no-store",
45
- ...init?.headers
46
- }
47
- });
39
+ headers
40
+ };
41
+ }
42
+ const JSON_DEFAULTS = [["content-type", "application/json"], ["cache-control", "no-store"]];
43
+ const TEXT_DEFAULTS = [["content-type", "text/plain; charset=utf-8"]];
44
+ function json_response(data, init) {
45
+ return new Response(JSON.stringify(data), with_defaults(init, JSON_DEFAULTS));
46
+ }
47
+ function text_response(body, init) {
48
+ return new Response(body, with_defaults(init, TEXT_DEFAULTS));
48
49
  }
49
50
  function redirect_response(status, location) {
50
51
  return new Response(null, {
@@ -76,4 +77,4 @@ function options_response(allow) {
76
77
  headers: { allow: allow.join(", ") }
77
78
  });
78
79
  }
79
- export { error, fail, finalize, is_action_failure, is_http_error, is_redirect, json_response, method_not_allowed, not_found, options_response, redirect, redirect_response };
80
+ export { error, fail, finalize, is_action_failure, is_http_error, is_redirect, json_response, method_not_allowed, not_found, options_response, redirect, redirect_response, text_response };
package/dist/router.d.ts CHANGED
@@ -40,10 +40,10 @@ export interface Router<T extends TableShape = RouteTable> {
40
40
  /** `(request) => Response | null` — null on no-match (a catchall 404s its own way). */
41
41
  fetch(request: Request, event?: RequestEvent): Promise<Response | null>;
42
42
  /** Kit handle: dispatches, else falls through to the rest of the app. */
43
- handle(input: {
43
+ handle: (input: {
44
44
  event: RequestEvent;
45
45
  resolve: (e: RequestEvent) => Response | Promise<Response>;
46
- }): Promise<Response>;
46
+ }) => Promise<Response>;
47
47
  /** Rename-safe URL to a route in this table. */
48
48
  href<P extends keyof T & string>(pattern: P, ...args: HrefArgs<P>): string;
49
49
  /** The catchall crawl list (static page routes) — `export const entries = app.entries`. */
@@ -68,5 +68,12 @@ export interface Router<T extends TableShape = RouteTable> {
68
68
  * sees the entry exactly as if unwrapped.
69
69
  */
70
70
  export declare function when<T extends object>(gate: (c: Ctx) => boolean, entry: T): T;
71
+ /**
72
+ * The router: a flat table of `pattern → page()` or endpoint values, with layouts wrapped around
73
+ * page entries by `layout(...)(table)`. A request matches one entry. A page runs its loads at the
74
+ * same time (each load once per request), merges their data outermost first, and renders through
75
+ * its layouts; an endpoint runs its verb. `redirect()` and `error()` throw, `fail()` returns.
76
+ * `typeof app.$infer` types the whole table.
77
+ */
71
78
  export declare function routes<const T extends KeyedTable<T>>(typed: T, opts?: RoutesOptions): Router<T>;
72
79
  export type { Component };
package/dist/router.js CHANGED
@@ -7,7 +7,7 @@ import { request_scope } from "@ogygia/core/internal/server";
7
7
  import { document } from "@ogygia/core/server";
8
8
  import { lateSlot, openLateScope, region, registerRouteConfig, takeLateRegions } from "@ogygia/core/plugin";
9
9
  import { componentCssHead } from "@ogygia/core/plugin/css";
10
- import { escapeText } from "@ogygia/core/plugin/utils";
10
+ import { html } from "@ogygia/core/plugin/utils";
11
11
  import LayoutChain from "./LayoutChain.svelte";
12
12
  import RawHtml from "./RawHtml.svelte";
13
13
  // src/router.ts
@@ -33,6 +33,13 @@ function when(gate, entry) {
33
33
  }
34
34
  const HEAD_AS_GET = (m) => m === "HEAD" ? "GET" : m;
35
35
  const LAST_SLASH_RE = /\/$/;
36
+ /**
37
+ * The router: a flat table of `pattern → page()` or endpoint values, with layouts wrapped around
38
+ * page entries by `layout(...)(table)`. A request matches one entry. A page runs its loads at the
39
+ * same time (each load once per request), merges their data outermost first, and renders through
40
+ * its layouts; an endpoint runs its verb. `redirect()` and `error()` throw, `fail()` returns.
41
+ * `typeof app.$infer` types the whole table.
42
+ */
36
43
  function routes(typed, opts = {}) {
37
44
  const table = typed;
38
45
  const base = (opts.base ?? "").replace(LAST_SLASH_RE, "");
@@ -72,11 +79,11 @@ function routes(typed, opts = {}) {
72
79
  ...leaf.def.config
73
80
  });
74
81
  }
75
- registerRouteConfig(base + "|" + leaves.map((l) => l.pattern).join(","), (pathname) => {
82
+ registerRouteConfig(`${base}|${leaves.map((l) => l.pattern).join(",")}`, (pathname) => {
76
83
  let path = pathname;
77
84
  if (base) {
78
85
  if (path === base) path = "/";
79
- else if (path.startsWith(base + "/")) path = path.slice(base.length);
86
+ else if (path.startsWith(`${base}/`)) path = path.slice(base.length);
80
87
  else return void 0;
81
88
  }
82
89
  path = canonical_slash(path, slash) ?? path;
@@ -89,13 +96,13 @@ function routes(typed, opts = {}) {
89
96
  let path = url.pathname;
90
97
  if (base) {
91
98
  if (path === base) path = "/";
92
- else if (path.startsWith(base + "/")) path = path.slice(base.length);
99
+ else if (path.startsWith(`${base}/`)) path = path.slice(base.length);
93
100
  else return null;
94
101
  }
95
102
  const canon = canonical_slash(path, slash);
96
103
  if (canon) return new Response(null, {
97
104
  status: 308,
98
- headers: { location: base + canon + url.search }
105
+ headers: { location: on_site(base + canon) + url.search }
99
106
  });
100
107
  const hit = match_path(compiled, path);
101
108
  const unmatched = async () => {
@@ -200,7 +207,7 @@ function routes(typed, opts = {}) {
200
207
  ...node.layouts.map((l) => l.load),
201
208
  node.load
202
209
  ];
203
- const results = await Promise.all(load_defs.map((l) => l ? l(ctx) : void 0));
210
+ const results = await Promise.all(load_defs.map((l) => l ? l(ctx) : Promise.resolve(void 0)));
204
211
  const data = {};
205
212
  for (const r of results) {
206
213
  if (r instanceof Response) return r;
@@ -226,10 +233,12 @@ function routes(typed, opts = {}) {
226
233
  gen_first_html = await bake_yield(last);
227
234
  }
228
235
  }
229
- const resolved = gen_first_html !== null ? {
236
+ let resolved = node.component;
237
+ if (gen_first_html !== null) resolved = {
230
238
  __oghtml: true,
231
239
  html: lateSlot("pg", gen_first_html)
232
- } : typeof node.component === "object" && node.component !== null && "__ogpick" in node.component ? node.component.__ogpick(ctx, data) : node.component;
240
+ };
241
+ else if (typeof node.component === "object" && node.component !== null && "__ogpick" in node.component) resolved = node.component.__ogpick(ctx, data);
233
242
  const html_view = typeof resolved === "object" && resolved !== null && "__oghtml" in resolved ? resolved : null;
234
243
  const page_component = html_view ? RawHtml : resolved;
235
244
  if (html_view?.status && html_view.status >= 400) status = html_view.status;
@@ -244,7 +253,7 @@ function routes(typed, opts = {}) {
244
253
  data,
245
254
  fallback: node.fallback
246
255
  });
247
- const css_head = await componentCssHead(html_view ? chain : [...chain, page_component]) + (html_view ? (html_view.title ? `<title>${escapeText(html_view.title)}</title>` : "") + (html_view.css?.join("") ?? "") + (html_view.head ?? "") : "");
256
+ const css_head = await componentCssHead(html_view ? chain : [...chain, page_component]) + (html_view ? (html_view.title ? String(html`<title>${html_view.title}</title>`) : "") + (html_view.css?.join("") ?? "") + (html_view.head ?? "") : "");
248
257
  if (m === "GET") openLateScope();
249
258
  const res = await document(of, {
250
259
  status,
@@ -260,7 +269,9 @@ function routes(typed, opts = {}) {
260
269
  });
261
270
  if (method === "HEAD") return new Response(null, res);
262
271
  const late = takeLateRegions();
263
- const chunk_src = gen_rest && late?.length ? merge_chunks(page_slot_chunks(gen_rest), late_region_chunks(late)) : gen_rest ? page_slot_chunks(gen_rest) : late?.length ? late_region_chunks(late) : null;
272
+ const page_chunks = gen_rest ? page_slot_chunks(gen_rest) : null;
273
+ const late_chunks = late?.length ? late_region_chunks(late) : null;
274
+ const chunk_src = page_chunks && late_chunks ? merge_chunks(page_chunks, late_chunks) : page_chunks ?? late_chunks;
264
275
  if (chunk_src && m === "GET") return stream_document(await res.text(), res, until_drained(chunk_src, takeLateRegions), "pg", request_scope(ctx.request));
265
276
  return res;
266
277
  }
@@ -371,7 +382,6 @@ async function run_endpoint(node, ctx, method) {
371
382
  }
372
383
  return finalize(await e.handler(ctx));
373
384
  }
374
- /** Run a Standard Schema; issues normalized to `{ message, path }[]`. */
375
385
  async function validate(schema, input) {
376
386
  const r = await schema["~standard"].validate(input);
377
387
  if (r.issues) return { issues: r.issues.map((i) => ({
@@ -381,19 +391,27 @@ async function validate(schema, input) {
381
391
  return { value: r.value };
382
392
  }
383
393
  const TRAILING_SLASH = /\/+$/;
394
+ const LEADING_SLASHES = /^[/\\]+/;
395
+ /** A redirect target that stays on this site: exactly one leading `/` and no `\` (test:
396
+ * router-dispatch.test.ts › the trailing-slash redirect stays on the site). */
397
+ function on_site(path) {
398
+ return `/${path.replace(LEADING_SLASHES, "").replaceAll("\\", "%5C")}`;
399
+ }
384
400
  function canonical_slash(path, mode) {
385
401
  if (mode === "ignore" || path === "/") return null;
386
402
  const has = path.endsWith("/");
387
403
  if (mode === "never" && has) return path.replace(TRAILING_SLASH, "") || "/";
388
- if (mode === "always" && !has) return path + "/";
404
+ if (mode === "always" && !has) return `${path}/`;
389
405
  return null;
390
406
  }
407
+ /** The action a POST names (`?/name`), or the default when it names none. A name the page has no
408
+ * action for is a 404, as in Kit: never the default in its place (test/router-dispatch.test.ts). */
391
409
  function pick_action(node, url) {
392
410
  const actions = node.actions;
393
411
  if (!actions) return void 0;
394
412
  for (const key of url.searchParams.keys()) if (key.startsWith("/")) {
395
- const named = actions[key.slice(1)];
396
- if (named) return named;
413
+ const name = key.slice(1);
414
+ return Object.hasOwn(actions, name) ? actions[name] : () => error(404, `No action named "${name}"`);
397
415
  }
398
416
  return actions.default;
399
417
  }
package/dist/stream.d.ts CHANGED
@@ -8,13 +8,6 @@ export declare function bake_yield(v: unknown): Promise<string>;
8
8
  /** Is this page slot an async-generator function? (Svelte components are plain functions —
9
9
  * never async generators — so this discriminator needs no brand.) */
10
10
  export declare function is_stream_slot(v: unknown): v is (...args: never[]) => AsyncGenerator<unknown>;
11
- /**
12
- * Turn a fully-rendered document (first yield in place) + the generator's REMAINING yields into
13
- * a streamed Response: flush everything up to `</body>` now, append one template chunk per
14
- * later yield, then the tail. A generator throw after the flush becomes an inline error-card
15
- * chunk (the page must never end broken) — the status is already on the wire, which is
16
- * streaming's documented trade.
17
- */
18
11
  /** One late chunk headed for one slot — the multi-slot unit `stream_document` drains. */
19
12
  export interface LateChunk {
20
13
  slot: string;
@@ -22,6 +15,14 @@ export interface LateChunk {
22
15
  }
23
16
  /** Adapt a page GENERATOR's remaining yields into page-slot chunks (bake included). */
24
17
  export declare function page_slot_chunks(rest: AsyncGenerator<unknown>): AsyncGenerator<LateChunk>;
18
+ /**
19
+ * Turns a fully rendered document (first yield in place) and the remaining chunks into a streamed
20
+ * Response: everything up to `</body>` flushes now, each later chunk follows as an inert
21
+ * `<template>` that core's late boot script swaps into its slot as it parses, then the tail. The
22
+ * status and headers go out with the first flush, so a later throw cannot change them: it becomes
23
+ * an error card in `error_slot`. The stream ends when the visitor leaves (the body is cancelled)
24
+ * or `request` ends, and its chunk source is ended with it.
25
+ */
25
26
  export declare function stream_document(full_html: string, res: Response, rest: AsyncGenerator<LateChunk>, error_slot?: string, request?: Scope): Response;
26
27
  /** The in-slot failure card (message escaped) — a stream must never end broken or empty. */
27
28
  export declare function error_card_html(e: unknown): string;
package/dist/stream.js CHANGED
@@ -1,31 +1,8 @@
1
1
  import { STALE, scope } from "@ogygia/machine";
2
- import { cleanup_failed } from "@ogygia/core/internal/server";
2
+ import { body_end, cleanup_failed, head_end } from "@ogygia/core/internal/server";
3
3
  import { LATE_BOOT_SCRIPT, lateChunk } from "@ogygia/core/plugin";
4
4
  import { escapeText } from "@ogygia/core/plugin/utils";
5
5
  // src/stream.ts
6
- /**
7
- * STREAMED PAGES — `page(async function* (c, data) { yield region(...); ... })`.
8
- *
9
- * "The next state of a slot is a region" is the house law (`query.live` yields regions over the
10
- * push channel); this is the same vocabulary on the INITIAL response: the FIRST yield renders in
11
- * the document and the page flushes immediately; every later yield rides down the SAME response
12
- * as an inert `<template data-og-late>` chunk that swaps into the slot as it parses. One
13
- * connection, closed when the generator ends — no SSE, no second round trip, and no Svelte
14
- * streaming needed: each yield is an ordinary synchronous render, only the DOCUMENT is chunked.
15
- *
16
- * Islands inside late chunks need no orchestration: `<ogygia-region>` is a custom element, so
17
- * the moment swapped content lands in the DOM it upgrades, connects, and wakes on its own
18
- * schedule — the runtime never has to be told.
19
- *
20
- * Swapping is driven by ONE small classic inline script in the head (module scripts don't run
21
- * until parsing ENDS, which for a streamed document is the very thing we're not waiting for).
22
- * The slot, chunk and boot script are core's late wire (`ogygia/plugin`): core's `<Region
23
- * of={promise}>` emits the same slots and its runtime applies the same chunks. SPA navigations
24
- * fetch the COMPLETED stream, so there the runtime applies remaining templates after the body swap.
25
- *
26
- * Streaming's honest trades (documented): status/title/headers flush with the first yield — a
27
- * late error can't change an already-sent 200, and Server-Timing set after the flush is lost.
28
- */
29
6
  /** The slot id for the page position (one streamed slot per page in v1). */
30
7
  const PAGE_SLOT_ID = "pg";
31
8
  /** Bake ANY yielded value to html: a string passes through, an inline region carries its html,
@@ -47,7 +24,6 @@ async function bake_yield(v) {
47
24
  function is_stream_slot(v) {
48
25
  return Object.prototype.toString.call(v) === "[object AsyncGeneratorFunction]";
49
26
  }
50
- const HEAD_CLOSE_RE = /<\/head>/i;
51
27
  const NO_TRANSFORM_RE = /no-transform/i;
52
28
  /** Adapt a page GENERATOR's remaining yields into page-slot chunks (bake included). */
53
29
  async function* page_slot_chunks(rest) {
@@ -60,9 +36,18 @@ async function* page_slot_chunks(rest) {
60
36
  };
61
37
  }
62
38
  }
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
+ */
63
47
  function stream_document(full_html, res, rest, error_slot = "pg", request) {
64
- const with_boot = full_html.replace(HEAD_CLOSE_RE, LATE_BOOT_SCRIPT + "</head>");
65
- const cut = with_boot.lastIndexOf("</body>");
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);
66
51
  const head_part = cut === -1 ? with_boot : with_boot.slice(0, cut);
67
52
  const tail_part = cut === -1 ? "" : with_boot.slice(cut);
68
53
  const enc = new TextEncoder();
@@ -170,9 +155,6 @@ async function* until_drained(first, take) {
170
155
  end_all(sources);
171
156
  }
172
157
  }
173
- /** Ends each source (its `finally` runs once its pending step lands); one that already ended is
174
- * left as it is. Nobody waits on that ending, so a `finally` that throws is said
175
- * (`request_cleanup_failed`). */
176
158
  function end_all(sources) {
177
159
  for (const s of sources) s.return(void 0).catch(cleanup_failed);
178
160
  }
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,17 +1,23 @@
1
- import { definePlugin } from "@ogygia/core/vite";
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { definePlugin } from "@ogygia/compiler/vite";
2
4
  // src/vite.ts
5
+ const LIB_DIR = path.dirname(fileURLToPath(import.meta.url));
3
6
  /**
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`).
7
+ * The server router's plugin, listed beside `ogygia()` in vite.config. A `routes()` table renders
8
+ * pages outside Kit's routes, so nothing file-derived links their components' CSS: this tells the
9
+ * build that every module importing `@ogygia/router` is a page module, and every component it can
10
+ * reach gets its whole-tree CSS linked when it renders.
9
11
  */
10
12
  function router() {
11
13
  return definePlugin({
12
14
  name: "@ogygia/router",
13
15
  build(b) {
14
16
  b.pageModules({ importers: ["@ogygia/router"] });
17
+ b.files({
18
+ root: path.dirname(LIB_DIR),
19
+ files: [path.join(LIB_DIR, "LayoutChain.svelte")]
20
+ });
15
21
  }
16
22
  });
17
23
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ogygia/router",
3
- "version": "0.13.0",
3
+ "version": "0.15.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",
@@ -42,18 +42,19 @@
42
42
  "access": "public"
43
43
  },
44
44
  "dependencies": {
45
- "@ogygia/machine": "^0.13.0"
45
+ "@ogygia/machine": "^0.14.0"
46
46
  },
47
47
  "devDependencies": {
48
+ "@ogygia/compiler": "0.15.0",
48
49
  "@ogygia/config": "0.0.0",
49
- "@ogygia/core": "0.13.0",
50
+ "@ogygia/core": "0.15.0",
50
51
  "@ogygia/tooling": "0.0.0",
51
52
  "@playwright/test": "1.62.1",
52
53
  "@sveltejs/kit": "^2.70.2",
53
54
  "@sveltejs/vite-plugin-svelte": "^7.2.0",
54
55
  "@types/node": "^26.1.2",
55
56
  "@typescript/native": "npm:typescript@^7.0.2",
56
- "svelte": "5.56.8",
57
+ "svelte": "5.57.3",
57
58
  "svelte-check": "^4.7.4",
58
59
  "tsdown": "^0.23.4",
59
60
  "typescript": "^6.0.3",
@@ -61,7 +62,8 @@
61
62
  "vitest": "^4.1.12"
62
63
  },
63
64
  "peerDependencies": {
64
- "@ogygia/core": "^0.13.0",
65
+ "@ogygia/compiler": "^0.15.0",
66
+ "@ogygia/core": "^0.15.0",
65
67
  "@sveltejs/kit": ">=2.70.2 <4",
66
68
  "svelte": "^5.56.8"
67
69
  },