@ogygia/router 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/LayoutChain.svelte +2 -18
- package/dist/LayoutChain.svelte.d.ts +11 -18
- package/dist/RawHtml.svelte +1 -5
- package/dist/client-api.d.ts +9 -3
- package/dist/client-api.js +18 -25
- package/dist/ctx.d.ts +3 -1
- package/dist/ctx.js +3 -9
- package/dist/define.d.ts +2 -7
- package/dist/define.js +30 -12
- package/dist/infer.d.ts +12 -25
- package/dist/match.d.ts +16 -13
- package/dist/match.js +156 -49
- package/dist/respond.d.ts +1 -5
- package/dist/respond.js +15 -14
- package/dist/router.d.ts +9 -2
- package/dist/router.js +35 -16
- package/dist/stream.d.ts +22 -8
- package/dist/stream.js +98 -49
- package/dist/view.d.ts +2 -2
- package/dist/visitor.d.ts +10 -0
- package/dist/visitor.js +11 -13
- package/dist/vite.d.ts +7 -1
- package/dist/vite.js +5 -6
- package/package.json +11 -4
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
|
-
|
|
7
|
-
const
|
|
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
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
|
40
|
-
|
|
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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
-
})
|
|
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
|
@@ -2,11 +2,12 @@ import { compile_all, fill, match_path } from "./match.js";
|
|
|
2
2
|
import { make_ctx } from "./ctx.js";
|
|
3
3
|
import { compile_endpoint, is_page, to_load } from "./define.js";
|
|
4
4
|
import { error, finalize, is_action_failure, is_http_error, is_redirect, json_response, method_not_allowed, not_found, options_response, redirect_response } from "./respond.js";
|
|
5
|
-
import { bake_yield, is_stream_slot, late_region_chunks, merge_chunks, page_slot_chunks, stream_document } from "./stream.js";
|
|
5
|
+
import { bake_yield, is_stream_slot, late_region_chunks, merge_chunks, page_slot_chunks, stream_document, until_drained } from "./stream.js";
|
|
6
|
+
import { request_scope } from "@ogygia/core/internal/server";
|
|
6
7
|
import { document } from "@ogygia/core/server";
|
|
7
8
|
import { lateSlot, openLateScope, region, registerRouteConfig, takeLateRegions } from "@ogygia/core/plugin";
|
|
8
9
|
import { componentCssHead } from "@ogygia/core/plugin/css";
|
|
9
|
-
import {
|
|
10
|
+
import { html } from "@ogygia/core/plugin/utils";
|
|
10
11
|
import LayoutChain from "./LayoutChain.svelte";
|
|
11
12
|
import RawHtml from "./RawHtml.svelte";
|
|
12
13
|
// src/router.ts
|
|
@@ -32,6 +33,13 @@ function when(gate, entry) {
|
|
|
32
33
|
}
|
|
33
34
|
const HEAD_AS_GET = (m) => m === "HEAD" ? "GET" : m;
|
|
34
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
|
+
*/
|
|
35
43
|
function routes(typed, opts = {}) {
|
|
36
44
|
const table = typed;
|
|
37
45
|
const base = (opts.base ?? "").replace(LAST_SLASH_RE, "");
|
|
@@ -71,11 +79,11 @@ function routes(typed, opts = {}) {
|
|
|
71
79
|
...leaf.def.config
|
|
72
80
|
});
|
|
73
81
|
}
|
|
74
|
-
registerRouteConfig(base
|
|
82
|
+
registerRouteConfig(`${base}|${leaves.map((l) => l.pattern).join(",")}`, (pathname) => {
|
|
75
83
|
let path = pathname;
|
|
76
84
|
if (base) {
|
|
77
85
|
if (path === base) path = "/";
|
|
78
|
-
else if (path.startsWith(base
|
|
86
|
+
else if (path.startsWith(`${base}/`)) path = path.slice(base.length);
|
|
79
87
|
else return void 0;
|
|
80
88
|
}
|
|
81
89
|
path = canonical_slash(path, slash) ?? path;
|
|
@@ -88,13 +96,13 @@ function routes(typed, opts = {}) {
|
|
|
88
96
|
let path = url.pathname;
|
|
89
97
|
if (base) {
|
|
90
98
|
if (path === base) path = "/";
|
|
91
|
-
else if (path.startsWith(base
|
|
99
|
+
else if (path.startsWith(`${base}/`)) path = path.slice(base.length);
|
|
92
100
|
else return null;
|
|
93
101
|
}
|
|
94
102
|
const canon = canonical_slash(path, slash);
|
|
95
103
|
if (canon) return new Response(null, {
|
|
96
104
|
status: 308,
|
|
97
|
-
headers: { location: base + canon + url.search }
|
|
105
|
+
headers: { location: on_site(base + canon) + url.search }
|
|
98
106
|
});
|
|
99
107
|
const hit = match_path(compiled, path);
|
|
100
108
|
const unmatched = async () => {
|
|
@@ -199,7 +207,7 @@ function routes(typed, opts = {}) {
|
|
|
199
207
|
...node.layouts.map((l) => l.load),
|
|
200
208
|
node.load
|
|
201
209
|
];
|
|
202
|
-
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)));
|
|
203
211
|
const data = {};
|
|
204
212
|
for (const r of results) {
|
|
205
213
|
if (r instanceof Response) return r;
|
|
@@ -225,10 +233,12 @@ function routes(typed, opts = {}) {
|
|
|
225
233
|
gen_first_html = await bake_yield(last);
|
|
226
234
|
}
|
|
227
235
|
}
|
|
228
|
-
|
|
236
|
+
let resolved = node.component;
|
|
237
|
+
if (gen_first_html !== null) resolved = {
|
|
229
238
|
__oghtml: true,
|
|
230
239
|
html: lateSlot("pg", gen_first_html)
|
|
231
|
-
}
|
|
240
|
+
};
|
|
241
|
+
else if (typeof node.component === "object" && node.component !== null && "__ogpick" in node.component) resolved = node.component.__ogpick(ctx, data);
|
|
232
242
|
const html_view = typeof resolved === "object" && resolved !== null && "__oghtml" in resolved ? resolved : null;
|
|
233
243
|
const page_component = html_view ? RawHtml : resolved;
|
|
234
244
|
if (html_view?.status && html_view.status >= 400) status = html_view.status;
|
|
@@ -243,7 +253,7 @@ function routes(typed, opts = {}) {
|
|
|
243
253
|
data,
|
|
244
254
|
fallback: node.fallback
|
|
245
255
|
});
|
|
246
|
-
const css_head = await componentCssHead(html_view ? chain : [...chain, page_component]) + (html_view ? (html_view.title ? `<title>${
|
|
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 ?? "") : "");
|
|
247
257
|
if (m === "GET") openLateScope();
|
|
248
258
|
const res = await document(of, {
|
|
249
259
|
status,
|
|
@@ -259,8 +269,10 @@ function routes(typed, opts = {}) {
|
|
|
259
269
|
});
|
|
260
270
|
if (method === "HEAD") return new Response(null, res);
|
|
261
271
|
const late = takeLateRegions();
|
|
262
|
-
const
|
|
263
|
-
|
|
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;
|
|
275
|
+
if (chunk_src && m === "GET") return stream_document(await res.text(), res, until_drained(chunk_src, takeLateRegions), "pg", request_scope(ctx.request));
|
|
264
276
|
return res;
|
|
265
277
|
}
|
|
266
278
|
async function handle_thrown(thrown, def, ctx) {
|
|
@@ -370,7 +382,6 @@ async function run_endpoint(node, ctx, method) {
|
|
|
370
382
|
}
|
|
371
383
|
return finalize(await e.handler(ctx));
|
|
372
384
|
}
|
|
373
|
-
/** Run a Standard Schema; issues normalized to `{ message, path }[]`. */
|
|
374
385
|
async function validate(schema, input) {
|
|
375
386
|
const r = await schema["~standard"].validate(input);
|
|
376
387
|
if (r.issues) return { issues: r.issues.map((i) => ({
|
|
@@ -380,19 +391,27 @@ async function validate(schema, input) {
|
|
|
380
391
|
return { value: r.value };
|
|
381
392
|
}
|
|
382
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
|
+
}
|
|
383
400
|
function canonical_slash(path, mode) {
|
|
384
401
|
if (mode === "ignore" || path === "/") return null;
|
|
385
402
|
const has = path.endsWith("/");
|
|
386
403
|
if (mode === "never" && has) return path.replace(TRAILING_SLASH, "") || "/";
|
|
387
|
-
if (mode === "always" && !has) return path
|
|
404
|
+
if (mode === "always" && !has) return `${path}/`;
|
|
388
405
|
return null;
|
|
389
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). */
|
|
390
409
|
function pick_action(node, url) {
|
|
391
410
|
const actions = node.actions;
|
|
392
411
|
if (!actions) return void 0;
|
|
393
412
|
for (const key of url.searchParams.keys()) if (key.startsWith("/")) {
|
|
394
|
-
const
|
|
395
|
-
|
|
413
|
+
const name = key.slice(1);
|
|
414
|
+
return Object.hasOwn(actions, name) ? actions[name] : () => error(404, `No action named "${name}"`);
|
|
396
415
|
}
|
|
397
416
|
return actions.default;
|
|
398
417
|
}
|
package/dist/stream.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Scope } from "@ogygia/machine";
|
|
1
2
|
/** The slot id for the page position (one streamed slot per page in v1). */
|
|
2
3
|
export declare const PAGE_SLOT_ID = "pg";
|
|
3
4
|
/** Bake ANY yielded value to html: a string passes through, an inline region carries its html,
|
|
@@ -7,13 +8,6 @@ export declare function bake_yield(v: unknown): Promise<string>;
|
|
|
7
8
|
/** Is this page slot an async-generator function? (Svelte components are plain functions —
|
|
8
9
|
* never async generators — so this discriminator needs no brand.) */
|
|
9
10
|
export declare function is_stream_slot(v: unknown): v is (...args: never[]) => AsyncGenerator<unknown>;
|
|
10
|
-
/**
|
|
11
|
-
* Turn a fully-rendered document (first yield in place) + the generator's REMAINING yields into
|
|
12
|
-
* a streamed Response: flush everything up to `</body>` now, append one template chunk per
|
|
13
|
-
* later yield, then the tail. A generator throw after the flush becomes an inline error-card
|
|
14
|
-
* chunk (the page must never end broken) — the status is already on the wire, which is
|
|
15
|
-
* streaming's documented trade.
|
|
16
|
-
*/
|
|
17
11
|
/** One late chunk headed for one slot — the multi-slot unit `stream_document` drains. */
|
|
18
12
|
export interface LateChunk {
|
|
19
13
|
slot: string;
|
|
@@ -21,7 +15,15 @@ export interface LateChunk {
|
|
|
21
15
|
}
|
|
22
16
|
/** Adapt a page GENERATOR's remaining yields into page-slot chunks (bake included). */
|
|
23
17
|
export declare function page_slot_chunks(rest: AsyncGenerator<unknown>): AsyncGenerator<LateChunk>;
|
|
24
|
-
|
|
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
|
+
*/
|
|
26
|
+
export declare function stream_document(full_html: string, res: Response, rest: AsyncGenerator<LateChunk>, error_slot?: string, request?: Scope): Response;
|
|
25
27
|
/** The in-slot failure card (message escaped) — a stream must never end broken or empty. */
|
|
26
28
|
export declare function error_card_html(e: unknown): string;
|
|
27
29
|
/** Drain registered LATE REGIONS (`<Region of={promise}>` holes) in COMPLETION order — the slot
|
|
@@ -31,6 +33,18 @@ export declare function late_region_chunks(list: ReadonlyArray<{
|
|
|
31
33
|
id: string;
|
|
32
34
|
promise: Promise<unknown>;
|
|
33
35
|
}>): AsyncGenerator<LateChunk>;
|
|
36
|
+
/**
|
|
37
|
+
* Every late chunk of the document, until nothing new registers. A chunk bakes its region as its
|
|
38
|
+
* promise settles, and a region baked there may hold a `<Region of={promise}>` of its own: it
|
|
39
|
+
* registers then, after the document's list was taken. So after each chunk the request's late
|
|
40
|
+
* regions are taken again (`take`), and whatever registered joins as one more source, in
|
|
41
|
+
* completion order with the rest. It ends only when every source ended and a last take finds
|
|
42
|
+
* none: no slot is left that nothing fills.
|
|
43
|
+
*/
|
|
44
|
+
export declare function until_drained(first: AsyncGenerator<LateChunk>, take: () => ReadonlyArray<{
|
|
45
|
+
id: string;
|
|
46
|
+
promise: Promise<unknown>;
|
|
47
|
+
}> | null): AsyncGenerator<LateChunk>;
|
|
34
48
|
/** Interleave chunk sources by READINESS (a page generator + the late-region pool run together;
|
|
35
49
|
* whichever has a chunk ready streams next). Ends when every source ends. */
|
|
36
50
|
export declare function merge_chunks(...sources: AsyncGenerator<LateChunk>[]): AsyncGenerator<LateChunk>;
|