@mandujs/core 0.23.0 → 0.25.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,339 @@
1
+ /**
2
+ * ReverseImportGraph — #189
3
+ *
4
+ * Tracks `importee -> Set<importer>` edges so the dev watcher can answer
5
+ * "which user modules transitively import this file?" when a file change
6
+ * misses every known root set (SSR / API / client / common-dir).
7
+ *
8
+ * # Why this exists
9
+ *
10
+ * Bun caches ES modules at the process level. When a common/shared file
11
+ * changes, `dev.ts` re-imports that file fresh, but intermediate modules
12
+ * that reference it transitively may retain their cached form. The three
13
+ * real-world patterns flagged in #189:
14
+ *
15
+ * 1. Barrel + static map — `index.ts` builds a lookup at module load,
16
+ * so a new entry in a leaf `translations/ko.ts` never shows up until
17
+ * the intermediate barrel is re-evaluated.
18
+ * 2. Deep re-export chain — `A -> B -> C -> D`. A single edit to `D`
19
+ * requires every ancestor to be refreshed.
20
+ * 3. Module-level singletons / registries whose state is captured at
21
+ * import time.
22
+ *
23
+ * The existing watcher dispatches only when the changed path itself is in
24
+ * `serverModuleSet` / `apiModuleSet` / `clientModuleToRoute` / a common
25
+ * dir. For files that live elsewhere — `app/lib/helper.ts`,
26
+ * `app/_utils/translations/ko.ts`, etc. — the event falls through and
27
+ * the user sees stale output until a manual restart.
28
+ *
29
+ * # Design
30
+ *
31
+ * - `edges: Map<importee -> Set<importer>>` — reverse index.
32
+ * - `forward: Map<importer -> Set<importee>>` — kept so that a
33
+ * subsequent `update(importer, newImports)` can tear down stale edges
34
+ * without iterating the full reverse map.
35
+ * - BFS closure for `transitiveImporters(file, maxDepth)` with an
36
+ * explicit visited set and a defensive depth cap (default 10) to
37
+ * prevent pathological full-graph walks on projects with dense
38
+ * cyclic imports. Every node visited at depth d+1 is checked against
39
+ * `visited` BEFORE enqueue so cycles terminate.
40
+ * - All keys are normalized OS-native absolute paths, lowercased on win32
41
+ * so fs.watch events match regardless of drive-letter casing.
42
+ * - The scanner is a conservative regex over `import ... from "…"`,
43
+ * `export ... from "…"`, and dynamic `import("…")`. We intentionally
44
+ * skip a full AST parse — the goal is "catch the common case cheaply"
45
+ * and the static table never drives code generation, only invalidation
46
+ * routing. A false-negative means the change falls through the existing
47
+ * silent-drop path (unchanged behavior); a false-positive triggers an
48
+ * extra rebuild (acceptable cost).
49
+ * - Only first-party (relative / alias-resolvable) imports are recorded.
50
+ * Bare `react`, `@mandujs/core`, etc. are skipped so the graph never
51
+ * tracks node_modules.
52
+ *
53
+ * # What this does NOT do
54
+ *
55
+ * - Does not resolve TypeScript path aliases from `tsconfig.json`. A
56
+ * future pass can wire the `compilerOptions.paths` map in, but the
57
+ * relative-import case covers the scenarios in the issue.
58
+ * - Does not track CSS `@import` — the CSS-update path already has its
59
+ * own mechanism in `dev.ts`.
60
+ * - Does not persist. In-memory only; rebuilt from scratch on dev-server
61
+ * start.
62
+ */
63
+
64
+ import fs from "fs";
65
+ import path from "path";
66
+
67
+ /**
68
+ * Default safety cap for `transitiveImporters` BFS. 10 hops is deep
69
+ * enough for any realistic barrel chain while stopping cold on
70
+ * degenerate graphs (e.g. a project with everything re-exporting
71
+ * everything).
72
+ */
73
+ export const DEFAULT_MAX_CLOSURE_DEPTH = 10;
74
+
75
+ /** Normalize an fs path to the form the watcher emits (forward slash, lowercase on win32). */
76
+ function normalize(p: string): string {
77
+ const abs = path.resolve(p).replace(/\\/g, "/");
78
+ return process.platform === "win32" ? abs.toLowerCase() : abs;
79
+ }
80
+
81
+ /**
82
+ * Return true for a specifier that points at a first-party module we
83
+ * can resolve on disk. Bare specifiers (`react`, `@scope/pkg`) are
84
+ * filtered out so the graph never grows with node_modules edges.
85
+ */
86
+ function isFirstPartySpecifier(spec: string): boolean {
87
+ if (spec.length === 0) return false;
88
+ // `./foo`, `../bar`, `/abs/path` — first-party for sure.
89
+ if (spec.startsWith("./") || spec.startsWith("../") || spec.startsWith("/")) {
90
+ return true;
91
+ }
92
+ // Windows absolute path. `fs.watch` never emits this shape, but a
93
+ // user file could in theory reference one — reject for the same
94
+ // reason we reject node_modules: the file isn't in the reactive tree.
95
+ if (/^[A-Za-z]:[\\/]/.test(spec)) return false;
96
+ // Everything else — bare module — is external.
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * Extensions we try (in order) when a specifier has no explicit
102
+ * extension. Mirrors the set Bun itself would walk for a relative
103
+ * import inside the monorepo.
104
+ */
105
+ const RESOLVE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] as const;
106
+
107
+ /**
108
+ * Resolve a relative specifier from `fromFile`'s directory to an
109
+ * absolute on-disk path. Returns `null` when the target cannot be
110
+ * found (e.g. a typed-only stub, a file the user has not yet
111
+ * written). Callers treat `null` as "skip this edge".
112
+ *
113
+ * Exported for tests; production code uses it via `scanFileImports`.
114
+ */
115
+ export function resolveRelativeImport(fromFile: string, specifier: string): string | null {
116
+ if (!isFirstPartySpecifier(specifier)) return null;
117
+ const fromDir = path.dirname(fromFile);
118
+ const base = path.resolve(fromDir, specifier);
119
+ // If the path already has a recognized extension, test it directly.
120
+ if (RESOLVE_EXTENSIONS.some((e) => base.endsWith(e))) {
121
+ return fs.existsSync(base) ? base : null;
122
+ }
123
+ // Try each extension + `/index.<ext>` so barrel directories resolve.
124
+ for (const ext of RESOLVE_EXTENSIONS) {
125
+ const candidate = base + ext;
126
+ if (fs.existsSync(candidate)) return candidate;
127
+ }
128
+ for (const ext of RESOLVE_EXTENSIONS) {
129
+ const candidate = path.join(base, "index" + ext);
130
+ if (fs.existsSync(candidate)) return candidate;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ // Static-import, export-from, and dynamic import patterns. Written
136
+ // conservatively: each regex consumes a single pair of matching quotes,
137
+ // never spans newlines, and does not attempt to handle template literals
138
+ // (dynamic `import(\`…\`)` with interpolation is inherently unresolvable
139
+ // statically).
140
+ const IMPORT_PATTERNS: readonly RegExp[] = [
141
+ // `import foo from "…"` / `import { x } from "…"` / `import "…"` / `import type { x } from "…"`
142
+ /\bimport\s+(?:type\s+)?(?:[^'"\n;]*?\bfrom\s+)?['"]([^'"\n]+)['"]/g,
143
+ // `export { x } from "…"` / `export * from "…"`
144
+ /\bexport\s+(?:\*|\{[^}]*\})\s+from\s+['"]([^'"\n]+)['"]/g,
145
+ // `import("…")` — dynamic. Template literals (`) intentionally excluded.
146
+ /\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)/g,
147
+ ];
148
+
149
+ /**
150
+ * Scan a file's source text for first-party import specifiers. Returns
151
+ * the raw specifiers (not resolved). Callers usually pair this with
152
+ * `resolveRelativeImport` to get absolute paths.
153
+ *
154
+ * The parser is intentionally regex-based — we do not want to pay the
155
+ * cost of a full AST traverse on every file change. See the module
156
+ * header for the false-positive/negative trade-off.
157
+ */
158
+ export function extractImportSpecifiers(source: string): string[] {
159
+ const out = new Set<string>();
160
+ for (const pattern of IMPORT_PATTERNS) {
161
+ // Reset lastIndex — the regex has `/g` so reuse across calls would
162
+ // otherwise skip matches in later invocations.
163
+ pattern.lastIndex = 0;
164
+ let match: RegExpExecArray | null;
165
+ while ((match = pattern.exec(source)) !== null) {
166
+ const spec = match[1];
167
+ if (typeof spec === "string" && spec.length > 0) out.add(spec);
168
+ }
169
+ }
170
+ return Array.from(out);
171
+ }
172
+
173
+ /**
174
+ * Read a file from disk and return the absolute paths of every
175
+ * resolvable first-party import it contains. Non-existent files and
176
+ * unreadable files both return an empty array (treated as "no edges
177
+ * to record"). Async so the dev server can batch this work off the
178
+ * main event loop.
179
+ */
180
+ export async function scanFileImports(filePath: string): Promise<string[]> {
181
+ let source: string;
182
+ try {
183
+ source = await fs.promises.readFile(filePath, "utf-8");
184
+ } catch {
185
+ return [];
186
+ }
187
+ const specifiers = extractImportSpecifiers(source);
188
+ const out: string[] = [];
189
+ for (const spec of specifiers) {
190
+ const resolved = resolveRelativeImport(filePath, spec);
191
+ if (resolved) out.push(resolved);
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /**
197
+ * Reverse-import graph with a bounded BFS closure API. All public
198
+ * methods accept raw paths; normalization is applied internally.
199
+ */
200
+ export class ReverseImportGraph {
201
+ /** importee -> set of direct importers. */
202
+ private readonly edges = new Map<string, Set<string>>();
203
+ /** importer -> set of direct importees. Kept so `update` is O(|old imports|). */
204
+ private readonly forward = new Map<string, Set<string>>();
205
+
206
+ /**
207
+ * Replace the outgoing edges for `importerFile`. Any prior importees
208
+ * that no longer appear drop the importer from their reverse set so
209
+ * the graph doesn't accumulate stale pointers.
210
+ */
211
+ update(importerFile: string, importeePaths: Iterable<string>): void {
212
+ const importer = normalize(importerFile);
213
+
214
+ // Tear down the previous forward entries.
215
+ const prev = this.forward.get(importer);
216
+ if (prev) {
217
+ for (const importee of prev) {
218
+ const back = this.edges.get(importee);
219
+ if (!back) continue;
220
+ back.delete(importer);
221
+ if (back.size === 0) this.edges.delete(importee);
222
+ }
223
+ }
224
+
225
+ // Build the new forward entry + reverse edges. We normalize inside
226
+ // the loop so the caller can pass unnormalized paths.
227
+ const next = new Set<string>();
228
+ for (const raw of importeePaths) {
229
+ const importee = normalize(raw);
230
+ // Self-edges would create a trivial cycle the BFS has to skip.
231
+ // Drop them at insert time so the visited-check is the only
232
+ // cycle defense we need downstream.
233
+ if (importee === importer) continue;
234
+ next.add(importee);
235
+ let back = this.edges.get(importee);
236
+ if (!back) {
237
+ back = new Set<string>();
238
+ this.edges.set(importee, back);
239
+ }
240
+ back.add(importer);
241
+ }
242
+ if (next.size === 0) {
243
+ this.forward.delete(importer);
244
+ } else {
245
+ this.forward.set(importer, next);
246
+ }
247
+ }
248
+
249
+ /** Forget a single importer. Reverse edges pointing at its importees are cleaned up. */
250
+ remove(importerFile: string): void {
251
+ const importer = normalize(importerFile);
252
+ const prev = this.forward.get(importer);
253
+ if (!prev) return;
254
+ for (const importee of prev) {
255
+ const back = this.edges.get(importee);
256
+ if (!back) continue;
257
+ back.delete(importer);
258
+ if (back.size === 0) this.edges.delete(importee);
259
+ }
260
+ this.forward.delete(importer);
261
+ }
262
+
263
+ /** Direct importers of `file` — the single-hop reverse lookup. */
264
+ directImporters(file: string): ReadonlySet<string> {
265
+ const set = this.edges.get(normalize(file));
266
+ return set ?? new Set<string>();
267
+ }
268
+
269
+ /**
270
+ * Transitive importers of `file`. Returns the normalized set
271
+ * excluding `file` itself. BFS with cycle detection; every node is
272
+ * visited at most once. Capped at `maxDepth` hops so a pathological
273
+ * graph cannot degrade a single file change into a full-project walk.
274
+ *
275
+ * Depth 0 is the changed file itself (not included in the result).
276
+ * Depth 1 is the set returned by `directImporters`. Depth N is the
277
+ * set of modules whose shortest path to `file` is exactly N hops.
278
+ */
279
+ transitiveImporters(
280
+ file: string,
281
+ maxDepth: number = DEFAULT_MAX_CLOSURE_DEPTH,
282
+ ): Set<string> {
283
+ const target = normalize(file);
284
+ const result = new Set<string>();
285
+ // Guard against 0 / negative depth — those are no-ops.
286
+ if (!Number.isFinite(maxDepth) || maxDepth <= 0) return result;
287
+
288
+ let frontier = new Set<string>([target]);
289
+ const visited = new Set<string>([target]);
290
+
291
+ for (let depth = 0; depth < maxDepth && frontier.size > 0; depth++) {
292
+ const next = new Set<string>();
293
+ for (const node of frontier) {
294
+ const directs = this.edges.get(node);
295
+ if (!directs) continue;
296
+ for (const importer of directs) {
297
+ if (visited.has(importer)) continue;
298
+ visited.add(importer);
299
+ result.add(importer);
300
+ next.add(importer);
301
+ }
302
+ }
303
+ frontier = next;
304
+ }
305
+ return result;
306
+ }
307
+
308
+ /** True if any edge points at `file`. Useful for fast "do we know this file?" checks. */
309
+ knows(file: string): boolean {
310
+ const key = normalize(file);
311
+ return this.edges.has(key) || this.forward.has(key);
312
+ }
313
+
314
+ /** Drop everything (dev-server restart). */
315
+ clear(): void {
316
+ this.edges.clear();
317
+ this.forward.clear();
318
+ }
319
+
320
+ /** Total number of tracked importer modules (for diagnostics). */
321
+ get size(): number {
322
+ return this.forward.size;
323
+ }
324
+
325
+ /**
326
+ * Dump the current state as plain JSON. Intended for debug
327
+ * assertions in unit tests, not for production hot paths.
328
+ */
329
+ _inspect(): {
330
+ forward: Record<string, string[]>;
331
+ reverse: Record<string, string[]>;
332
+ } {
333
+ const forward: Record<string, string[]> = {};
334
+ for (const [k, v] of this.forward) forward[k] = Array.from(v);
335
+ const reverse: Record<string, string[]> = {};
336
+ for (const [k, v] of this.edges) reverse[k] = Array.from(v);
337
+ return { forward, reverse };
338
+ }
339
+ }
@@ -125,4 +125,58 @@ describe("safeBuild", () => {
125
125
  expect(state.active).toBe(0);
126
126
  expect(state.queued).toBe(0);
127
127
  });
128
+
129
+ it("slot handoff — new callers cannot bypass queued waiters (regression for cap+1 race)", async () => {
130
+ // Scenario: a build completes with a waiter queued; a NEW safeBuild call
131
+ // fires on the same microtask. A prior revision decremented `active`
132
+ // before resolving the waiter, leaving a microtask-sized window where
133
+ // the new caller saw `active < max`, skipped the wait, and became the
134
+ // cap+1 concurrent build. This test launches 3*max + 1 builds, samples
135
+ // active at every slot release, and asserts the peak never exceeds max.
136
+ const { max } = _getConcurrencyState();
137
+ const N = max * 3 + 1; // always enough to trigger at least one handoff
138
+ const entries = await Promise.all(
139
+ Array.from({ length: N }, (_, i) => makeEntry(`handoff-${i}`)),
140
+ );
141
+
142
+ let peak = 0;
143
+ let samples = 0;
144
+ // Sample at microtask granularity — more aggressive than the setInterval
145
+ // sampler in the earlier test — so the cap+1 window has a realistic
146
+ // chance of being observed if the bug returned.
147
+ let stop = false;
148
+ const sample = async () => {
149
+ while (!stop) {
150
+ const { active } = _getConcurrencyState();
151
+ if (active > peak) peak = active;
152
+ samples++;
153
+ await Promise.resolve(); // yield to microtask queue
154
+ }
155
+ };
156
+ const sampler = sample();
157
+
158
+ try {
159
+ const results = await Promise.all(
160
+ entries.map((entry) =>
161
+ safeBuild({
162
+ entrypoints: [entry],
163
+ outdir: rootDir,
164
+ target: "browser",
165
+ naming: path.basename(entry, ".ts") + ".[ext]",
166
+ }),
167
+ ),
168
+ );
169
+ expect(results.every((r) => r.success)).toBe(true);
170
+ } finally {
171
+ stop = true;
172
+ await sampler;
173
+ }
174
+
175
+ expect(peak).toBeLessThanOrEqual(max);
176
+ expect(samples).toBeGreaterThan(0);
177
+
178
+ const state = _getConcurrencyState();
179
+ expect(state.active).toBe(0);
180
+ expect(state.queued).toBe(0);
181
+ });
128
182
  });
@@ -20,6 +20,15 @@
20
20
  * - In-process only. Cross-worker coordination is not this module's job;
21
21
  * per-worker throttling already prevents the observed failure modes in
22
22
  * our test matrix.
23
+ *
24
+ * Correctness — slot handoff:
25
+ * - The semaphore does slot *handoff* rather than release-then-acquire. When
26
+ * a build completes with waiters queued, the slot is transferred directly
27
+ * to the next waiter (active count never drops). A previous revision had
28
+ * a classic acquire race: `releaseSlot()` decremented `active` before the
29
+ * waiter's `active++` ran, which opened a microtask-sized window where a
30
+ * concurrent `safeBuild()` call could observe `active < max`, skip the
31
+ * wait, and join in — yielding `cap+1` concurrent builds.
23
32
  */
24
33
 
25
34
  import type { BuildConfig, BuildOutput } from "bun";
@@ -38,16 +47,36 @@ const maxConcurrent = parseMaxConcurrent();
38
47
  let active = 0;
39
48
  const waiters: Array<() => void> = [];
40
49
 
41
- function waitForSlot(): Promise<void> {
50
+ /**
51
+ * Acquire a slot. When `active < max`, increment synchronously and return.
52
+ * Otherwise, queue and await a direct handoff from a completing build —
53
+ * the completing build does NOT decrement `active`; it resolves our waiter,
54
+ * and `active` stays at `max` through the transition. This prevents a
55
+ * microtask-window race where a third caller could see `active < max` and
56
+ * skip the wait entirely.
57
+ */
58
+ function acquireSlot(): Promise<void> {
59
+ if (active < maxConcurrent) {
60
+ active++;
61
+ return Promise.resolve();
62
+ }
42
63
  return new Promise<void>((resolve) => {
43
64
  waiters.push(resolve);
44
65
  });
45
66
  }
46
67
 
68
+ /**
69
+ * Release a slot. If a waiter is queued, hand the slot off directly (keep
70
+ * `active` at `max`, resolve the waiter). Otherwise decrement `active`.
71
+ */
47
72
  function releaseSlot(): void {
48
- active--;
49
73
  const next = waiters.shift();
50
- if (next) next();
74
+ if (next) {
75
+ // Direct handoff — `active` stays at max, waiter resumes holding the slot.
76
+ next();
77
+ } else {
78
+ active--;
79
+ }
51
80
  }
52
81
 
53
82
  /**
@@ -60,10 +89,7 @@ function releaseSlot(): void {
60
89
  * coordination work.
61
90
  */
62
91
  export async function safeBuild(options: BuildConfig): Promise<BuildOutput> {
63
- if (active >= maxConcurrent) {
64
- await waitForSlot();
65
- }
66
- active++;
92
+ await acquireSlot();
67
93
  try {
68
94
  return await Bun.build(options);
69
95
  } finally {
@@ -1,44 +1,61 @@
1
- /**
2
- * Mandu 전역 타입 선언
3
- * 클라이언트 측 전역 상태의 타입 정의
4
- */
5
- import type { Root } from "react-dom/client";
6
- import type { RouterState } from "./router";
7
-
8
- interface ManduRouteInfo {
9
- id: string;
10
- pattern: string;
11
- params: Record<string, string>;
12
- }
13
-
14
- interface ManduDataEntry {
15
- serverData: unknown;
16
- timestamp?: number;
17
- }
18
-
19
- declare global {
20
- interface Window {
21
- /** 서버에서 전달된 데이터 (routeId → data) */
22
- __MANDU_DATA__?: Record<string, ManduDataEntry>;
23
-
24
- /** 직렬화된 서버 데이터 (raw JSON) */
25
- __MANDU_DATA_RAW__?: string;
26
-
27
- /** 현재 라우트 정보 */
28
- __MANDU_ROUTE__?: ManduRouteInfo;
29
-
30
- /** 클라이언트 라우터 상태 */
31
- __MANDU_ROUTER_STATE__?: RouterState;
32
-
33
- /** 라우터 상태 변경 리스너 */
34
- __MANDU_ROUTER_LISTENERS__?: Set<(state: RouterState) => void>;
35
-
36
- /** Hydrated roots 추적 (unmount용) */
37
- __MANDU_ROOTS__?: Map<string, Root>;
38
-
39
- /** React 인스턴스 공유 */
40
- __MANDU_REACT__?: typeof import("react");
41
- }
42
- }
43
-
44
- export {};
1
+ /**
2
+ * Mandu 전역 타입 선언
3
+ * 클라이언트 측 전역 상태의 타입 정의
4
+ */
5
+ import type { Root } from "react-dom/client";
6
+ import type { RouterState } from "./router";
7
+
8
+ interface ManduRouteInfo {
9
+ id: string;
10
+ pattern: string;
11
+ params: Record<string, string>;
12
+ }
13
+
14
+ interface ManduDataEntry {
15
+ serverData: unknown;
16
+ timestamp?: number;
17
+ }
18
+
19
+ declare global {
20
+ interface Window {
21
+ /** 서버에서 전달된 데이터 (routeId → data) */
22
+ __MANDU_DATA__?: Record<string, ManduDataEntry>;
23
+
24
+ /** 직렬화된 서버 데이터 (raw JSON) */
25
+ __MANDU_DATA_RAW__?: string;
26
+
27
+ /** 현재 라우트 정보 */
28
+ __MANDU_ROUTE__?: ManduRouteInfo;
29
+
30
+ /** 클라이언트 라우터 상태 */
31
+ __MANDU_ROUTER_STATE__?: RouterState;
32
+
33
+ /** 라우터 상태 변경 리스너 */
34
+ __MANDU_ROUTER_LISTENERS__?: Set<(state: RouterState) => void>;
35
+
36
+ /** Hydrated roots 추적 (unmount용) */
37
+ __MANDU_ROOTS__?: Map<string, Root>;
38
+
39
+ /** React 인스턴스 공유 */
40
+ __MANDU_REACT__?: typeof import("react");
41
+
42
+ /**
43
+ * Issue #193 — global SPA navigation toggle.
44
+ *
45
+ * - `undefined` (not set) → default. Plain `<a href="/about">`
46
+ * is intercepted and routed through the client-side router.
47
+ * - `false` → legacy opt-in behavior. Only `<a>`
48
+ * tags with `data-mandu-link` are intercepted; all other
49
+ * internal links perform a full browser navigation.
50
+ * - `true` → same as undefined; present only for
51
+ * symmetry and forward compat.
52
+ *
53
+ * SSR injects this global only when `mandu.config.ts` sets
54
+ * `spa: false` — the default case emits nothing to keep the
55
+ * typical response payload unchanged.
56
+ */
57
+ __MANDU_SPA__?: boolean;
58
+ }
59
+ }
60
+
61
+ export {};
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Issue #192 — Hover prefetch helper
3
+ *
4
+ * Self-contained IIFE that watches `mouseover` events bubbling from
5
+ * internal `<a href="/...">` anchors and issues a one-shot
6
+ * `<link rel="prefetch" as="document">` per unique anchor. The browser
7
+ * cache services the subsequent full-reload navigation, so most
8
+ * above-the-fold links feel instantaneous without requiring a SPA
9
+ * runtime.
10
+ *
11
+ * Design choices (locked to keep the payload tiny — target ≤500 bytes
12
+ * minified + gzipped):
13
+ *
14
+ * 1. **WeakSet-based dedup**: we never attach per-anchor listeners;
15
+ * we use a single `document`-level capture listener and stamp
16
+ * each anchor we've seen into a `WeakSet`. Anchors removed from
17
+ * the DOM collect automatically.
18
+ *
19
+ * 2. **Scope: same-origin `/...` paths only**: we deliberately skip
20
+ * absolute URLs, `mailto:`, `tel:`, `javascript:`, hash-only
21
+ * fragments, and `#`-on-same-page links. The `a[href^="/"]`
22
+ * selector implicitly covers this and avoids a surprise
23
+ * cross-origin DNS lookup.
24
+ *
25
+ * 3. **Opt-out per-link via `data-no-prefetch`**: mirrors Next.js'
26
+ * `prefetch={false}` ergonomics while being framework-agnostic —
27
+ * works with plain `<a>` and with Mandu's `<Link>` component.
28
+ *
29
+ * 4. **`as="document"` hint**: the correct token for HTML documents
30
+ * that will be navigated to via a subsequent click. Without it
31
+ * Chrome 121+ logs a `rel=prefetch as=missing` warning.
32
+ *
33
+ * 5. **Capture phase + `passive: true`**: listening in the capture
34
+ * phase catches the event before any app-level bubble handlers
35
+ * can cancel it (defensive against apps that `stopPropagation`
36
+ * on `<a>`). `passive` ensures we can never accidentally block
37
+ * scroll.
38
+ *
39
+ * 6. **Inline, not external bundle**: the helper is under 1KB and
40
+ * emitting it as a `<script>` child (rather than
41
+ * `<script src=".../_prefetch.js">`) avoids one HTTP round-trip
42
+ * on every SSR response and keeps the module graph unchanged.
43
+ *
44
+ * The exported `PREFETCH_HELPER_SCRIPT` wraps the IIFE in a
45
+ * `<script>` tag, ready to paste into `<head>`. Callers MUST keep it
46
+ * nonce-aware if they plan to enable CSP (future work — right now the
47
+ * Fast Refresh preamble is the only inline script covered by Mandu's
48
+ * CSP header).
49
+ */
50
+
51
+ /** Inner IIFE — exposed for unit tests that want to parse the source. */
52
+ export const PREFETCH_HELPER_BODY = `(function(){var s=new WeakSet();document.addEventListener("mouseover",function(e){var t=e.target;if(!t||typeof t.closest!=="function")return;var a=t.closest("a[href^='/']");if(!a||s.has(a))return;if(a.dataset&&a.dataset.noPrefetch!==undefined)return;if(a.hasAttribute&&a.hasAttribute("download"))return;if(a.target&&a.target!=="_self")return;s.add(a);try{var l=document.createElement("link");l.rel="prefetch";l.href=a.href;l.as="document";document.head.appendChild(l);}catch(_){}},{passive:true,capture:true});})();`;
53
+
54
+ /** Ready-to-inject `<script>` tag for SSR `<head>` injection. */
55
+ export const PREFETCH_HELPER_SCRIPT = `<script>${PREFETCH_HELPER_BODY}</script>`;