@ogygia/router 0.0.0-stage → 0.11.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.
@@ -0,0 +1,294 @@
1
+ import { Ctx } from "./ctx.js";
2
+ import { InferOutput, Params, StandardSchemaV1 } from "./view.js";
3
+ import { RouteConfig } from "@ogygia/core/plugin";
4
+ import { Component } from "svelte";
5
+ /** A per-request component chooser for `page()` — what `flag.pick({ … })` returns
6
+ * (`page(hero.pick({ control: A, bold: B }))`). Branded, not a bare function, because Svelte 5
7
+ * components ARE functions. Structural: the flags package builds the same shape without importing
8
+ * the router. */
9
+ export interface ComponentPick {
10
+ __ogpick: (c: {
11
+ request: Request;
12
+ url: URL;
13
+ }) => unknown;
14
+ }
15
+ /** TYPE helper for a pulled-out or inline load — annotate a bare function so its `c` (and `c.params`)
16
+ * are typed without the `load()` value wrapper: `const l: Load<'/docs/[slug]'> = async (c) => …`.
17
+ * Pass it straight to `page(Comp, { load: l })`. Use the `load()` VALUE wrapper only when a load must
18
+ * be SHARED across loads (`await other(c)` — memoized per request). */
19
+ export type Load<P extends string = string> = (c: Ctx<Params<P>>) => unknown;
20
+ /** TYPE helper for a pulled-out or inline action (mirrors {@link Load}). */
21
+ export type Action<P extends string = string> = (c: Ctx<Params<P>>) => unknown;
22
+ /** TYPE helper for an endpoint handler written OUTSIDE its table. `In` (a schema output) types
23
+ * `c.input` — the validated JSON body of a `POST`/`PUT`/`PATCH`. Verb-agnostic (the method doesn't
24
+ * change the ctx). Check against it with `satisfies`, which keeps the handler's own return type (the
25
+ * payload `$infer` and `api()` read): `const getPost = ((c) => …) satisfies Handler<'/p/[id]'>`.
26
+ * Inside a table nothing is needed: the key types the handler. */
27
+ export type Handler<P extends string = string, In = undefined> = (c: Ctx<Params<P>, Record<string, string>, In>) => unknown;
28
+ /** Any component. Props are a component's INPUT, so `never` props is the one shape every
29
+ * component's props can stand in for: every `Component<Props>` is assignable to this. */
30
+ export type AnyComponent = Component<never>;
31
+ /** A load is a CALLABLE, memoized per request: `await session_load(c)` runs `.run(c)` once per
32
+ * request (the memo lives on `c`), so a layout and its child sharing a load never double-fetch —
33
+ * Kit's `parent()`, generalized. `pattern` (optional) binds `c.params` AND is checked against the
34
+ * table key at assembly. `$infer` reads `Data`. `Prm`/`Srch` are the params and search its `c` was
35
+ * typed with: the page's (its key's params or its schemas' output) when written in a page's `load`
36
+ * slot, loose elsewhere. They type the call, so a loose load (a shared one) fits any page, and its
37
+ * call signature matches a bare load's — which is what lets a bare `(c) => …` in the same slot keep
38
+ * its contextual type. */
39
+ export interface LoadDef<Data = unknown, P extends string = string, Prm = LooseParams, Srch = Record<string, string>> {
40
+ (c: Ctx<Prm, Srch>): Promise<Data>;
41
+ readonly __ogload: true;
42
+ readonly pattern: P | undefined;
43
+ readonly run: (c: Ctx) => Data | Promise<Data>;
44
+ }
45
+ /** `load(fn)` / `load(pattern, fn)`. The returned function memoizes on `c` (run once per request);
46
+ * the dispatcher's concurrent branch-load pass and any `await other_load(c)` share the same promise.
47
+ * In a page's `load` slot, `load(fn)` takes the page's params through its contextual return type
48
+ * (like a verb wrapper); anywhere else they are loose. */
49
+ 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>;
50
+ export declare function load<Data, P extends string, Srch = Record<string, string>>(pattern: P, run: (c: Ctx<Params<P>, Srch>) => Data | Promise<Data>): LoadDef<Awaited<Data>, P, Params<P>, Srch>;
51
+ /** A form action def (symmetric with `load`): `action(fn)` / `action(pattern, fn)`. Returns
52
+ * `fail(...)` for validation, throws `redirect()` on success, or returns data for the `form` prop —
53
+ * Kit's action contract. `pattern` types `c.params`; `$infer` reads `Ret` into the `form` prop.
54
+ * `Prm`/`Srch` are the params and search its `c` was typed with (see {@link LoadDef}). */
55
+ export interface ActionDef<Ret = unknown, P extends string = string, Prm = LooseParams, Srch = Record<string, string>> {
56
+ (c: Ctx<Prm, Srch>): Ret | Promise<Ret>;
57
+ readonly __ogaction: true;
58
+ readonly pattern: P | undefined;
59
+ }
60
+ /** `action(fn)` / `action(pattern, fn)` — one form action. Called once on POST (no memoization).
61
+ * In a page's `actions`, `action(fn)` takes the page's params like `load(fn)` does. */
62
+ export declare function action<Ret, Prm = LooseParams, Srch = Record<string, string>>(run: (c: Ctx<Prm, Srch>) => Ret | Promise<Ret>): ActionDef<Awaited<Ret>, string, Prm, Srch>;
63
+ export declare function action<Ret, P extends string, Srch = Record<string, string>>(pattern: P, run: (c: Ctx<Params<P>, Srch>) => Ret | Promise<Ret>): ActionDef<Awaited<Ret>, P, Params<P>, Srch>;
64
+ /** Either load form `page()` / `layout()` accept: the `load()` value wrapper OR a bare typed fn. */
65
+ export type LoadInput = LoadDef | ((c: Ctx) => unknown);
66
+ 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
+ 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
+ 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
+ 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
+ type PageSearch<SS> = [SS] extends [StandardSchemaV1] ? InferOutput<SS> : Record<string, string>;
76
+ /** The `+page.server.ts`-shaped second argument to `page()`. Always an object (ruled). Route input is
77
+ * declared here (`params`/`search` schemas — coerced, typed into `c`, shown in `$infer`); `load` and
78
+ * `actions` are the behaviors (each a wrapper or a bare typed fn). Actions read `FormData` themselves
79
+ * (Kit-identical) — no action schema; typed mutation input is a `command` RF, not a form action.
80
+ * `page()` instantiates it with what it infers; the bare `PageServer` is the loose shape. */
81
+ export interface PageServer<PS = StandardSchemaV1, SS = StandardSchemaV1, Ld = LoadInput, A = Record<string, ActionInput>> {
82
+ /** Coerce + validate path params (garbage → 404); `c.params` and `App['/p']['params']` = its output. */
83
+ params?: PS;
84
+ /** Coerce + validate query (bad → 400, or lenient via `.default()`); `c.search` + `App['/p']['search']`. */
85
+ search?: SS;
86
+ load?: Ld;
87
+ actions?: A;
88
+ /** PRERENDER param sets for a DYNAMIC pattern — Kit's per-route `entries` export. Each item
89
+ * fills the pattern (`/posts/[id]` + `{ id: '1' }` → `/posts/1`) and joins the router's
90
+ * `entries()` crawl list; a dynamic page without this is skipped (crawled or SSR'd live). */
91
+ entries?: () => Array<Record<string, string>> | Promise<Array<Record<string, string>>>;
92
+ /** Kit's `config` page option, the programmatic twin of `export const config = {…}` in a
93
+ * `+page.server.ts`: plugins read their keys from it (`{ postrender: false }`). Merged like Kit's:
94
+ * `routes(table, { config })`, then each layout outermost → innermost, then the page; a later
95
+ * level replaces a key, top level only. */
96
+ config?: RouteConfig;
97
+ }
98
+ /** A page route def, generic over its layout chain / load / actions so `$infer` reads them. `L` is
99
+ * the OUTERMOST-first layout chain (empty = no chrome); the runtime prepends to it as `layout(...)()`
100
+ * wraps this entry's table. `Load`/`Actions` keep the AUTHORED form (wrapper or bare fn) for infer.
101
+ * `KeyParams` is what `page()` took from its table key (loose outside a table) — see {@link PageFor}. */
102
+ export interface PageDef<L extends readonly LayoutDef[] = readonly LayoutDef[], Load = unknown, Actions = unknown, ParamsSchema = undefined, SearchSchema = undefined, KeyParams = LooseParams> {
103
+ readonly __ogkind: "page";
104
+ /** The page component, a per-request `ComponentPick` (`page(flag.pick({...}))`), or a
105
+ * STREAMED page (`page(async function* (c, data) { … })` — see {@link StreamSlot});
106
+ * the dispatcher resolves it with the ctx. */
107
+ readonly component: AnyComponent | ComponentPick | StreamSlot;
108
+ readonly load: LoadDef | undefined;
109
+ readonly actions: Record<string, ActionDef> | undefined;
110
+ readonly params_schema?: StandardSchemaV1;
111
+ readonly search_schema?: StandardSchemaV1;
112
+ /** a deferred page's loading placeholder — the component's reserved `ogygiaFallback` slot */
113
+ readonly fallback?: AnyComponent;
114
+ /** prerender param sets for a dynamic pattern — see {@link PageServer.entries} */
115
+ readonly entries?: PageServer["entries"];
116
+ /** the page's own `config` — see {@link PageServer.config} */
117
+ readonly config?: RouteConfig;
118
+ readonly layouts: L;
119
+ /** phantom — carries the authored load/actions/schema types to `$infer`, and the key's params to
120
+ * `page()`; never read at runtime. `key` is a METHOD, so bivariant: a page built with loose params
121
+ * (outside a table, or by a plugin) fits any key. */
122
+ readonly __types?: {
123
+ load: Load;
124
+ actions: Actions;
125
+ params: ParamsSchema;
126
+ search: SearchSchema;
127
+ key(params: KeyParams): void;
128
+ };
129
+ }
130
+ /** Normalize a bare function to a memoized LoadDef; a `load()` wrapper passes through. */
131
+ export declare function to_load(input: PageLoad<never, never> | undefined): LoadDef | undefined;
132
+ /** A page slot that resolved to RAW HTML (a mounted fragment document): rendered through
133
+ * ogygia's own pure-HTML region component — no bespoke page component. `css` tags and the
134
+ * (escaped) `title` join the DOCUMENT head. */
135
+ export interface PageHtmlView {
136
+ __oghtml: true;
137
+ html: string;
138
+ css?: readonly string[];
139
+ title?: string;
140
+ /** Extra raw head markup (a mounted document's SEO/social meta — trusted federation). */
141
+ head?: string;
142
+ /** STATUS CHANNEL: `>= 400` becomes the response status — a mounted app's 404 page must
143
+ * answer 404 THROUGH the shell (a 200-wrapped error page poisons caches and SEO). */
144
+ status?: number;
145
+ }
146
+ /** THE page-slot primitive: a branded per-request resolver, run AFTER the branch's loads —
147
+ * returns the component to render, or a {@link PageHtmlView}. Everything else is sugar over
148
+ * this ONE shape: a bare component is the constant resolver, `experiment().pick()` is the
149
+ * single-arg public face (it ignores `data`), and `mount()` resolves its wire document out of
150
+ * `data` into an html view. Branded (not a bare function) because Svelte 5 components ARE
151
+ * functions. */
152
+ export interface PageSlotResolver {
153
+ __ogpick: (c: Ctx, data: Record<string, unknown>) => unknown;
154
+ }
155
+ /** A STREAMED page slot: `page(async function* (c, data) { yield fast; yield await slow; })`.
156
+ * The first yield flushes with the document; later yields ride the SAME response as template
157
+ * chunks. Yield regions or HTML strings. Params are contravariant-friendly (`never`) so any
158
+ * authored `(c, data) => AsyncGenerator<…>` fits without ceremony. */
159
+ export type StreamSlot = (c: never, data: never) => AsyncGenerator<unknown, unknown, unknown>;
160
+ /** `page(Component)` / `page(Component, { params?, search?, load?, actions? })`. The second arg mirrors
161
+ * +page.server.ts; `params`/`search` are input schemas (typed into `c` + `$infer`), `load`/`actions`
162
+ * are behaviors (wrappers or bare typed functions — see {@link Load} / {@link Action}). The
163
+ * component slot also takes a `flag.pick()`, a {@link PageSlotResolver}, or a streamed-page
164
+ * generator ({@link StreamSlot}).
165
+ *
166
+ * Inside a table, `c.params` in `load` and `actions` is the KEY's: `P` comes from the contextual
167
+ * return type ({@link PageFor}), like a verb wrapper's. A `params` schema wins over the key, and a
168
+ * `search` schema types `c.search`. Outside a table `P` stays loose. `Ld`/`A` lead with NO default:
169
+ * a slot's contextual type is then its constraint (the typed `c`) — a default would win outside a
170
+ * table and leave `c` untyped. An unwritten slot infers its constraint, which keeps the `| undefined`
171
+ * `$infer` reads as "no load" / "no actions". */
172
+ export declare function page<Ld extends PageLoad<PageParams<P, PS>, PageSearch<SS>> | undefined, A extends Record<string, PageAction<PageParams<P, PS>, PageSearch<SS>>> | undefined, P = LooseParams, PS extends StandardSchemaV1 | undefined = undefined, SS extends StandardSchemaV1 | undefined = undefined>(component: AnyComponent | ComponentPick | PageSlotResolver | StreamSlot, server?: PageServer<PS, SS, Ld, A>): PageDef<readonly [], Ld, A, PS, SS, P>;
173
+ /** A table of route defs — the value `routes()` and `layout(name, C)(...)` both take. A page is a
174
+ * `page(...)` value; an endpoint is a plain `{ GET, POST, … }` object (the `+server.ts` shape). */
175
+ export type RouteDef = AnyPageDef | Endpoint;
176
+ /** Any page def. Every PageDef parameter sits in a read-only (covariant) slot — `layouts`, and
177
+ * the phantom `__types` — so the widest of each is the type every page def is assignable to (the
178
+ * key params sit in a bivariant method, so any of them fits). */
179
+ export type AnyPageDef = PageDef<readonly LayoutDef[], unknown, unknown, unknown, unknown, unknown>;
180
+ export type RouteTable = Record<string, RouteDef>;
181
+ /** A table as `routes()` / `layout()` take it: any entries, checked by {@link KeyedTable} — which
182
+ * is what types each entry by its key. (The constraint itself stays shapeless: a handler signature
183
+ * here would be a second contextual type for every handler, and the two would cancel out.) */
184
+ export type TableShape = Record<string, object>;
185
+ /** A layout def, generic over its NAME and own LOAD (authored form) so `$infer` can key
186
+ * `App['(name)']` and merge its data into the chains that contain it. */
187
+ export interface LayoutDef<Name extends string = string, Load = unknown> {
188
+ readonly __ogkind: "layout";
189
+ readonly name: Name;
190
+ readonly component: AnyComponent;
191
+ readonly load: LoadDef | undefined;
192
+ readonly error?: AnyComponent;
193
+ /** `config` for every page under this layout (a deeper layout's or the page's own key wins) */
194
+ readonly config?: RouteConfig;
195
+ /** phantom — carries the authored load type to `$infer`; never read at runtime */
196
+ readonly __loadType?: Load;
197
+ }
198
+ /** Prepend a layout to one entry's chain, preserving all generics (endpoints pass through). */
199
+ 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
+ export interface LayoutFn<Def extends LayoutDef> {
201
+ readonly __oglayout: Def;
202
+ <const T extends KeyedTable<T>>(table: T): NoInfer<{ [K in keyof T]: WithLayout<T[K], Def>; }>;
203
+ }
204
+ /** `layout(name, Component, { load?, error?, config? })` — a named table→table wrapper. Applying it PREPENDS
205
+ * this layout to every entry's chain and returns a table with the SAME KEYS, so `...admin({...})`
206
+ * spreads the tagged entries into the parent (a wrapped table nested in another accumulates the
207
+ * chain — Kit's nested layouts). `load` may be a `load()` wrapper or a bare typed fn. The name keys
208
+ * the layout's `{ data, children }` type as `App['(name)']`; duplicate names are a build error. */
209
+ export declare function layout<Name extends string, S extends {
210
+ load?: LoadInput;
211
+ error?: AnyComponent;
212
+ config?: RouteConfig;
213
+ }>(name: Name, component: AnyComponent, opts?: S): LayoutFn<LayoutDef<Name, S["load"]>>;
214
+ /** A verb entry produced by the `GET`/`POST`/… value wrappers — a handler plus (for body verbs) a
215
+ * body schema (`POST(schema, fn)`). Symmetric with `load()`/`action()`. `Out`/`In`/`P` are PHANTOM
216
+ * types for `$infer` + the typed `api()` client: a PLAIN return is the endpoint's JSON payload
217
+ * (finalize() serializes it), a `Response` return erases to `unknown`; `In` is the body schema's
218
+ * output; `P` the params the handler was typed with (its table key's, inside a table). */
219
+ export interface VerbEntry<Out = unknown, In = undefined, P = unknown> {
220
+ readonly __ogverb: true;
221
+ readonly handler: (c: Ctx) => unknown;
222
+ readonly bodySchema?: StandardSchemaV1;
223
+ /** phantom — never read at runtime */
224
+ readonly __types?: {
225
+ out: Out;
226
+ in: In;
227
+ params: P;
228
+ };
229
+ }
230
+ /** Params a handler sees with no table key to type them (a wrapper outside a table): indexable. */
231
+ type LooseParams = Record<string, string | undefined>;
232
+ /** One verb slot of an endpoint object, as `RouteTable` accepts it: any handler, or a verb wrapper.
233
+ * What a slot's `c` IS comes from its table key ({@link KeyedTable}). */
234
+ export type VerbSlot = ((c: never) => unknown) | VerbEntry<unknown, unknown, unknown>;
235
+ /** An endpoint route entry — the `+server.ts` shape, as an object of uppercase verb slots. Each verb
236
+ * is a bare handler or a verb wrapper. Distinguished from a page by having no `__ogkind`. */
237
+ export interface Endpoint {
238
+ GET?: VerbSlot;
239
+ DELETE?: VerbSlot;
240
+ HEAD?: VerbSlot;
241
+ OPTIONS?: VerbSlot;
242
+ POST?: VerbSlot;
243
+ PUT?: VerbSlot;
244
+ PATCH?: VerbSlot;
245
+ }
246
+ /** The endpoint a table KEY types: every verb's `c.params` is that key's params, a bare handler's
247
+ * and a wrapper's alike (the wrapper takes them through its contextual return type). */
248
+ export type EndpointFor<K extends string> = { [V in (typeof VERBS)[number]]?: Handler<K> | VerbEntry<unknown, unknown, Params<K>>; };
249
+ /** The page a table KEY types: `page()` takes `Params<K>` from it through its contextual return type,
250
+ * so its `load` and `actions` read the key's params. Any page def fits (the slot is bivariant). */
251
+ export type PageFor<K extends string> = PageDef<readonly LayoutDef[], unknown, unknown, unknown, unknown, Params<K>>;
252
+ /** What `routes()` and `layout()` check a table against: each entry typed by its own key, so
253
+ * `'/posts/[id]': { GET: (c) => c.params.id }` and `'/posts/[id]': page(Post, { load: (c) =>
254
+ * c.params.id })` read a STRICT `id` and keep their return types — no pattern restated.
255
+ *
256
+ * It is the table's own CONSTRAINT (`<const T extends KeyedTable<T>>(table: T)`), never intersected
257
+ * with the table: the constraint depends on the keys alone, so it is a complete contextual type even
258
+ * while the entries are being inferred — a wrapper (`GET(fn)`, `page(C, { load })`, `when(gate,
259
+ * entry)`, a spread `layout()`) reads its key's params through it. No condition on an ENTRY here for the same reason:
260
+ * a type that waits on the entry gives its handlers no contextual type at all. */
261
+ export type KeyedTable<T> = { [K in keyof T]: EndpointFor<K & string> | PageFor<K & string>; };
262
+ declare const VERBS: readonly ["GET", "DELETE", "HEAD", "OPTIONS", "POST", "PUT", "PATCH"];
263
+ /** `GET(handler)` — a verb wrapper for a GET slot (no body, so no schema). Inside a table its
264
+ * `c.params` are the key's; a bare `{ GET: (c) => … }` is the same thing — the wrapper exists for
265
+ * symmetry with the body verbs. */
266
+ export declare function GET<P = LooseParams, R = unknown>(handler: (c: Ctx<P>) => R): VerbEntry<Awaited<R>, undefined, P>;
267
+ /** `DELETE(handler)` — a verb wrapper for a DELETE slot (no body schema). */
268
+ export declare function DELETE<P = LooseParams, R = unknown>(handler: (c: Ctx<P>) => R): VerbEntry<Awaited<R>, undefined, P>;
269
+ /** `POST(handler)` / `POST(bodySchema, handler)` — a POST slot. The schema validates the JSON body
270
+ * into `c.input` (400 on failure), like a `command` RF's typed argument. */
271
+ export declare function POST<P = LooseParams, R = unknown>(handler: (c: Ctx<P>) => R): VerbEntry<Awaited<R>, undefined, P>;
272
+ export declare function POST<Sch extends StandardSchemaV1, P = LooseParams, R = unknown>(schema: Sch, handler: (c: Ctx<P, Record<string, string>, InferOutput<Sch>>) => R): VerbEntry<Awaited<R>, InferOutput<Sch>, P>;
273
+ /** `PUT(handler)` / `PUT(bodySchema, handler)`. */
274
+ export declare function PUT<P = LooseParams, R = unknown>(handler: (c: Ctx<P>) => R): VerbEntry<Awaited<R>, undefined, P>;
275
+ export declare function PUT<Sch extends StandardSchemaV1, P = LooseParams, R = unknown>(schema: Sch, handler: (c: Ctx<P, Record<string, string>, InferOutput<Sch>>) => R): VerbEntry<Awaited<R>, InferOutput<Sch>, P>;
276
+ /** `PATCH(handler)` / `PATCH(bodySchema, handler)`. */
277
+ export declare function PATCH<P = LooseParams, R = unknown>(handler: (c: Ctx<P>) => R): VerbEntry<Awaited<R>, undefined, P>;
278
+ export declare function PATCH<Sch extends StandardSchemaV1, P = LooseParams, R = unknown>(schema: Sch, handler: (c: Ctx<P, Record<string, string>, InferOutput<Sch>>) => R): VerbEntry<Awaited<R>, InferOutput<Sch>, P>;
279
+ /** Normalized runtime shape the dispatcher reads (built once by routes() from the Endpoint object). */
280
+ export interface MethodEntry {
281
+ handler: (c: Ctx) => unknown;
282
+ bodySchema?: StandardSchemaV1;
283
+ }
284
+ export interface EndpointDef {
285
+ readonly __ogkind: "endpoint";
286
+ readonly methods: Map<string, MethodEntry>;
287
+ }
288
+ export declare const is_page: (d: unknown) => d is PageDef;
289
+ /** An endpoint object: not a page, and carries at least one uppercase verb slot. */
290
+ export declare function is_endpoint_object(d: RouteDef): d is Endpoint;
291
+ /** Compile an `{ GET, POST, … }` endpoint object into the dispatcher's method map — a bare handler,
292
+ * or a `GET(...)`/`POST(...)` wrapper (unwrapped to its handler + optional body schema). */
293
+ export declare function compile_endpoint(ep: Endpoint): EndpointDef;
294
+ export {};
package/dist/define.js ADDED
@@ -0,0 +1,159 @@
1
+ // src/define.ts
2
+ function memo_of(c) {
3
+ const holder = c;
4
+ return holder.__ogloads ??= /* @__PURE__ */ new Map();
5
+ }
6
+ function load(a, b) {
7
+ const pattern = typeof a === "string" ? a : void 0;
8
+ const run = typeof a === "string" ? b : a;
9
+ const fn = ((c) => {
10
+ const memo = memo_of(c);
11
+ let p = memo.get(fn);
12
+ if (!p) {
13
+ p = Promise.resolve(run(c));
14
+ memo.set(fn, p);
15
+ }
16
+ return p;
17
+ });
18
+ fn.__ogload = true;
19
+ fn.pattern = pattern;
20
+ fn.run = run;
21
+ return fn;
22
+ }
23
+ function action(a, b) {
24
+ const pattern = typeof a === "string" ? a : void 0;
25
+ const run = typeof a === "string" ? b : a;
26
+ const fn = ((c) => run(c));
27
+ fn.__ogaction = true;
28
+ fn.pattern = pattern;
29
+ return fn;
30
+ }
31
+ /** Normalize a bare function to a memoized LoadDef; a `load()` wrapper passes through. */
32
+ function to_load(input) {
33
+ if (!input) return void 0;
34
+ if (input.__ogload) return input;
35
+ return load(input);
36
+ }
37
+ /** Normalize a bare function to an ActionDef; an `action()` wrapper passes through. Both take the
38
+ * widest input (`never` params/search: a load typed for any page fits). */
39
+ function to_action(input) {
40
+ if (input.__ogaction) return input;
41
+ return action(input);
42
+ }
43
+ /** `page(Component)` / `page(Component, { params?, search?, load?, actions? })`. The second arg mirrors
44
+ * +page.server.ts; `params`/`search` are input schemas (typed into `c` + `$infer`), `load`/`actions`
45
+ * are behaviors (wrappers or bare typed functions — see {@link Load} / {@link Action}). The
46
+ * component slot also takes a `flag.pick()`, a {@link PageSlotResolver}, or a streamed-page
47
+ * generator ({@link StreamSlot}).
48
+ *
49
+ * Inside a table, `c.params` in `load` and `actions` is the KEY's: `P` comes from the contextual
50
+ * return type ({@link PageFor}), like a verb wrapper's. A `params` schema wins over the key, and a
51
+ * `search` schema types `c.search`. Outside a table `P` stays loose. `Ld`/`A` lead with NO default:
52
+ * a slot's contextual type is then its constraint (the typed `c`) — a default would win outside a
53
+ * table and leave `c` untyped. An unwritten slot infers its constraint, which keeps the `| undefined`
54
+ * `$infer` reads as "no load" / "no actions". */
55
+ function page(component, server) {
56
+ const actions = server?.actions ? Object.fromEntries(Object.entries(server.actions).map(([k, v]) => [k, to_action(v)])) : void 0;
57
+ return {
58
+ __ogkind: "page",
59
+ component,
60
+ load: to_load(server?.load),
61
+ actions,
62
+ params_schema: server?.params,
63
+ search_schema: server?.search,
64
+ entries: server?.entries,
65
+ config: server?.config,
66
+ layouts: []
67
+ };
68
+ }
69
+ /** `layout(name, Component, { load?, error?, config? })` — a named table→table wrapper. Applying it PREPENDS
70
+ * this layout to every entry's chain and returns a table with the SAME KEYS, so `...admin({...})`
71
+ * spreads the tagged entries into the parent (a wrapped table nested in another accumulates the
72
+ * chain — Kit's nested layouts). `load` may be a `load()` wrapper or a bare typed fn. The name keys
73
+ * the layout's `{ data, children }` type as `App['(name)']`; duplicate names are a build error. */
74
+ function layout(name, component, opts) {
75
+ const def = {
76
+ __ogkind: "layout",
77
+ name,
78
+ component,
79
+ load: to_load(opts?.load),
80
+ error: opts?.error,
81
+ config: opts?.config
82
+ };
83
+ const fn = ((table) => {
84
+ const out = {};
85
+ for (const key in table) {
86
+ const entry = table[key];
87
+ out[key] = is_page(entry) ? {
88
+ ...entry,
89
+ layouts: [def, ...entry.layouts]
90
+ } : entry;
91
+ }
92
+ return out;
93
+ });
94
+ fn.__oglayout = def;
95
+ return fn;
96
+ }
97
+ const VERBS = [
98
+ "GET",
99
+ "DELETE",
100
+ "HEAD",
101
+ "OPTIONS",
102
+ "POST",
103
+ "PUT",
104
+ "PATCH"
105
+ ];
106
+ const verb_entry = (handler, bodySchema) => ({
107
+ __ogverb: true,
108
+ handler,
109
+ bodySchema
110
+ });
111
+ /** `GET(handler)` — a verb wrapper for a GET slot (no body, so no schema). Inside a table its
112
+ * `c.params` are the key's; a bare `{ GET: (c) => … }` is the same thing — the wrapper exists for
113
+ * symmetry with the body verbs. */
114
+ function GET(handler) {
115
+ return verb_entry(handler);
116
+ }
117
+ /** `DELETE(handler)` — a verb wrapper for a DELETE slot (no body schema). */
118
+ function DELETE(handler) {
119
+ return verb_entry(handler);
120
+ }
121
+ function POST(a, b) {
122
+ return body_verb(a, b);
123
+ }
124
+ function PUT(a, b) {
125
+ return body_verb(a, b);
126
+ }
127
+ function PATCH(a, b) {
128
+ return body_verb(a, b);
129
+ }
130
+ function body_verb(a, b) {
131
+ return b === void 0 ? verb_entry(a) : verb_entry(b, a);
132
+ }
133
+ const is_page = (d) => d.__ogkind === "page";
134
+ /** An endpoint object: not a page, and carries at least one uppercase verb slot. */
135
+ function is_endpoint_object(d) {
136
+ if (is_page(d) || typeof d !== "object" || d === null) return false;
137
+ return VERBS.some((v) => v in d);
138
+ }
139
+ /** Compile an `{ GET, POST, … }` endpoint object into the dispatcher's method map — a bare handler,
140
+ * or a `GET(...)`/`POST(...)` wrapper (unwrapped to its handler + optional body schema). */
141
+ function compile_endpoint(ep) {
142
+ const methods = /* @__PURE__ */ new Map();
143
+ for (const verb of VERBS) {
144
+ const v = ep[verb];
145
+ if (v == null) continue;
146
+ if (v.__ogverb) {
147
+ const e = v;
148
+ methods.set(verb, {
149
+ handler: e.handler,
150
+ bodySchema: e.bodySchema
151
+ });
152
+ } else methods.set(verb, { handler: v });
153
+ }
154
+ return {
155
+ __ogkind: "endpoint",
156
+ methods
157
+ };
158
+ }
159
+ export { DELETE, GET, PATCH, POST, PUT, action, compile_endpoint, is_endpoint_object, is_page, layout, load, page, to_load };
@@ -0,0 +1,10 @@
1
+ import { Router, RoutesOptions, routes, when } from "./router.js";
2
+ import { Action, ActionDef, AnyComponent, ComponentPick, DELETE, Endpoint, GET, Handler, LayoutDef, Load, LoadDef, PATCH, POST, PUT, PageDef, PageServer, RouteTable, VerbEntry, action, layout, load, page } from "./define.js";
3
+ import { ActionFailure, error, fail, is_http_error, is_redirect, redirect } from "./respond.js";
4
+ import { Ctx } from "./ctx.js";
5
+ import { InferMap } from "./infer.js";
6
+ import { HrefArgs, HrefParams, InferOutput, Params, Simplify, StandardSchemaV1 } from "./view.js";
7
+ import { CompiledPattern, compile, match_path } from "./match.js";
8
+ import { AnonymousVisitorOptions, anonymousVisitor } from "./visitor.js";
9
+ import { ApiClient, ApiClientOptions, ApiError, api } from "./client-api.js";
10
+ export { type Action, type ActionDef, type ActionFailure, type AnonymousVisitorOptions, type AnyComponent, type ApiClient, type ApiClientOptions, ApiError, type CompiledPattern, type ComponentPick, type Ctx, DELETE, type Endpoint, GET, type Handler, type HrefArgs, type HrefParams, type InferMap, type InferOutput, type LayoutDef, type Load, type LoadDef, PATCH, POST, PUT, type PageDef, type PageServer, type Params, type RouteTable, type Router, type RoutesOptions, type Simplify, type StandardSchemaV1, type VerbEntry, action, anonymousVisitor, api, compile, error, fail, is_http_error as isHttpError, is_redirect as isRedirect, layout, load, match_path, page, redirect, routes, when };
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import { routes, when } from "./router.js";
2
+ import { DELETE, GET, PATCH, POST, PUT, action, layout, load, page } from "./define.js";
3
+ import { error, fail, is_http_error, is_redirect, redirect } from "./respond.js";
4
+ import { compile, match_path } from "./match.js";
5
+ import { anonymousVisitor } from "./visitor.js";
6
+ import { ApiError, api } from "./client-api.js";
7
+ export { ApiError, DELETE, GET, PATCH, POST, PUT, action, anonymousVisitor, api, compile, error, fail, is_http_error as isHttpError, is_redirect as isRedirect, layout, load, match_path, page, redirect, routes, when };
@@ -0,0 +1,64 @@
1
+ import { AnyPageDef, LayoutDef, LoadDef, PageDef, TableShape, VerbEntry } from "./define.js";
2
+ import { ActionFailure } from "./respond.js";
3
+ import { InferOutput, Params, Simplify, StandardSchemaV1 } from "./view.js";
4
+ import { Snippet } from "svelte";
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
+ 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>> : {};
13
+ type LayoutData<L> = L extends LayoutDef<string, infer LD> ? DataOf<LD> : {};
14
+ /** Merge a layout chain's data (outermost-first) — the whole tuple. */
15
+ type ChainData<Ls extends readonly LayoutDef[]> = Ls extends readonly [infer H, ...infer R] ? LayoutData<H> & (R extends readonly LayoutDef[] ? ChainData<R> : {}) : {};
16
+ type Layouts<V> = V extends PageDef<infer L, unknown, unknown, unknown, unknown> ? L : readonly [];
17
+ type LoadType<V> = V extends PageDef<readonly LayoutDef[], infer Load, unknown, unknown, unknown> ? Load : undefined;
18
+ type ActionsType<V> = V extends PageDef<readonly LayoutDef[], unknown, infer A, unknown, unknown> ? A : undefined;
19
+ type ParamsSchemaType<V> = V extends PageDef<readonly LayoutDef[], unknown, unknown, infer PS, unknown> ? PS : undefined;
20
+ 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
+ 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
+ type ActionData<R> = R extends ActionFailure<infer F> ? F : R;
26
+ 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
+ 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
+ type SearchOf<V> = SearchSchemaType<V> extends StandardSchemaV1 ? InferOutput<SearchSchemaType<V>> : {};
31
+ /** Page entries: `{ [path]: { data, form, params, search } }` for every PageDef key. */
32
+ type PageEntries<T> = { [K in keyof T & string as T[K] extends AnyPageDef ? K : never]: T[K] extends AnyPageDef ? {
33
+ data: Simplify<PageData<T[K]>>;
34
+ form: FormOf<T[K]>;
35
+ params: Simplify<ParamsOf<K, T[K]>>;
36
+ search: Simplify<SearchOf<T[K]>>;
37
+ } : 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>>;
42
+ 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). */
45
+ 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
+ type PayloadOf<R> = [R] extends [never] ? unknown : R extends Response ? unknown : R;
49
+ type SlotOut<H> = H extends VerbEntry<infer O, unknown> ? PayloadOf<O> : H extends ((c: never) => infer R) ? PayloadOf<Awaited<R>> : unknown;
50
+ type SlotIn<H> = H extends VerbEntry<unknown, infer I> ? I : undefined;
51
+ type SlotEntry<H> = {
52
+ out: SlotOut<H>;
53
+ in: SlotIn<H>;
54
+ };
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
+ type EndpointVerbs<V> = { [M in keyof V & string as V[M] extends undefined ? never : Lowercase<M>]: SlotEntry<V[M]>; };
59
+ 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
+ params: Simplify<Params<K>>;
61
+ }>; };
62
+ /** The full `$infer` map: page paths ⊕ endpoint paths ⊕ layout `(name)`s. */
63
+ export type InferMap<T extends TableShape> = Simplify<PageEntries<T> & EndpointEntries<T> & AllLayoutEntries<T>>;
64
+ export {};
package/dist/infer.js ADDED
File without changes
@@ -0,0 +1,37 @@
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
+ export interface ParamSpec {
12
+ name: string;
13
+ /** `[...rest]` — captures the remaining path (slashes included), may be '' */
14
+ rest?: boolean;
15
+ /** `[[opt]]` — the segment may be absent; param is `undefined` when so */
16
+ optional?: boolean;
17
+ }
18
+ export interface CompiledPattern {
19
+ /** the original table key, e.g. '/docs/[slug]' — also the route.id we expose */
20
+ pattern: string;
21
+ regex: RegExp;
22
+ params: ParamSpec[];
23
+ /** higher = more specific; used to order overlapping matches (static beats dynamic) */
24
+ score: number;
25
+ }
26
+ export declare function compile(pattern: string): CompiledPattern;
27
+ /** Compile a whole table's keys and sort most-specific-first, so the first match wins. */
28
+ export declare function compile_all(patterns: string[]): CompiledPattern[];
29
+ export interface PathMatch {
30
+ pattern: string;
31
+ params: Record<string, string | undefined>;
32
+ }
33
+ /** Match one compiled pattern against a pathname. Returns params, or null if it doesn't match. */
34
+ export declare function match_one(c: CompiledPattern, pathname: string): PathMatch | null;
35
+ export declare function fill(pattern: string, params: Record<string, string | number>): string;
36
+ /** First (most-specific) match in a pre-sorted list, or null. */
37
+ export declare function match_path(sorted: CompiledPattern[], pathname: string): PathMatch | null;