@sigil-dev/grimoire 0.9.33 → 0.10.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/bin/sigil.ts +1 -1
- package/package.json +6 -5
- package/src/client/csrf.ts +1 -1
- package/src/client/router.ts +6 -4
- package/src/rendering/preload.ts +4 -4
- package/src/rendering/ssrPlugin.ts +114 -107
- package/src/rendering/timing.ts +1 -1
- package/src/routing/scanner.ts +24 -2
- package/src/server/coordinator.ts +6 -5
- package/src/server/index.ts +26 -9
- package/src/server/plugins.ts +0 -2
- package/src/testing/index.ts +1 -1
- package/src/testing/server-preload.ts +14 -0
- package/test/router-ssr-import.test.ts +12 -0
- package/test/scanning.test.ts +26 -1
- package/test/scope.test.ts +7 -2
- package/test/server.test.ts +30 -0
- package/test/workspace-files.test.ts +13 -16
- package/test/workspace-versions.test.ts +9 -15
package/bin/sigil.ts
CHANGED
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"module": "index.ts",
|
|
12
12
|
"type": "module",
|
|
13
13
|
"private": false,
|
|
14
|
-
"version": "0.
|
|
14
|
+
"version": "0.10.0",
|
|
15
15
|
"bin": {
|
|
16
16
|
"sigil": "bin/sigil.ts"
|
|
17
17
|
},
|
|
@@ -32,15 +32,16 @@
|
|
|
32
32
|
"./adapters/bun": "./src/adapters/bun.ts",
|
|
33
33
|
"./testing": "./src/testing/index.ts",
|
|
34
34
|
"./testing/dom": "./src/testing/dom.ts",
|
|
35
|
-
"./testing/server": "./src/testing/server.ts"
|
|
35
|
+
"./testing/server": "./src/testing/server.ts",
|
|
36
|
+
"./testing/server-preload": "./src/testing/server-preload.ts"
|
|
36
37
|
},
|
|
37
38
|
"scripts": {
|
|
38
39
|
"test": "bun test"
|
|
39
40
|
},
|
|
40
41
|
"dependencies": {
|
|
41
|
-
"@sigil-dev/cli": "0.
|
|
42
|
-
"@sigil-dev/compiler": "0.
|
|
43
|
-
"@sigil-dev/runtime": "0.
|
|
42
|
+
"@sigil-dev/cli": "0.10.0",
|
|
43
|
+
"@sigil-dev/compiler": "0.10.0",
|
|
44
|
+
"@sigil-dev/runtime": "0.10.0"
|
|
44
45
|
},
|
|
45
46
|
"peerDependencies": {
|
|
46
47
|
"typescript": "^5",
|
package/src/client/csrf.ts
CHANGED
|
@@ -15,7 +15,7 @@ export const CSRF_FIELD = "_csrf";
|
|
|
15
15
|
|
|
16
16
|
function cookieToken(): string | null {
|
|
17
17
|
const m = /(?:^|;\s*)_csrf=([^;]+)/.exec(document.cookie);
|
|
18
|
-
return m ? decodeURIComponent(m[1]) : null;
|
|
18
|
+
return m?.[1] ? decodeURIComponent(m[1]) : null;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
export function ensureCsrf(form: HTMLFormElement): void {
|
package/src/client/router.ts
CHANGED
|
@@ -88,8 +88,10 @@ let disposeCurrentPage: (() => void) | null = null;
|
|
|
88
88
|
// Scroll keys and same-page refetch detection are pathname-only on purpose.
|
|
89
89
|
// currentSearch is tracked alongside so popstate can tell "?page=2" apart
|
|
90
90
|
// from "?page=1" without polluting either of those.
|
|
91
|
-
|
|
92
|
-
|
|
91
|
+
// importing this on the server (a component that calls invalidate() renders
|
|
92
|
+
// there too) must not touch the browser's globals
|
|
93
|
+
let currentPath = typeof location === "undefined" ? "" : location.pathname;
|
|
94
|
+
let currentSearch = typeof location === "undefined" ? "" : location.search;
|
|
93
95
|
|
|
94
96
|
// C1: Navigation hooks
|
|
95
97
|
let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
|
|
@@ -264,7 +266,7 @@ function sharedTransitionKeys(
|
|
|
264
266
|
// The HTTP cache cannot do this job: the navigate JSON carries no freshness
|
|
265
267
|
// headers and pages are commonly served `no-cache`, so a plain prefetch
|
|
266
268
|
// warmed nothing the click could reuse.
|
|
267
|
-
let preloadTimer:
|
|
269
|
+
let preloadTimer: ReturnType<typeof setTimeout> | undefined;
|
|
268
270
|
const PREFETCH_TTL_MS = 15_000;
|
|
269
271
|
const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
|
|
270
272
|
|
|
@@ -478,7 +480,7 @@ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
|
|
|
478
480
|
};
|
|
479
481
|
|
|
480
482
|
for (let i = matchedLayouts.length - 1; i >= 0; i--) {
|
|
481
|
-
const LayoutComponent = matchedLayouts[i]
|
|
483
|
+
const LayoutComponent = matchedLayouts[i]!.component;
|
|
482
484
|
const innerRender = renderFn;
|
|
483
485
|
const currentLayoutData = layoutData?.[i];
|
|
484
486
|
renderFn = () => {
|
package/src/rendering/preload.ts
CHANGED
|
@@ -35,8 +35,8 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
|
|
|
35
35
|
let ids: string[];
|
|
36
36
|
let raw: Array<Array<string | number>>;
|
|
37
37
|
try {
|
|
38
|
-
ids = JSON.parse(call[1]);
|
|
39
|
-
raw = JSON.parse(call[2]);
|
|
38
|
+
ids = JSON.parse(call[1]!);
|
|
39
|
+
raw = JSON.parse(call[2]!);
|
|
40
40
|
} catch {
|
|
41
41
|
return null;
|
|
42
42
|
}
|
|
@@ -46,14 +46,14 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
|
|
|
46
46
|
if (typeof file !== "string") return;
|
|
47
47
|
nodes.set(id, {
|
|
48
48
|
file,
|
|
49
|
-
deps: deps.map((d) => ids[Number(d)]).filter(
|
|
49
|
+
deps: deps.map((d) => ids[Number(d)]).filter((d): d is string => !!d),
|
|
50
50
|
});
|
|
51
51
|
});
|
|
52
52
|
const routes = new Map<string, string>();
|
|
53
53
|
for (const m of source.matchAll(
|
|
54
54
|
/^\s*("(?:[^"\\]|\\.)*"):\s*\{\s*__lazy:\s*\(\)\s*=>\s*\(__preload\("([^"]+)"\)/gm,
|
|
55
55
|
)) {
|
|
56
|
-
routes.set(JSON.parse(m[1]), m[2]);
|
|
56
|
+
routes.set(JSON.parse(m[1]!), m[2]!);
|
|
57
57
|
}
|
|
58
58
|
return { routes, nodes };
|
|
59
59
|
}
|
|
@@ -1,107 +1,114 @@
|
|
|
1
|
-
import { transformSync } from "@babel/core";
|
|
2
|
-
import type { ParserPlugin } from "@babel/parser";
|
|
3
|
-
import sigilPlugin from "@sigil-dev/compiler/babel";
|
|
4
|
-
import {
|
|
5
|
-
computeHash,
|
|
6
|
-
extractStyles,
|
|
7
|
-
serverStyleSnippet,
|
|
8
|
-
} from "@sigil-dev/compiler/css";
|
|
9
|
-
import { log } from "../logger/instance";
|
|
10
|
-
import { pinRuntime, rewriteAliases } from "../server/resolver";
|
|
11
|
-
import type { GrimoirePlugin } from "../types";
|
|
12
|
-
|
|
13
|
-
const logger = log.scope("scope");
|
|
14
|
-
let registered = false;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
if (
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
1
|
+
import { transformSync } from "@babel/core";
|
|
2
|
+
import type { ParserPlugin } from "@babel/parser";
|
|
3
|
+
import sigilPlugin from "@sigil-dev/compiler/babel";
|
|
4
|
+
import {
|
|
5
|
+
computeHash,
|
|
6
|
+
extractStyles,
|
|
7
|
+
serverStyleSnippet,
|
|
8
|
+
} from "@sigil-dev/compiler/css";
|
|
9
|
+
import { log } from "../logger/instance";
|
|
10
|
+
import { pinRuntime, rewriteAliases } from "../server/resolver";
|
|
11
|
+
import type { GrimoirePlugin } from "../types";
|
|
12
|
+
|
|
13
|
+
const logger = log.scope("scope");
|
|
14
|
+
let registered = false;
|
|
15
|
+
let current: { plugins: GrimoirePlugin[]; aliases: Record<string, string> } = { plugins: [], aliases: {} };
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `aliases` (prefix → absolute directory, see projectAliases) are rewritten
|
|
19
|
+
* to file paths in every compiled module: Bun's runtime plugins can't
|
|
20
|
+
* resolve them for static imports.
|
|
21
|
+
*/
|
|
22
|
+
export function registerSSRPlugin(
|
|
23
|
+
plugins: GrimoirePlugin[] = [],
|
|
24
|
+
aliases: Record<string, string> = {},
|
|
25
|
+
) {
|
|
26
|
+
// Registered once (Bun keeps every plugin), but a later call brings the
|
|
27
|
+
// app's real plugins and aliases: `sigil test` registers early with the
|
|
28
|
+
// defaults, so a test's own imports compile with Sigil's JSX, and the app
|
|
29
|
+
// fills in the rest when it starts.
|
|
30
|
+
current = { plugins, aliases };
|
|
31
|
+
if (registered) return;
|
|
32
|
+
registered = true;
|
|
33
|
+
|
|
34
|
+
Bun.plugin({
|
|
35
|
+
name: "sigil-ssr",
|
|
36
|
+
|
|
37
|
+
setup(build) {
|
|
38
|
+
// loader: "ts" not "tsx" — Babel already consumed the JSX,
|
|
39
|
+
// Bun only needs to strip remaining TypeScript types
|
|
40
|
+
const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
|
|
41
|
+
build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
|
|
42
|
+
try {
|
|
43
|
+
const resolved = Bun.resolveSync(args.path, process.cwd());
|
|
44
|
+
return { path: resolved.replaceAll("\\", "/") };
|
|
45
|
+
} catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
|
|
51
|
+
const { plugins, aliases } = current;
|
|
52
|
+
if (path.includes("index.tsx"))
|
|
53
|
+
logger.debug("[ssr-plugin] onLoad:", path);
|
|
54
|
+
const source = await Bun.file(path).text();
|
|
55
|
+
|
|
56
|
+
// node_modules and .grimoire files are plain TypeScript (no sigil JSX).
|
|
57
|
+
// Still must return { contents, loader } — never return undefined from onLoad.
|
|
58
|
+
if (path.includes("node_modules") || path.includes(".grimoire")) {
|
|
59
|
+
return {
|
|
60
|
+
contents: transpiler.transformSync(source),
|
|
61
|
+
loader: "js" as const,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (process.env.SIGIL_VERBOSE) {
|
|
66
|
+
logger.debug("[sigil-ssr] XFORM:", path);
|
|
67
|
+
}
|
|
68
|
+
// must match the client build, or scoped classes differ per side;
|
|
69
|
+
// files without a <style> block get no scope class at all. The
|
|
70
|
+
// CSS is registered for the renderer, which puts it in <head>.
|
|
71
|
+
const styles = extractStyles(source, computeHash(path), path);
|
|
72
|
+
const hash = styles.css ? computeHash(path) : undefined;
|
|
73
|
+
const sourceNoStyle = styles.code;
|
|
74
|
+
const result = transformSync(sourceNoStyle, {
|
|
75
|
+
configFile: false,
|
|
76
|
+
babelrc: false,
|
|
77
|
+
parserOpts: {
|
|
78
|
+
// The jsx plugin goes on .tsx files only.
|
|
79
|
+
//
|
|
80
|
+
// With it enabled everywhere, Babel parses `<R>(x: R) => x`
|
|
81
|
+
// as the opening of a JSX element and fails with
|
|
82
|
+
// "Unexpected token `>`". So a generic arrow function in a
|
|
83
|
+
// plain .ts file — completely ordinary TypeScript — could
|
|
84
|
+
// not be compiled. Found while writing the Drizzle adapter
|
|
85
|
+
// recipe, where `transaction: <R>(db, fn) => ...` is the
|
|
86
|
+
// form that removes an `as any`.
|
|
87
|
+
//
|
|
88
|
+
// A .tsx file is genuinely ambiguous (`<R>(x) => x` is
|
|
89
|
+
// JSX there), so .tsx keeps both and users write `<R,>`.
|
|
90
|
+
plugins: path.endsWith(".tsx")
|
|
91
|
+
? (["typescript", "jsx"] as ParserPlugin[])
|
|
92
|
+
: (["typescript"] as ParserPlugin[]),
|
|
93
|
+
},
|
|
94
|
+
plugins: [[sigilPlugin, { mode: "ssr", hash, aliases }]],
|
|
95
|
+
filename: path,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
let contents = pinRuntime(
|
|
99
|
+
rewriteAliases(transpiler.transformSync(result?.code ?? ""), aliases),
|
|
100
|
+
);
|
|
101
|
+
if (styles.css && hash) {
|
|
102
|
+
contents = serverStyleSnippet(hash, styles.css) + contents;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
for (const plugin of plugins) {
|
|
106
|
+
if (plugin.transform)
|
|
107
|
+
contents = (await plugin.transform(contents, path)) ?? contents;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return { contents, loader: "js" as const };
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
package/src/rendering/timing.ts
CHANGED
package/src/routing/scanner.ts
CHANGED
|
@@ -102,6 +102,26 @@ export function filePathToRoutePath(
|
|
|
102
102
|
|
|
103
103
|
const TEST_FILE = /[._](test|spec)\.[jt]sx?$/;
|
|
104
104
|
|
|
105
|
+
/** How loosely a pattern segment matches: fixed text, a param, an optional one, the rest. */
|
|
106
|
+
const segmentRank = (seg: string) =>
|
|
107
|
+
seg.startsWith("*") ? 3 : seg.endsWith("?") ? 2 : seg.startsWith(":") ? 1 : 0;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Between routes that score the same, the one that is more specific earlier
|
|
111
|
+
* in the path goes first: /wiki/_history/*page before /wiki/*page, though
|
|
112
|
+
* both have one rest param. Without this, ties fell to the order the
|
|
113
|
+
* filesystem listed the folders in, which differs between machines.
|
|
114
|
+
*/
|
|
115
|
+
export function byShape(a: string, b: string): number {
|
|
116
|
+
const as = a.split("/").filter(Boolean);
|
|
117
|
+
const bs = b.split("/").filter(Boolean);
|
|
118
|
+
for (let i = 0; i < Math.min(as.length, bs.length); i++) {
|
|
119
|
+
const d = segmentRank(as[i]!) - segmentRank(bs[i]!);
|
|
120
|
+
if (d) return d;
|
|
121
|
+
}
|
|
122
|
+
return bs.length - as.length || (a < b ? -1 : a > b ? 1 : 0);
|
|
123
|
+
}
|
|
124
|
+
|
|
105
125
|
export async function scanRoutes(
|
|
106
126
|
routesDir: string,
|
|
107
127
|
viteRoot: string = routesDir,
|
|
@@ -170,8 +190,10 @@ export async function scanRoutes(
|
|
|
170
190
|
r.paramNames.length * 2 +
|
|
171
191
|
r.optionalParamNames.length +
|
|
172
192
|
r.restParamNames.length * 1000;
|
|
173
|
-
|
|
174
|
-
|
|
193
|
+
const byScore = (a: RouteFile, b: RouteFile) =>
|
|
194
|
+
scoreRoute(a) - scoreRoute(b) || byShape(a.path, b.path);
|
|
195
|
+
routes.sort(byScore);
|
|
196
|
+
servers.sort(byScore);
|
|
175
197
|
|
|
176
198
|
assertNoDuplicatePaths(
|
|
177
199
|
routes.filter((r) => r.type === "page" || r.type === "simple"),
|
|
@@ -51,7 +51,7 @@ async function waitForWorkers(
|
|
|
51
51
|
|
|
52
52
|
function roundRobin(workers: WorkerDescriptor[]): WorkerDescriptor {
|
|
53
53
|
const idx = roundRobinCounter++ % workers.length;
|
|
54
|
-
return workers[idx]
|
|
54
|
+
return workers[idx]!;
|
|
55
55
|
}
|
|
56
56
|
let roundRobinCounter = 0;
|
|
57
57
|
|
|
@@ -63,7 +63,7 @@ function consistentHash(
|
|
|
63
63
|
let hash = 0;
|
|
64
64
|
for (let i = 0; i < key.length; i++)
|
|
65
65
|
hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
|
|
66
|
-
return workers[hash % workers.length]
|
|
66
|
+
return workers[hash % workers.length]!;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
function defaultRoute(
|
|
@@ -86,7 +86,7 @@ function defaultRoute(
|
|
|
86
86
|
(w) => w.mode === "frontend" || w.mode === "full",
|
|
87
87
|
);
|
|
88
88
|
if (frontend.length) return roundRobin(frontend);
|
|
89
|
-
return workers[0]
|
|
89
|
+
return workers[0]!;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
export interface ScaleSpec {
|
|
@@ -226,7 +226,7 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
226
226
|
index: i + 1,
|
|
227
227
|
globalIndex: globalIndex++,
|
|
228
228
|
internalUrl: `http://127.0.0.1:${workerPort}`,
|
|
229
|
-
routes: slices[mode] ?? slices.full,
|
|
229
|
+
routes: slices[mode] ?? slices.full ?? [],
|
|
230
230
|
};
|
|
231
231
|
|
|
232
232
|
const publicEnvVars: Record<string, string> = {};
|
|
@@ -311,7 +311,8 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
311
311
|
return new Response("Upgrade Required", { status: 426 });
|
|
312
312
|
}
|
|
313
313
|
|
|
314
|
-
|
|
314
|
+
// filled in by the plugins' handles before anything reads it
|
|
315
|
+
const locals = {} as App.Locals;
|
|
315
316
|
const descriptors = liveWorkers.map((w) => w.descriptor);
|
|
316
317
|
const chosen =
|
|
317
318
|
(await runRouteRequest(plugins, req, descriptors, tree)) ??
|
package/src/server/index.ts
CHANGED
|
@@ -479,14 +479,13 @@ export async function createApp(
|
|
|
479
479
|
const rawLocals = finalConfig._behindCoordinator
|
|
480
480
|
? req.headers.get("X-Grimoire-Locals")
|
|
481
481
|
: null;
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
: {};
|
|
482
|
+
// filled in by the plugins' handles before anything reads it
|
|
483
|
+
const locals = (rawLocals ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {}) : {}) as App.Locals;
|
|
485
484
|
// Plugin services sit under the request's own locals: what the app
|
|
486
485
|
// set (a session, a user) always wins over what a plugin declared,
|
|
487
486
|
// so a plugin cannot clobber auth by defining a common key.
|
|
488
487
|
for (const [key, value] of Object.entries(services)) {
|
|
489
|
-
if (!(key in locals)) locals[key] = value;
|
|
488
|
+
if (!(key in locals)) (locals as unknown as Record<string, unknown>)[key] = value;
|
|
490
489
|
}
|
|
491
490
|
const url = new URL(req.url);
|
|
492
491
|
|
|
@@ -639,7 +638,7 @@ export async function createApp(
|
|
|
639
638
|
] as const;
|
|
640
639
|
|
|
641
640
|
// Build event BEFORE matching — handle() runs pre-match like SvelteKit
|
|
642
|
-
trackClientAddress(req, server);
|
|
641
|
+
trackClientAddress(req, server ?? null);
|
|
643
642
|
const cookieHeader = req.headers.get("cookie") ?? "";
|
|
644
643
|
const cookies = createCookies(cookieHeader);
|
|
645
644
|
const setHeadersMap: Record<string, string> = {};
|
|
@@ -664,13 +663,13 @@ export async function createApp(
|
|
|
664
663
|
);
|
|
665
664
|
};
|
|
666
665
|
}
|
|
667
|
-
const patchedFetch: typeof fetch
|
|
666
|
+
const patchedFetch = ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
|
|
668
667
|
const resolved =
|
|
669
668
|
typeof input === "string" && input.startsWith("/")
|
|
670
669
|
? new URL(input, url.origin).toString()
|
|
671
670
|
: input;
|
|
672
671
|
return globalThis.fetch(resolved as any, init);
|
|
673
|
-
};
|
|
672
|
+
}) as typeof fetch;
|
|
674
673
|
const resolve: ResolveFunction = async (evt) => {
|
|
675
674
|
// matching happens here — after handle() has run
|
|
676
675
|
let matched = matchRoute(tree, evt.url, paramMatcherFns);
|
|
@@ -737,7 +736,7 @@ export async function createApp(
|
|
|
737
736
|
locals: evt.locals,
|
|
738
737
|
fetch: patchedFetch,
|
|
739
738
|
cookies,
|
|
740
|
-
setHeaders: (headers) => Object.assign(setHeadersMap, headers),
|
|
739
|
+
setHeaders: (headers: Record<string, string>) => Object.assign(setHeadersMap, headers),
|
|
741
740
|
getClientAddress: () => clientAddressOf(evt.request),
|
|
742
741
|
});
|
|
743
742
|
} catch (e) {
|
|
@@ -748,6 +747,24 @@ export async function createApp(
|
|
|
748
747
|
headers: { Location: e.location },
|
|
749
748
|
});
|
|
750
749
|
}
|
|
750
|
+
// so do a thrown Response and `throw error(404, "…")`: a helper the
|
|
751
|
+
// endpoint shares with pages (a "load the repo or 404" one, say) must
|
|
752
|
+
// not turn its 404 into a 500 here
|
|
753
|
+
if (e instanceof Response) return e;
|
|
754
|
+
if (isErrorResult(e)) {
|
|
755
|
+
const json = evt.request.headers
|
|
756
|
+
.get("accept")
|
|
757
|
+
?.includes("application/json");
|
|
758
|
+
return json
|
|
759
|
+
? Response.json(
|
|
760
|
+
{ error: true, status: e.status, message: e.message },
|
|
761
|
+
{ status: e.status },
|
|
762
|
+
)
|
|
763
|
+
: new Response(`${e.message}\n`, {
|
|
764
|
+
status: e.status,
|
|
765
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
766
|
+
});
|
|
767
|
+
}
|
|
751
768
|
throw e;
|
|
752
769
|
}
|
|
753
770
|
}
|
|
@@ -1110,7 +1127,7 @@ export async function createApp(
|
|
|
1110
1127
|
};
|
|
1111
1128
|
|
|
1112
1129
|
return {
|
|
1113
|
-
fetch: fetchUnderBase,
|
|
1130
|
+
fetch: async (req: Request) => fetchUnderBase(req),
|
|
1114
1131
|
websocket,
|
|
1115
1132
|
tree,
|
|
1116
1133
|
matchers: paramMatcherFns,
|
package/src/server/plugins.ts
CHANGED
|
@@ -101,9 +101,7 @@ export async function runWorkerSpawn(
|
|
|
101
101
|
const merged: WorkerEnv = { env: {} };
|
|
102
102
|
for (const plugin of plugins) {
|
|
103
103
|
const result = await plugin.onWorkerSpawn?.(worker);
|
|
104
|
-
//@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
|
|
105
104
|
if (result?.env) Object.assign(merged.env!, result.env);
|
|
106
|
-
//@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
|
|
107
105
|
if (result?.name) merged.name = result.name;
|
|
108
106
|
}
|
|
109
107
|
return merged;
|
package/src/testing/index.ts
CHANGED
|
@@ -161,7 +161,7 @@ export function context(options: ContextOptions = {}) {
|
|
|
161
161
|
request,
|
|
162
162
|
url,
|
|
163
163
|
params: options.params ?? {},
|
|
164
|
-
locals: (options.locals ?? {}) as App.Locals,
|
|
164
|
+
locals: (options.locals ?? {}) as unknown as App.Locals,
|
|
165
165
|
cookies,
|
|
166
166
|
fetch: options.fetch ?? globalThis.fetch,
|
|
167
167
|
parent: async () => options.parent ?? {},
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Preloaded by `sigil test` for `*.server.test.ts` files.
|
|
3
|
+
*
|
|
4
|
+
* Bun compiles a test file's static imports before any of its code runs, so
|
|
5
|
+
* server code a test imports directly (a module that renders a mail
|
|
6
|
+
* template, say) would be compiled before `createTestApp()` sets up Sigil's
|
|
7
|
+
* compiler, and its `.tsx` would get React's JSX. Registering the compiler
|
|
8
|
+
* here, first, means it compiles the same as when the app loads it. The app
|
|
9
|
+
* adds its plugins and aliases when it starts.
|
|
10
|
+
*/
|
|
11
|
+
import { registerSSRPlugin } from "../rendering/ssrPlugin";
|
|
12
|
+
import { projectAliases } from "../server/resolver";
|
|
13
|
+
|
|
14
|
+
registerSSRPlugin([], projectAliases({}));
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
// A component that calls invalidate() is rendered on the server too, so the
|
|
5
|
+
// router module gets imported there, where there's no `location`. A process
|
|
6
|
+
// of its own: this test run has a DOM, and may have imported the router already.
|
|
7
|
+
test("the client router can be imported where there's no browser", () => {
|
|
8
|
+
const router = join(import.meta.dir, "../src/client/router.ts");
|
|
9
|
+
const p = Bun.spawnSync([process.execPath, "-e", `const m = await import(${JSON.stringify(router)}); if (typeof location !== "undefined") throw new Error("has a browser"); console.log(typeof m.invalidateAll)`], { stdout: "pipe", stderr: "pipe" });
|
|
10
|
+
expect(p.stderr.toString()).toBe("");
|
|
11
|
+
expect(p.stdout.toString().trim()).toBe("function");
|
|
12
|
+
});
|
package/test/scanning.test.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
|
2
2
|
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { filePathToRoutePath, scanRoutes } from "../src/routing/scanner";
|
|
5
|
+
import { byShape, filePathToRoutePath, scanRoutes } from "../src/routing/scanner";
|
|
6
6
|
|
|
7
7
|
describe("File scanning", () => {
|
|
8
8
|
test("index.tsx → /", () => {
|
|
@@ -367,3 +367,28 @@ describe("Duplicate route detection", () => {
|
|
|
367
367
|
);
|
|
368
368
|
});
|
|
369
369
|
});
|
|
370
|
+
|
|
371
|
+
describe("Routes that score the same", () => {
|
|
372
|
+
test("the more specific one first, whatever order the folders are listed in", async () => {
|
|
373
|
+
// a rest param under a fixed folder vs a rest param right away: both
|
|
374
|
+
// score one rest param, and used to fall to readdir order
|
|
375
|
+
const root = join(tmpdir(), `grimoire-ties-${Date.now()}`);
|
|
376
|
+
const dirs = ["wiki/[...page]", "wiki/_history/[...page]", "wiki/_edit/[...page]", "wiki/_raw/[...path]"];
|
|
377
|
+
for (const d of dirs) {
|
|
378
|
+
await mkdir(join(root, d), { recursive: true });
|
|
379
|
+
await writeFile(join(root, d, "+page.tsx"), "export default () => null");
|
|
380
|
+
}
|
|
381
|
+
const tree = await scanRoutes(root);
|
|
382
|
+
const order = tree.routes.map((r) => r.path);
|
|
383
|
+
expect(order.indexOf("/wiki/*page")).toBe(order.length - 1);
|
|
384
|
+
expect(order.slice(0, 3).sort()).toEqual(["/wiki/_edit/*page", "/wiki/_history/*page", "/wiki/_raw/*path"]);
|
|
385
|
+
await rm(root, { recursive: true });
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
test("byShape: fixed text before params before the rest, segment by segment", () => {
|
|
389
|
+
expect(byShape("/a/_x/*p", "/a/*p")).toBeLessThan(0);
|
|
390
|
+
expect(byShape("/:o/:r/b", "/:o/:r/:x")).toBeLessThan(0);
|
|
391
|
+
expect(byShape("/a/:x?", "/a/:x")).toBeGreaterThan(0);
|
|
392
|
+
expect(byShape("/a/b", "/a/b")).toBe(0);
|
|
393
|
+
});
|
|
394
|
+
});
|
package/test/scope.test.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
tick,
|
|
20
20
|
} from "@sigil-dev/runtime";
|
|
21
21
|
import { withEffectScope } from "../src/client/scope.ts";
|
|
22
|
+
import { Window } from "happy-dom";
|
|
22
23
|
|
|
23
24
|
describe("grimoire withEffectScope", () => {
|
|
24
25
|
test("effects inside scope stop after dispose", async () => {
|
|
@@ -157,6 +158,10 @@ describe("grimoire withEffectScope", () => {
|
|
|
157
158
|
});
|
|
158
159
|
});
|
|
159
160
|
|
|
161
|
+
// these two only need elements to put in the pool: a DOM of their own, so they
|
|
162
|
+
// run the same from the repo root (whose preload has one) and from here
|
|
163
|
+
const doc = (globalThis as { document?: Document }).document ?? (new Window().document as unknown as Document);
|
|
164
|
+
|
|
160
165
|
describe("__nodes pool reset on SPA navigation", () => {
|
|
161
166
|
test("navigate sets __nodes to [] before calling Page()", () => {
|
|
162
167
|
// Simulate exactly what router.ts's navigate() does:
|
|
@@ -166,7 +171,7 @@ describe("__nodes pool reset on SPA navigation", () => {
|
|
|
166
171
|
|
|
167
172
|
const mockPage = () => {
|
|
168
173
|
nodesAtCallTime = (globalThis as any).__nodes;
|
|
169
|
-
return
|
|
174
|
+
return doc.createElement("div"); // satisfy replaceChildren
|
|
170
175
|
};
|
|
171
176
|
// Mimic the three lines in navigate() that matter
|
|
172
177
|
(globalThis as any).__nodes = ["stale", "dom", "nodes"]; // leftover from previous page
|
|
@@ -178,7 +183,7 @@ describe("__nodes pool reset on SPA navigation", () => {
|
|
|
178
183
|
|
|
179
184
|
test("Page() called during SSR hydration sees real DOM nodes, not empty pool", () => {
|
|
180
185
|
// Contrast: hydrate.ts sets __nodes to Array.from(slot.childNodes) before calling Page()
|
|
181
|
-
const fakeSlotChild =
|
|
186
|
+
const fakeSlotChild = doc.createElement("div");
|
|
182
187
|
let nodesAtCallTime: unknown = "not set";
|
|
183
188
|
|
|
184
189
|
const mockPage = () => {
|
package/test/server.test.ts
CHANGED
|
@@ -23,6 +23,7 @@ beforeAll(async () => {
|
|
|
23
23
|
await mkdir(join(tmpDir, "api", "hello"), { recursive: true });
|
|
24
24
|
await mkdir(join(tmpDir, "api", "items"), { recursive: true });
|
|
25
25
|
await mkdir(join(tmpDir, "api", "away"), { recursive: true });
|
|
26
|
+
await mkdir(join(tmpDir, "api", "gone"), { recursive: true });
|
|
26
27
|
|
|
27
28
|
await writeFile(
|
|
28
29
|
join(tmpDir, "api", "hello", "+server.ts"),
|
|
@@ -40,6 +41,17 @@ beforeAll(async () => {
|
|
|
40
41
|
}`,
|
|
41
42
|
);
|
|
42
43
|
|
|
44
|
+
// what error(404, "No such thing") throws, and a thrown Response
|
|
45
|
+
await writeFile(
|
|
46
|
+
join(tmpDir, "api", "gone", "+server.ts"),
|
|
47
|
+
`export async function GET() {
|
|
48
|
+
throw { __error: true, status: 404, message: "No such thing" };
|
|
49
|
+
}
|
|
50
|
+
export async function POST() {
|
|
51
|
+
throw new Response("I'm a teapot", { status: 418 });
|
|
52
|
+
}`,
|
|
53
|
+
);
|
|
54
|
+
|
|
43
55
|
// what redirect(303, "/login") throws
|
|
44
56
|
await writeFile(
|
|
45
57
|
join(tmpDir, "api", "away", "+server.ts"),
|
|
@@ -107,6 +119,24 @@ describe("Server — API routes (+server.ts)", () => {
|
|
|
107
119
|
server.stop();
|
|
108
120
|
});
|
|
109
121
|
|
|
122
|
+
test("a thrown error() keeps its status, as text or JSON; a thrown Response is the reply", async () => {
|
|
123
|
+
const server = await createServer({
|
|
124
|
+
port: 3004,
|
|
125
|
+
routes: tmpDir,
|
|
126
|
+
_skipBuild: true,
|
|
127
|
+
});
|
|
128
|
+
let res = await fetch("http://localhost:3004/api/gone");
|
|
129
|
+
expect(res.status).toBe(404);
|
|
130
|
+
expect(await res.text()).toBe("No such thing\n");
|
|
131
|
+
res = await fetch("http://localhost:3004/api/gone", { headers: { Accept: "application/json" } });
|
|
132
|
+
expect(res.status).toBe(404);
|
|
133
|
+
expect(await res.json()).toEqual({ error: true, status: 404, message: "No such thing" });
|
|
134
|
+
res = await fetch("http://localhost:3004/api/gone", { method: "POST" });
|
|
135
|
+
expect(res.status).toBe(418);
|
|
136
|
+
expect(await res.text()).toBe("I'm a teapot");
|
|
137
|
+
server.stop();
|
|
138
|
+
});
|
|
139
|
+
|
|
110
140
|
test("maxRequestBodySize caps request bodies", async () => {
|
|
111
141
|
const server = await createServer({
|
|
112
142
|
port: 3004,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
|
-
import {
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
3
4
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
4
5
|
import { dirname, join, normalize, relative } from "node:path";
|
|
5
6
|
import { fileURLToPath } from "node:url";
|
|
@@ -103,31 +104,27 @@ function reachable(dir: string, entries: string[]): Set<string> {
|
|
|
103
104
|
return seen;
|
|
104
105
|
}
|
|
105
106
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
cwd: dir,
|
|
112
|
-
encoding: "utf8",
|
|
113
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
114
|
-
},
|
|
115
|
-
);
|
|
116
|
-
const [report] = JSON.parse(out) as Array<{ files: Array<{ path: string }> }>;
|
|
107
|
+
// npm pack takes seconds a package; they run side by side so the whole
|
|
108
|
+
// workspace fits the timeout on a slow machine too
|
|
109
|
+
async function packedFiles(dir: string): Promise<Set<string>> {
|
|
110
|
+
const { stdout } = await promisify(execFile)("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], { cwd: dir, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
111
|
+
const [report] = JSON.parse(stdout) as Array<{ files: Array<{ path: string }> }>;
|
|
117
112
|
return new Set(report!.files.map((f) => normalize(join(dir, f.path))));
|
|
118
113
|
}
|
|
119
114
|
|
|
120
115
|
describe("workspace files", () => {
|
|
121
|
-
test("every file an entry point imports is in the tarball", () => {
|
|
116
|
+
test("every file an entry point imports is in the tarball", async () => {
|
|
122
117
|
const missing: string[] = [];
|
|
123
|
-
|
|
118
|
+
const packages = shipped();
|
|
119
|
+
const packs = await Promise.all(packages.map(({ dir }) => packedFiles(dir)));
|
|
120
|
+
for (const [i, { dir, manifest }] of packages.entries()) {
|
|
124
121
|
const entries = [
|
|
125
122
|
...(manifest.module ? [manifest.module] : []),
|
|
126
123
|
...(manifest.main ? [manifest.main] : []),
|
|
127
124
|
...exportTargets(manifest.bin),
|
|
128
125
|
...exportTargets(manifest.exports),
|
|
129
126
|
];
|
|
130
|
-
const packed =
|
|
127
|
+
const packed = packs[i]!;
|
|
131
128
|
for (const file of reachable(dir, entries)) {
|
|
132
129
|
if (!packed.has(file)) {
|
|
133
130
|
missing.push(
|
|
@@ -137,7 +134,7 @@ describe("workspace files", () => {
|
|
|
137
134
|
}
|
|
138
135
|
}
|
|
139
136
|
expect(missing).toEqual([]);
|
|
140
|
-
},
|
|
137
|
+
}, 120_000);
|
|
141
138
|
|
|
142
139
|
test("no relative import points at a file that does not exist", () => {
|
|
143
140
|
// A type-only import of a missing file still runs, because Bun erases
|
|
@@ -95,20 +95,14 @@ describe("workspace versions", () => {
|
|
|
95
95
|
expect(mismatches).toEqual([]);
|
|
96
96
|
});
|
|
97
97
|
|
|
98
|
-
test("
|
|
99
|
-
//
|
|
100
|
-
// them resolves to whichever one the
|
|
101
|
-
// packed dependency ends up pointing at a
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
];
|
|
105
|
-
expect(
|
|
106
|
-
distinct.length === 1
|
|
107
|
-
? []
|
|
108
|
-
: [
|
|
109
|
-
`packages sit at ${distinct.join(", ")} — a release moves them together`,
|
|
110
|
-
],
|
|
111
|
-
).toEqual([]);
|
|
98
|
+
test("core is at one version", () => {
|
|
99
|
+
// Core pins core exactly, so two core packages at different versions
|
|
100
|
+
// means a `workspace:*` between them resolves to whichever one the
|
|
101
|
+
// lockfile saw, which is how a packed dependency ends up pointing at a
|
|
102
|
+
// version nothing claims. Plugins version on their own (scripts/release-plan.ts).
|
|
103
|
+
const CORE = ["runtime", "compiler", "grimoire", "cli", "types"];
|
|
104
|
+
const distinct = [...new Set(shipped().filter(({ dir }) => CORE.includes(dir)).map(({ manifest }) => manifest.version))];
|
|
105
|
+
expect(distinct.length === 1 ? [] : [`core packages sit at ${distinct.join(", ")}; a release moves them together`]).toEqual([]);
|
|
112
106
|
});
|
|
113
107
|
|
|
114
108
|
test("the release version is not already published with other content", async () => {
|
|
@@ -120,7 +114,7 @@ describe("workspace versions", () => {
|
|
|
120
114
|
//
|
|
121
115
|
// So a version is only safe to depend on once it is published *with*
|
|
122
116
|
// this content. Until then a consumer resolves to the older tarball.
|
|
123
|
-
const version = shipped()
|
|
117
|
+
const version = shipped().find(({ dir }) => dir === "grimoire")?.manifest.version;
|
|
124
118
|
if (!version) return;
|
|
125
119
|
|
|
126
120
|
// Registry access is best-effort: a suite that needs the network to
|