@takazudo/zfb 0.1.0-next.78 → 0.1.0-next.79
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/README.md +81 -23
- package/dist/config.d.ts +112 -7
- package/dist/config.js +3 -3
- package/dist/config.js.map +1 -1
- package/dist/content.d.ts +4 -3
- package/dist/content.js +4 -3
- package/dist/content.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/plugins.d.ts +66 -9
- package/dist/plugins.js.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
The public SDK module for [zfb][zfb-site]: islands, content collections,
|
|
6
6
|
pagination, config, plugins, and frontmatter helpers. User pages reach this
|
|
7
|
-
package through the bare specifier `"zfb"` — the
|
|
8
|
-
|
|
7
|
+
package through the bare specifier `"zfb"` — the build pipeline aliases that
|
|
8
|
+
specifier to `@takazudo/zfb` so user TSX can write:
|
|
9
9
|
|
|
10
10
|
```tsx
|
|
11
11
|
import { Island } from "zfb";
|
|
@@ -29,16 +29,22 @@ npm install @takazudo/zfb
|
|
|
29
29
|
This package is the canonical TypeScript source for the `zfb` SDK
|
|
30
30
|
surface. Today it covers:
|
|
31
31
|
|
|
32
|
-
- `<Island when="visible|idle|load">` — JSX wrapper
|
|
33
|
-
for client-side hydration.
|
|
32
|
+
- `<Island when="visible|idle|load|media" media="...">` — JSX wrapper
|
|
33
|
+
that marks a region for client-side hydration. Passing `ssrFallback`
|
|
34
|
+
switches to the SSR-skip marker (`data-zfb-island-skip-ssr`).
|
|
34
35
|
- `scheduleHydrate(target, when, fire)` — the runtime branching helper
|
|
35
36
|
consumed by the hydration runtime.
|
|
37
|
+
- `mountIslands(manifest)`, `mountNewIslands()`,
|
|
38
|
+
`cancelPendingIslands()`, and `unmountIslands(...)` — public island
|
|
39
|
+
lifecycle helpers used by the generated islands runtime and by the
|
|
40
|
+
client router after body swaps.
|
|
36
41
|
- `When`, `WHEN_VALUES`, `DEFAULT_WHEN`, `isWhen`, `resolveWhen` — type
|
|
37
|
-
and runtime utilities pinning the spelling of the
|
|
38
|
-
- `getCollection(name)`, `
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
+
and runtime utilities pinning the spelling of the four modes.
|
|
43
|
+
- `getCollection(name)`, `getEntry(name, slug)`, and
|
|
44
|
+
`parseFrontmatter(raw)` — content collection helpers exported from
|
|
45
|
+
`zfb/content`. `parseFrontmatter` is part of the public SDK surface so
|
|
46
|
+
consumers can write custom content loaders that reuse the v0
|
|
47
|
+
frontmatter parser without re-implementing it.
|
|
42
48
|
- `defaultComponents` — eleven-entry per-element override map (`h2`, `h3`,
|
|
43
49
|
`h4`, `p`, `a`, `strong`, `blockquote`, `ul`, `ol`, `table`, `code`)
|
|
44
50
|
ported from zudo-doc's `htmlOverrides` convention. **`h1` is deliberately
|
|
@@ -53,12 +59,23 @@ surface. Today it covers:
|
|
|
53
59
|
|
|
54
60
|
<entry.Content components={{ ...defaultComponents, h2: MyFancyH2 }} />
|
|
55
61
|
```
|
|
62
|
+
- `mergeMdxComponents(globalSlot, perCall)` — precedence merge helper for
|
|
63
|
+
the MDX component map (`defaultComponents` < global slot < per-call
|
|
64
|
+
overrides).
|
|
56
65
|
- `paginate(items, opts)`, plus `PaginatedPage<T>` / `PaginateRoute<T>` —
|
|
57
66
|
exported from `zfb/paginate`.
|
|
58
67
|
- `defineConfig(config)` — exported from `zfb/config` for the
|
|
59
68
|
`zfb.config.ts` form (the recommended way to author a zfb project's
|
|
60
69
|
configuration; the back-compat `zfb.config.json` form is still
|
|
61
70
|
supported).
|
|
71
|
+
- `definePlugin(plugin)` — identity helper exported from `zfb/plugins`
|
|
72
|
+
and the root barrel so plugin authors get typed lifecycle hooks without
|
|
73
|
+
changing runtime behavior.
|
|
74
|
+
- `clientScript(name)` — SSR helper that returns the stable URL for a
|
|
75
|
+
named client-script asset.
|
|
76
|
+
- `slugify(input)` and `SlugAllocator` — exported from the root barrel and
|
|
77
|
+
the `zfb/slugify` subpath for heading-id parity with the Rust content
|
|
78
|
+
pipeline.
|
|
62
79
|
|
|
63
80
|
The package is JSX-runtime-agnostic: the `Island` component does not
|
|
64
81
|
import preact or react, so it works under either framework adapter
|
|
@@ -89,35 +106,61 @@ export default function Page() {
|
|
|
89
106
|
<Island when="visible">
|
|
90
107
|
<Counter />
|
|
91
108
|
</Island>
|
|
109
|
+
|
|
110
|
+
{/* Hydrate when a CSS media query first matches. */}
|
|
111
|
+
<Island when="media" media="(max-width: 720px)">
|
|
112
|
+
<Counter />
|
|
113
|
+
</Island>
|
|
114
|
+
|
|
115
|
+
{/* Skip SSR for the heavy child and render a placeholder instead. */}
|
|
116
|
+
<Island when="idle" ssrFallback={<div>Loading…</div>}>
|
|
117
|
+
<Counter />
|
|
118
|
+
</Island>
|
|
92
119
|
</>
|
|
93
120
|
);
|
|
94
121
|
}
|
|
95
122
|
```
|
|
96
123
|
|
|
97
|
-
## The
|
|
124
|
+
## The four `when=` modes
|
|
98
125
|
|
|
99
|
-
| `when` | Trigger
|
|
100
|
-
| ----------- |
|
|
101
|
-
| `"load"` | Synchronous, immediate fire after registration. **Default.**
|
|
102
|
-
| `"idle"` | `requestIdleCallback`
|
|
103
|
-
| `"visible"` | `IntersectionObserver`, threshold 0, first intersection only
|
|
126
|
+
| `when` | Trigger | Fallback |
|
|
127
|
+
| ----------- | -------------------------------------------------------------- | -------------------------------------------------- |
|
|
128
|
+
| `"load"` | Synchronous, immediate fire after registration. **Default.** | n/a |
|
|
129
|
+
| `"idle"` | `requestIdleCallback` | `setTimeout(0)` when not available |
|
|
130
|
+
| `"visible"` | `IntersectionObserver`, threshold 0, first intersection only | Immediate fire when `IntersectionObserver` is missing |
|
|
131
|
+
| `"media"` | `matchMedia(media)`, first matching change only | Immediate fire when `matchMedia` or `media` is missing |
|
|
104
132
|
|
|
105
133
|
Unknown values produce a `console.warn` in development builds and fall
|
|
106
134
|
back to `"load"`.
|
|
107
135
|
|
|
136
|
+
`when="media"` requires a `media` prop containing a CSS media query
|
|
137
|
+
string. Supplying `media` with any other `when` value is ignored and
|
|
138
|
+
warns in development builds.
|
|
139
|
+
|
|
108
140
|
## Build-time output
|
|
109
141
|
|
|
110
|
-
The wrapper is intentionally type-erased at the JSX boundary.
|
|
111
|
-
|
|
142
|
+
The wrapper is intentionally type-erased at the JSX boundary. It reads
|
|
143
|
+
the wrapped child's JSX type identity (`displayName`, then `name`, then
|
|
144
|
+
host tag name) and writes the component name immediately. At the call
|
|
145
|
+
site, `<Island when="visible"><Counter count={1} /></Island>` renders as:
|
|
112
146
|
|
|
113
147
|
```html
|
|
114
|
-
<div data-zfb-island data-when="visible"
|
|
148
|
+
<div data-zfb-island="Counter" data-when="visible" data-props='{"count":1}'>
|
|
149
|
+
<!-- rendered child output -->
|
|
150
|
+
</div>
|
|
115
151
|
```
|
|
116
152
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
153
|
+
`data-props` carries the wrapped child's serializable own props across
|
|
154
|
+
the SSR-to-hydration boundary. The wrapper omits `children`, omits the
|
|
155
|
+
attribute entirely when there is no useful props payload, and the runtime
|
|
156
|
+
falls back to `{}` when the attribute is missing or malformed.
|
|
157
|
+
|
|
158
|
+
When `ssrFallback` is supplied, the heavy child is not rendered at SSR
|
|
159
|
+
time. The wrapper writes `data-zfb-island-skip-ssr="ComponentName"`
|
|
160
|
+
instead of `data-zfb-island`, still includes `data-when` / `data-media`
|
|
161
|
+
and `data-props` when applicable, and renders the fallback markup inside
|
|
162
|
+
the wrapper. The client runtime treats that marker as a render target
|
|
163
|
+
rather than a hydration target.
|
|
121
164
|
|
|
122
165
|
## Runtime helper
|
|
123
166
|
|
|
@@ -125,7 +168,13 @@ The hydration runtime imports (or inlines) `scheduleHydrate` from this
|
|
|
125
168
|
package:
|
|
126
169
|
|
|
127
170
|
```ts
|
|
128
|
-
import {
|
|
171
|
+
import {
|
|
172
|
+
scheduleHydrate,
|
|
173
|
+
mountIslands,
|
|
174
|
+
mountNewIslands,
|
|
175
|
+
cancelPendingIslands,
|
|
176
|
+
unmountIslands,
|
|
177
|
+
} from "@takazudo/zfb/runtime";
|
|
129
178
|
|
|
130
179
|
for (const el of document.querySelectorAll<HTMLElement>("[data-zfb-island]")) {
|
|
131
180
|
const when = el.getAttribute("data-when") ?? "load";
|
|
@@ -137,6 +186,15 @@ for (const el of document.querySelectorAll<HTMLElement>("[data-zfb-island]")) {
|
|
|
137
186
|
if hydration has not fired yet. After firing, calling `cancel` is a
|
|
138
187
|
no-op.
|
|
139
188
|
|
|
189
|
+
`mountIslands(manifest)` captures the generated island manifest and
|
|
190
|
+
mounts both hydrated markers (`data-zfb-island`) and SSR-skip markers
|
|
191
|
+
(`data-zfb-island-skip-ssr`). `mountNewIslands()` re-walks the current
|
|
192
|
+
document after a client-router body swap using that captured manifest.
|
|
193
|
+
`cancelPendingIslands()` cancels deferred `idle` / `visible` / `media`
|
|
194
|
+
schedules before a swap, and `unmountIslands(root, incomingBody)` runs
|
|
195
|
+
framework cleanup for discarded islands while preserving matching
|
|
196
|
+
`data-zfb-transition-persist` islands.
|
|
197
|
+
|
|
140
198
|
## Markdown / GFM config
|
|
141
199
|
|
|
142
200
|
`ZfbConfig.markdown.gfm` controls which GitHub-Flavored-Markdown
|
package/dist/config.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export type CollectionDef = {
|
|
|
4
4
|
name: string;
|
|
5
5
|
/** Directory (relative to the project root) holding the entries. */
|
|
6
6
|
path: string;
|
|
7
|
-
/** Optional schema.
|
|
7
|
+
/** Optional schema. Enforced by `zfb check`. */
|
|
8
8
|
schema?: Record<string, unknown>;
|
|
9
9
|
/**
|
|
10
10
|
* Optional include globs (Astro-style, evaluated relative to `path`).
|
|
@@ -29,6 +29,20 @@ export type CollectionDef = {
|
|
|
29
29
|
* collection's slugs round-trip as `foo` instead of `foo.en`.
|
|
30
30
|
*/
|
|
31
31
|
idStripSuffix?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Opt-in to a `path` that escapes the project root via `..` (e.g. a
|
|
34
|
+
* monorepo-shared content dir living outside this package). Default
|
|
35
|
+
* `false` keeps the standard project-root guard. Absolute paths and
|
|
36
|
+
* Windows drive-relative/prefix forms are rejected regardless of
|
|
37
|
+
* this flag — only `..`-relative escapes are relaxed.
|
|
38
|
+
*
|
|
39
|
+
* Security note: if this collection comes from a preset, the preset
|
|
40
|
+
* author — not the consuming project — controls `path`. Setting
|
|
41
|
+
* `allowOutsideRoot: true` on a preset-provided collection widens
|
|
42
|
+
* the project's read surface to wherever that preset points, so
|
|
43
|
+
* treat it the same as any other preset-granted filesystem access.
|
|
44
|
+
*/
|
|
45
|
+
allowOutsideRoot?: boolean;
|
|
32
46
|
};
|
|
33
47
|
export type TailwindConfig = {
|
|
34
48
|
/** Whether Tailwind is enabled. Default: `true`. */
|
|
@@ -107,6 +121,22 @@ export type BundleConfig = {
|
|
|
107
121
|
* Mirrors `BundleConfig::external` in `crates/zfb/src/config.rs`.
|
|
108
122
|
*/
|
|
109
123
|
external?: string[];
|
|
124
|
+
/**
|
|
125
|
+
* Additional esbuild loaders keyed by file extension (for example
|
|
126
|
+
* `{ ".txt": "text" }`). Only inline loaders are supported: `file` and
|
|
127
|
+
* `copy` are intentionally excluded because they emit sibling assets the
|
|
128
|
+
* client bundlers do not publish. `.css`, `.module.css`, `.mdx`, and `.md`
|
|
129
|
+
* are reserved by zfb and rejected during config validation.
|
|
130
|
+
*/
|
|
131
|
+
loaders?: Record<string, "text" | "json" | "base64" | "dataurl" | "binary" | "empty">;
|
|
132
|
+
/**
|
|
133
|
+
* Operator-authored esbuild define substitutions. Values are raw esbuild
|
|
134
|
+
* expressions; string values must be pre-quoted JSON (for example
|
|
135
|
+
* `{ __APP_NAME__: '"my-app"' }`). The mode-owned keys
|
|
136
|
+
* `import.meta.env.PROD`, `import.meta.env.DEV`, and
|
|
137
|
+
* `process.env.NODE_ENV` are reserved and rejected at config-load time.
|
|
138
|
+
*/
|
|
139
|
+
define?: Record<string, string>;
|
|
110
140
|
};
|
|
111
141
|
/**
|
|
112
142
|
* One plugin entry in `zfb.config.ts`.
|
|
@@ -391,8 +421,9 @@ export type ZfbConfig = {
|
|
|
391
421
|
emitRoutesManifest?: boolean;
|
|
392
422
|
/**
|
|
393
423
|
* Syntect code-highlight options; absent = default theme
|
|
394
|
-
* (`base16-ocean.dark`)
|
|
395
|
-
* theme names
|
|
424
|
+
* (`base16-ocean.dark`) and inline color mode. See
|
|
425
|
+
* {@link CodeHighlightConfig} for accepted theme names, custom-theme
|
|
426
|
+
* loading, and the class-emission mode (Highlight Tokens epic).
|
|
396
427
|
*
|
|
397
428
|
* Mirrors `Config::code_highlight` in crates/zfb/src/config.rs.
|
|
398
429
|
*/
|
|
@@ -514,6 +545,12 @@ export type OutputMode = "static" | "hybrid" | "auto";
|
|
|
514
545
|
* `"base16-ocean.light"`, `"base16-ocean.dark"`, `"InspiredGitHub"`,
|
|
515
546
|
* `"Solarized (dark)"`), NOT Shiki names like `"dracula"`.
|
|
516
547
|
*
|
|
548
|
+
* **Class mode** (Highlight Tokens epic, zfb#1528): set `mode: "class"`.
|
|
549
|
+
* Each token gets a semantic role class instead of an inline color, so
|
|
550
|
+
* highlight colors become re-themeable CSS design tokens. Mutually
|
|
551
|
+
* exclusive with `theme` / `themeLight` / `themeDark` / `themesDir` —
|
|
552
|
+
* themes don't affect class emission, so setting both is a build error.
|
|
553
|
+
*
|
|
517
554
|
* Mirrors `CodeHighlightConfig` in crates/zfb/src/config.rs.
|
|
518
555
|
*/
|
|
519
556
|
export type CodeHighlightConfig = {
|
|
@@ -560,7 +597,63 @@ export type CodeHighlightConfig = {
|
|
|
560
597
|
* NOT a Shiki name like `"dracula"`.
|
|
561
598
|
*/
|
|
562
599
|
themeDark?: string;
|
|
600
|
+
/**
|
|
601
|
+
* Output mode for fenced-code highlighting (Highlight Tokens epic,
|
|
602
|
+
* zfb#1528). `"inline"` (default) bakes per-token colors into
|
|
603
|
+
* `style="color:#rrggbb"` (or the dual `--shiki-*` custom properties).
|
|
604
|
+
* `"class"` emits a semantic role class per token instead, so colors
|
|
605
|
+
* become re-themeable CSS design tokens rather than baked-in HTML.
|
|
606
|
+
*
|
|
607
|
+
* Mutually exclusive with {@link theme} / {@link themeLight} /
|
|
608
|
+
* {@link themeDark} / {@link themesDir} — themes don't affect class
|
|
609
|
+
* emission, so setting both is rejected rather than silently ignoring
|
|
610
|
+
* the theme.
|
|
611
|
+
*/
|
|
612
|
+
mode?: CodeHighlightMode;
|
|
613
|
+
/**
|
|
614
|
+
* Class-name prefix for class-mode role classes (e.g. the default
|
|
615
|
+
* `"hi-"` yields `hi-kw`, `hi-str`, ...). Must match
|
|
616
|
+
* `/^[A-Za-z][A-Za-z0-9_-]*$/`. Only meaningful when {@link mode} is
|
|
617
|
+
* `"class"`. Default: `"hi-"`.
|
|
618
|
+
*/
|
|
619
|
+
classPrefix?: string;
|
|
620
|
+
/**
|
|
621
|
+
* Per-role class overrides for class mode, e.g.
|
|
622
|
+
* `{ keyword: "text-violet-600 dark:text-violet-400" }` to map a role
|
|
623
|
+
* onto Tailwind utilities instead of the default `{classPrefix}{role}`
|
|
624
|
+
* class. Keys must be one of the 18 fixed role names (see
|
|
625
|
+
* {@link CodeHighlightRole}); a value may hold multiple
|
|
626
|
+
* space-separated classes and must not contain the bare token `"line"`
|
|
627
|
+
* (collides with the code-enrichment line wrapper class). Absent uses
|
|
628
|
+
* `{classPrefix}{role}` for every role.
|
|
629
|
+
*
|
|
630
|
+
* Setting this while `tailwind.enabled` is `false` (the authored-CSS
|
|
631
|
+
* path) is allowed but emits a build warning — no Tailwind safelist can
|
|
632
|
+
* be generated on that path, so the mapped utilities must already exist
|
|
633
|
+
* in your own CSS.
|
|
634
|
+
*/
|
|
635
|
+
roleClasses?: Partial<Record<CodeHighlightRole, string>>;
|
|
636
|
+
/**
|
|
637
|
+
* Whether to inject the built-in `--zfb-hi-*` token stylesheet
|
|
638
|
+
* (`zfb-hi.css`) into the combined `styles.css` output. Only meaningful
|
|
639
|
+
* in class mode. Default: `true`.
|
|
640
|
+
*/
|
|
641
|
+
defaultStylesheet?: boolean;
|
|
563
642
|
};
|
|
643
|
+
/**
|
|
644
|
+
* `codeHighlight.mode` — see {@link CodeHighlightConfig.mode}.
|
|
645
|
+
*
|
|
646
|
+
* Mirrors `CodeHighlightMode` in crates/zfb/src/config.rs.
|
|
647
|
+
*/
|
|
648
|
+
export type CodeHighlightMode = "inline" | "class";
|
|
649
|
+
/**
|
|
650
|
+
* The fixed 18-role semantic taxonomy for class-mode syntax highlighting
|
|
651
|
+
* (Highlight Tokens epic, zfb#1528) — valid {@link CodeHighlightConfig.roleClasses}
|
|
652
|
+
* keys.
|
|
653
|
+
*
|
|
654
|
+
* Mirrors `CODE_HIGHLIGHT_ROLES` in crates/zfb/src/config.rs.
|
|
655
|
+
*/
|
|
656
|
+
export type CodeHighlightRole = "escape" | "operator" | "comment" | "string" | "number" | "constant" | "keyword" | "function" | "type" | "namespace" | "property" | "variable" | "tag" | "attribute" | "punctuation" | "inserted" | "deleted" | "heading";
|
|
564
657
|
/**
|
|
565
658
|
* Table-of-contents options. Wire via `markdown.toc` in `zfb.config.ts`.
|
|
566
659
|
*
|
|
@@ -750,13 +843,25 @@ export type GithubAutolinksConfig = {
|
|
|
750
843
|
repo: string;
|
|
751
844
|
};
|
|
752
845
|
/**
|
|
753
|
-
* Options
|
|
846
|
+
* Options for the `codeEnrichment` feature.
|
|
754
847
|
*
|
|
755
|
-
*
|
|
848
|
+
* Both flags default to `true` when the feature is enabled with
|
|
849
|
+
* `codeEnrichment: {}` or when a field is absent.
|
|
756
850
|
*
|
|
757
|
-
* Mirrors `CodeEnrichmentConfig` in crates/zfb/src/
|
|
851
|
+
* Mirrors `CodeEnrichmentConfig` in `crates/zfb-md-ast/src/features_config.rs`.
|
|
758
852
|
*/
|
|
759
|
-
export type CodeEnrichmentConfig =
|
|
853
|
+
export type CodeEnrichmentConfig = {
|
|
854
|
+
/**
|
|
855
|
+
* Enable diff-marker processing for markers such as `// [!code ++]`
|
|
856
|
+
* and `// [!code --]`. Default: `true`.
|
|
857
|
+
*/
|
|
858
|
+
diffMarkers?: boolean;
|
|
859
|
+
/**
|
|
860
|
+
* Enable line-highlight processing for fence ranges such as `{1,3-5}`.
|
|
861
|
+
* Default: `true`.
|
|
862
|
+
*/
|
|
863
|
+
lineHighlight?: boolean;
|
|
864
|
+
};
|
|
760
865
|
/**
|
|
761
866
|
* Options for the `tocExport` feature.
|
|
762
867
|
*
|
package/dist/config.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// `zfb/config` — TypeScript helper for the `zfb.config.ts` form.
|
|
2
2
|
//
|
|
3
3
|
// The zfb config loader (`crates/zfb/src/config.rs`) accepts both
|
|
4
|
-
// `zfb.config.ts` and `zfb.config.json`;
|
|
5
|
-
// present
|
|
6
|
-
//
|
|
4
|
+
// `zfb.config.ts` and `zfb.config.json`; TS wins when both files are
|
|
5
|
+
// present. JSON remains accepted for projects predating the TS loader,
|
|
6
|
+
// while new projects should prefer the TS form for editor types and
|
|
7
7
|
// `defineConfig` autocomplete.
|
|
8
8
|
//
|
|
9
9
|
// At parse time, zfb bundles the user's `zfb.config.ts` with esbuild and
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,kEAAkE;AAClE,uEAAuE;AACvE,uEAAuE;AACvE,sEAAsE;AACtE,+BAA+B;AAC/B,EAAE;AACF,yEAAyE;AACzE,uEAAuE;AACvE,uEAAuE;AACvE,kEAAkE;AAClE,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AAmmCvE;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,MAAiB;IAC5C,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,YAAY,CAC1B,aAAqB,EACrB,MAA0B;IAE1B,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,OAAO;QACL,GAAG,MAAM;QACT,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;YACrC,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC5E,wEAAwE;gBACxE,mEAAmE;gBACnE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,GAAG,MAAM,EAAE,CAAC;YACtD,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["// `zfb/config` — TypeScript helper for the `zfb.config.ts` form.\n//\n// The zfb config loader (`crates/zfb/src/config.rs`) accepts both\n// `zfb.config.ts` and `zfb.config.json`; JSON wins when both files are\n// present, which is the back-compat path for projects predating the TS\n// loader. New projects should prefer the TS form for editor types and\n// `defineConfig` autocomplete.\n//\n// At parse time, zfb bundles the user's `zfb.config.ts` with esbuild and\n// aliases this `zfb/config` import to an internal stub that re-exports\n// `defineConfig` as the identity function — so a user project does not\n// need the `zfb` npm package installed locally just to be parsed.\n//\n// The shape mirrors the Rust `Config` struct one-for-one. Keep them in\n// sync; the `defineConfig` identity helper is the single anchor point.\n\nexport type Framework = \"preact\" | \"react\";\n\nexport type CollectionDef = {\n /** Identifier used at the call site (e.g. `\"blog\"`). */\n name: string;\n /** Directory (relative to the project root) holding the entries. */\n path: string;\n /** Optional schema. Reserved for v1.1 — accepted but not enforced today. */\n schema?: Record<string, unknown>;\n /**\n * Optional include globs (Astro-style, evaluated relative to `path`).\n * When set and non-empty, an entry is kept only if at least one\n * pattern matches its relative path. When omitted or empty, no\n * include-filtering happens. Patterns use the `globset` dialect\n * (Unix-style: `*`, `**`, `?`, `[…]`).\n */\n include?: string[];\n /**\n * Optional exclude globs. When set, an entry is dropped if any\n * pattern matches its relative path. Evaluated AFTER `include`.\n * Together they mirror Astro's `['**\\/*.mdx', '!**\\/*.en.mdx']`\n * convention (zfb splits the negative side into its own field).\n */\n exclude?: string[];\n /**\n * Optional suffix to strip from each kept entry's slug + module\n * specifier. Use with multi-locale layouts where one source\n * directory holds both `foo.mdx` (default locale) and `foo.en.mdx`\n * (locale override) — set `idStripSuffix: \".en\"` so the EN\n * collection's slugs round-trip as `foo` instead of `foo.en`.\n */\n idStripSuffix?: string;\n};\n\nexport type TailwindConfig = {\n /** Whether Tailwind is enabled. Default: `true`. */\n enabled?: boolean;\n};\n\n/**\n * Prefetch options. Mirrors `PrefetchConfig` in `crates/zfb/src/config.rs`.\n */\nexport type PrefetchConfig = {\n /**\n * Disable prefetch entirely.\n *\n * When `true`, the bundler emits `globalThis.__zfb.prefetchDisabled = true`\n * in `entry.mjs`, and `<ClientRouter />` renders\n * `<meta name=\"zfb-prefetch-disabled\" content=\"true\">` in `<head>`.\n * The sibling prefetch-core module reads that meta tag at `init()` time\n * and short-circuits — no prefetch wiring runs.\n *\n * The flag is site-wide and static — set once at bundle-emit time,\n * never recomputed per-page. Default: `false`.\n */\n disabled?: boolean;\n};\n\n/**\n * Bundler options. Mirrors `BundleConfig` in `crates/zfb/src/config.rs`.\n */\nexport type BundleConfig = {\n /**\n * Project-relative glob patterns (gitignore-style) for source files\n * the bundler must NOT pull into the esbuild graph.\n *\n * Why this exists: an eager `import.meta.glob('components/**\\/*.stories.tsx',\n * { eager: true })` expands to a static import of every matched file. If a\n * matched file imports a CJS-only package whose `package.json` resolves only\n * via `main`/`module` or a `require`-only `exports` condition (e.g.\n * `msw` → `path-to-regexp@6`), esbuild — invoked with `--platform=neutral`\n * for the worker bundle — rejects it with \"Could not resolve … Main fields\n * must be configured explicitly when using the neutral platform.\" Listing the\n * offending file here keeps the migration build green.\n *\n * Each pattern is matched against the file's path RELATIVE TO THE PROJECT\n * ROOT, in POSIX form (e.g. `components/Foo.stories.tsx` or\n * `components/**\\/*.stories.tsx`). A matched file is:\n *\n * - never copied/symlinked into the bundler's shadow tree, and\n * - dropped from any eager `import.meta.glob(...)` expansion that would\n * otherwise statically import it.\n *\n * Unset / empty → behaviour is byte-identical to a build without this knob:\n * no files are skipped.\n *\n * Mirrors `Config::bundle` in crates/zfb/src/config.rs.\n */\n exclude?: string[];\n\n /**\n * Explicit esbuild `main-fields` list for the `--platform=neutral` page/SSR\n * pass. Under `neutral` esbuild's main-fields list is EMPTY by default, so a\n * dep resolved purely via `package.json` `main`/`module` (no `exports` map)\n * is rejected (\"The \"main\" field here was ignored. Main fields must be\n * configured explicitly when using the neutral platform.\"). Set e.g.\n * `[\"main\", \"module\"]` to let such CJS-main-only deps resolve (#676 —\n * `msw` → `path-to-regexp@6`). Applies to every framework; unset/empty →\n * byte-identical to a build without the knob (the React-only `main,module`\n * shim still applies).\n *\n * Mirrors `BundleConfig::main_fields` in `crates/zfb/src/config.rs`.\n */\n mainFields?: string[];\n\n /**\n * Bare specifiers to mark external in the `--platform=neutral` page/SSR\n * pass, so esbuild leaves them unbundled instead of resolving them (the\n * other #676 escape hatch — externalize a CJS-only dep rather than\n * resolving it). Appended to the framework-provided externals. Unset/empty\n * → no extra externals.\n *\n * Mirrors `BundleConfig::external` in `crates/zfb/src/config.rs`.\n */\n external?: string[];\n};\n\n/**\n * One plugin entry in `zfb.config.ts`.\n *\n * `name` MUST be a module reference that Node's resolver can locate from\n * the project root. The zfb config loader\n * (`crates/zfb-config-loader/js/config-loader.mjs`) resolves it to an\n * absolute module specifier and the build / dev plugin host loads it via\n * dynamic `import()`:\n *\n * - `\"./plugins/my-plugin.mjs\"` / `\"../shared/plugin.mjs\"` —\n * path-relative to the project root (the dir containing `zfb.config.ts`).\n * - `\"/abs/path/to/plugin.mjs\"` — absolute filesystem path.\n * - `\"@takazudo/zfb-plugin-search\"` / `\"my-plugin\"` — npm bare specifier\n * resolved against the project's `node_modules`.\n *\n * Inline-function hooks are NOT supported; the plugin module's default\n * export must be a [`ZfbPlugin`] (see `@takazudo/zfb/plugins`).\n *\n * `options` is passed verbatim to the plugin's hook contexts; treat\n * the schema as plugin-specific.\n */\nexport type PluginConfig = {\n name: string;\n options?: Record<string, unknown>;\n};\n\nexport type ZfbConfig = {\n /** Output directory for built assets. Default: `dist`. */\n outDir?: string;\n /** Public/static directory copied verbatim. Default: `public`. */\n publicDir?: string;\n /** Optional dev/preview server bind host. */\n host?: string;\n /** Optional dev/preview server port. */\n port?: number;\n /**\n * Host header values the dev/preview server accepts when bound to a\n * non-localhost interface (`--host 0.0.0.0`, the bare `--host` LAN\n * shortcut, or `host` above) — the DNS-rebinding guard, mirroring\n * Vite's `server.allowedHosts`.\n *\n * Defaults: only consulted for non-loopback binds — the default\n * `localhost` bind skips validation entirely. `localhost`, the\n * explicitly bound host, and any IP-literal Host — `127.0.0.1`,\n * `[::1]`, the LAN URLs the startup banner prints — are always\n * allowed (DNS rebinding needs a DNS name, so raw IPs are safe;\n * Vite parity); requests with any other Host get a 403.\n *\n * Matching rules (the request Host's port is stripped first and\n * comparison is case-insensitive):\n *\n * - `\"example.com\"` — matches exactly that host.\n * - `\".example.com\"` (leading dot) — matches `example.com` and every\n * subdomain (`api.example.com`).\n * - IPv6 entries may be written with or without brackets\n * (`\"[::1]\"` / `\"::1\"`).\n *\n * Mirrors `Config::allowed_hosts` in `crates/zfb/src/config.rs`.\n */\n allowedHosts?: string[];\n /** JSX framework runtime. Default: `preact`. */\n framework?: Framework;\n /** Content collections. Mirrors the JSON form one-for-one. */\n collections?: CollectionDef[];\n /** Tailwind options; absent = defaults. */\n tailwind?: TailwindConfig;\n /**\n * Prefetch options. When `disabled: true`, the build emits a meta tag\n * that the runtime's prefetch-core module reads at init time to skip\n * all prefetch wiring. Mirrors `Config::prefetch` in\n * `crates/zfb/src/config.rs`.\n */\n prefetch?: PrefetchConfig;\n /**\n * Minify production HTML output from `zfb build`. Default: `false`.\n *\n * The implementation is Rust-only and does not spawn a Node.js minifier\n * subprocess. The first version is intentionally conservative: rendered\n * `.html` pages are candidates, source `.html` passthrough pages remain\n * verbatim, and non-HTML outputs are skipped.\n *\n * Mirrors `Config::minify_html` in `crates/zfb/src/config.rs`.\n */\n minifyHtml?: boolean;\n /**\n * Bundler options. `bundle.exclude` lists project-relative globs of\n * source files to keep out of the esbuild graph (e.g.\n * `[\"components/*.stories.tsx\"]`) — see {@link BundleConfig.exclude} for\n * why this is needed. Unset → byte-identical to a build without the knob.\n * Mirrors `Config::bundle` in `crates/zfb/src/config.rs`.\n */\n bundle?: BundleConfig;\n /** User-supplied plugins. */\n plugins?: PluginConfig[];\n /**\n * Deploy-target adapter package name. Omit (or `\"none\"`) for a pure\n * static build — any route exporting `prerender = false` is then a\n * hard build error. A package name like\n * `\"@takazudo/zfb-adapter-cloudflare\"` selects the matching adapter,\n * and `zfb build` invokes that package's bin to wrap the SSR bundle\n * into a deploy-ready entry (e.g. `dist/_worker.js` for Cloudflare\n * Workers Static Assets, Pages-compatible).\n *\n * Mirrors `Config::adapter` in crates/zfb/src/config.rs.\n */\n adapter?: string;\n /**\n * Strip `.md` / `.mdx` from internal `<a href>` paths during MDX\n * compilation, and append a trailing `/` so the resulting URL shape\n * converges with the rest of the site (mirrors the JS engine's\n * `rehypeStripMdExtension`). Default: `false`.\n *\n * Enable this when content authors hand-write `[label](other.md)`\n * style references that should resolve to the rendered route URL\n * (e.g. `other/`) instead of a literal file path. Built dist and\n * `pnpm dev` honour the same flag, so previews match shipped output.\n *\n * Mirrors `Config::strip_md_ext` in crates/zfb/src/config.rs.\n */\n stripMdExt?: boolean;\n\n /**\n * Public URL prefix mounted in front of every absolute HTML asset\n * URL the build emits — `<link rel=\"stylesheet\">`, `<script type=\"module\">`,\n * and any other `/assets/...`-prefixed reference rewritten by the\n * production asset pipeline.\n *\n * Use this when the site is deployed under a sub-path (e.g.\n * `https://example.com/pj/zudo-doc/`) instead of the domain root.\n * With `base: \"/pj/zudo-doc/\"` the dist HTML emits\n * `<link rel=\"stylesheet\" href=\"/pj/zudo-doc/assets/styles-<hash>.css\">`\n * instead of the unprefixed `/assets/styles-<hash>.css`.\n *\n * Accepted shapes (all normalised to a single canonical form\n * internally):\n *\n * - omitted / `undefined` / `\"\"` / `\"/\"` — no prefix; behaviour is\n * byte-identical to the pre-`base` build (root-mounted site).\n * - leading-and-trailing-slash path like `\"/pj/zudo-doc/\"` — prefix\n * that path onto every asset URL.\n * - absolute URL like `\"https://cdn.example.com/\"` — emit absolute\n * URLs (CDN-hosted assets).\n *\n * Inputs missing a leading or trailing `/` are normalised at config-\n * load time (paths) or asset-emit time (URL prefixes); callers do\n * not have to pre-trim.\n *\n * Mirrors `Config::base` in crates/zfb/src/config.rs.\n */\n base?: string;\n\n /**\n * Canonical origin URL for the site (e.g. `\"https://example.com\"`).\n *\n * When set, the bundler emits `globalThis.__zfb.site = <value>` in\n * `entry.mjs` so layouts can build canonical `<link>` tags,\n * OpenGraph `og:url` meta, sitemap absolute hrefs, and hreflang\n * `<link rel=\"alternate\">` from a single config-level source of truth.\n *\n * **Distinct from `base`**: `base` is a sub-path mount prefix used\n * for asset URLs (e.g. `\"/pj/my-site/\"`). `site` is the full\n * canonical origin (scheme + host, no path) used to construct\n * absolute page URLs for SEO/social metadata. Both may be set\n * simultaneously.\n *\n * Accepted shape: an absolute HTTP or HTTPS URL. Relative URLs,\n * non-HTTP(S) schemes, and empty strings are rejected at config-load\n * time. Trailing slash normalisation is the consumer's responsibility.\n *\n * When absent, `globalThis.__zfb.site` is not emitted — the build\n * output is byte-for-byte identical to builds without this field.\n *\n * Mirrors `Config::site` in crates/zfb/src/config.rs.\n */\n site?: string;\n\n /**\n * Markdown link resolver (port of `remarkResolveMarkdownLinks`).\n *\n * When `enabled: true`, the build appends `ResolveLinksPlugin` to the\n * mdast pipeline so author-written `[label](./other.mdx)` links are\n * rewritten to the corresponding rendered route URL — bypassing the\n * file→directory transformation that breaks relative paths in dist\n * HTML when `foo.mdx` becomes `foo/index.html`. Extensionless\n * (`./other`) and directory-style (`other/`) targets resolve too,\n * probing `{name}.mdx`, `{name}.md`, `{name}/index.mdx`,\n * `{name}/index.md` in that order. Relative targets resolve from the\n * source file's directory; for a directory-style link written from a\n * non-index page against its rendered URL — which sits one directory\n * deeper, e.g. `../sibling/` from `section/article.mdx` — a URL-space\n * fallback retries the probe from the page's route directory when\n * every file-space candidate misses.\n *\n * Two ways to specify the source dirs:\n *\n * - **Single dir (legacy):** set `docsDir` and the build assumes the\n * `/docs/` route prefix. Convenient for single-locale projects.\n * - **Multi dir (`dirs` non-empty):** explicit `{ dir, routePrefix }`\n * entries — required for any project with locale mirrors (e.g.\n * `docs/` AND `docs-ja/`) so each dir maps to its own route prefix\n * (`/docs/` vs `/ja/docs/`). When `dirs` is non-empty, `docsDir`\n * is ignored.\n *\n * Mirrors `Config::resolve_markdown_links` in crates/zfb/src/config.rs.\n */\n resolveMarkdownLinks?: ResolveMarkdownLinksConfig;\n\n /**\n * Whether the basePath rewriter should append a trailing `/` to\n * extensionless absolute hrefs (`<a href=\"/docs/foo\">` becomes\n * `<a href=\"/pj/zudo-doc/docs/foo/\">` when `base = \"/pj/zudo-doc/\"`\n * and this is `true`).\n *\n * Off by default — preserves byte-for-byte parity with the\n * pre-`trailingSlash` build for projects that haven't opted in.\n * Enable when the deploy target serves canonical URLs with trailing\n * slashes (Cloudflare Pages with `trailingSlash: always`, Netlify\n * pretty URLs, etc.) so the dist HTML doesn't ship non-canonical\n * hrefs that 301-redirect on every click.\n *\n * Only the trailing slash for extensionless hrefs is affected.\n * Hrefs that already end in `/`, that have a file extension\n * (`.png`, `.pdf`, …), or that opt out via `data-no-base` pass\n * through unchanged.\n *\n * Mirrors `Config::trailing_slash` in crates/zfb/src/config.rs.\n */\n trailingSlash?: boolean;\n\n /**\n * Markdown / MDX parsing options. Currently the only knob exposed is\n * [`gfm`](MarkdownConfig.gfm), which toggles GFM constructs\n * (strikethrough, table, autolink-literal, task-list-item,\n * footnote-definition) on or off.\n *\n * Mirrors `Config::markdown` in crates/zfb/src/config.rs.\n */\n markdown?: MarkdownConfig;\n\n /**\n * Extra absolute filesystem paths watched by the dev server in\n * addition to the project-root tree.\n *\n * Use this when project content reads from outside the project root\n * (a sibling knowledge-base repo, a shared filesystem directory, a\n * `file:` dep that ships content alongside code, etc.) and you want\n * `zfb dev` to live-reload when those external files change.\n *\n * Semantics:\n *\n * - Each entry MUST be an absolute path. Relative paths are\n * rejected at config-load time with a clear error message.\n * - Paths are canonicalised when the watcher boots; events match\n * the canonical form.\n * - A path that does NOT exist at boot is skipped with a warning;\n * the watcher does NOT re-watch the path if it appears later.\n * Restart `zfb dev` after creating the path.\n * - Each entry is watched recursively.\n * - Events from outside the project root bypass fine-grained graph\n * classification and may trigger a broader rebuild than equivalent\n * in-tree edits.\n *\n * **Security note:** opt-in only — do NOT point this at unbounded\n * directories like `$HOME` or `/`. On Linux the recursive watcher\n * registers every subdirectory and can hit the inotify\n * `max_user_watches` ceiling on large trees.\n *\n * Mirrors `Config::extra_watch_paths` in crates/zfb/src/config.rs.\n */\n extraWatchPaths?: string[];\n\n /**\n * Whether `zfb build` writes the post-build route manifest to disk\n * at `<outDir>/__zfb/routes.json` (#347).\n *\n * The on-disk file mirrors the in-memory `ctx.routes` shape that the\n * plugin API hands to `postBuild` hooks — same fields, same\n * url-sorted order — so any consumer script wired into `pnpm build`\n * can read the manifest without writing a zfb plugin. The plugin\n * `ctx.routes` and the on-disk `routes.json` are two access shapes\n * over the same data, not two contracts.\n *\n * Default: emit (`undefined` is treated as `true`). Set `false` to\n * skip the write — useful for projects that strip everything but\n * shipped assets out of `dist/` before deploy.\n *\n * Mirrors `Config::emit_routes_manifest` in crates/zfb/src/config.rs.\n */\n emitRoutesManifest?: boolean;\n\n /**\n * Syntect code-highlight options; absent = default theme\n * (`base16-ocean.dark`). See {@link CodeHighlightConfig} for accepted\n * theme names and custom-theme loading.\n *\n * Mirrors `Config::code_highlight` in crates/zfb/src/config.rs.\n */\n codeHighlight?: CodeHighlightConfig;\n\n /**\n * Maximum seconds a single plugin lifecycle hook (preBuild, postBuild,\n * setup, etc.) may run before the build fails with a diagnostic error\n * and the plugin host is force-killed.\n *\n * Absent falls through to the `ZFB_PLUGIN_HOOK_TIMEOUT` env var, then\n * the 120s built-in default. Set this when your plugins do long but\n * bounded work (e.g. large sitemap generation) and you want a tighter\n * or more explicit budget.\n *\n * Mirrors `Config::plugin_hook_timeout_secs` in crates/zfb/src/config.rs.\n */\n pluginHookTimeoutSecs?: number;\n\n /**\n * Whether `copy_public_dir` copies `public/` under the `base`\n * sub-path segment (`true`, default) or flat to the `dist/` root\n * (`false`).\n *\n * - **`true` (default):** files land at\n * `<outDir>/<base-segment>/<rel>`, matching the base-prefixed URLs\n * that `withBase()` emits in the rendered HTML. Use this for\n * projects served directly at their configured sub-path.\n * - **`false`:** files land flat at `<outDir>/<rel>` regardless of\n * `base`. Use this when the deploy pipeline relocates the entire\n * `dist/` tree into the base segment itself (e.g.\n * `cp -a dist/. deploy-root/pj/site/`), so putting the files under\n * `<outDir>/<base>/...` would result in a double-nested path.\n *\n * **Note on `zfb preview`:** with `false`, base-prefixed public-asset\n * URLs 404 under `zfb preview` because the flat copy lives at the\n * dist root and `zfb preview` does not simulate deploy-side\n * relocation. This is a known trade-off of the flat-copy deploy\n * scheme.\n *\n * Mirrors `Config::copy_public_with_base` in crates/zfb/src/config.rs.\n */\n copyPublicWithBase?: boolean;\n\n /**\n * Project output mode. Drives the V8-mode decision the build engine\n * makes right after the no-SSR-without-adapter precondition check\n * (sub-task 4.1b / issue #373):\n *\n * - `\"static\"` — declare a pure-static (SSG-only) project. Errors at\n * build start if any route exports `prerender = false`, pointing\n * at the offending route. Use this on projects that must never\n * accidentally pick up an SSR route as a result of a copy-paste.\n * - `\"hybrid\"` — declare a project that may host SSR routes. V8-on\n * regardless of detection, even when no `prerender = false` route\n * currently exists. Useful for projects that will add SSR routes\n * later and want a stable build topology in the meantime.\n * - `\"auto\"` (default) — detection-driven. Non-empty `prerender =\n * false` route set => V8-on; empty => V8-off.\n *\n * Today's load-bearing role is the `\"static\"` precondition check.\n * The V8-off branch does NOT skip V8 host startup on the shipping\n * `zfb` binary — SSG still needs V8 to render pages. The flag exists\n * as infrastructure for the future shipping path (Tauri sidecar /\n * standalone SSR server). See the\n * [Build engine docs](https://github.com/Takazudo/zudo-front-builder/blob/main/docs/src/content/docs/architecture/build-engine.mdx)\n * for the gate decision table.\n *\n * Mirrors `Config::output` in crates/zfb/src/config.rs.\n */\n output?: OutputMode;\n\n /**\n * Config presets to merge before validation (#1196).\n *\n * Each preset is a partial `ZfbConfig`-shaped object. The merge pass runs\n * BEFORE field validation and folds preset contributions using additive\n * semantics:\n *\n * - **Array fields** (`plugins`, `collections`, `extraWatchPaths`,\n * `allowedHosts`): preset values are prepended so the main config's\n * entries retain their relative position after the preset's.\n * - **Scalar / optional fields**: a preset value fills in only when the\n * main config leaves the field at its default — the main config is\n * authoritative; presets act as defaults.\n *\n * Nested `presets` inside a preset are NOT recursively expanded.\n *\n * Mirrors `Config::presets` in crates/zfb/src/config.rs.\n */\n presets?: Partial<ZfbConfig>[];\n};\n\n/**\n * Project output mode.\n *\n * - `\"static\"` — pure-static (SSG-only); errors on detected SSR routes.\n * - `\"hybrid\"` — may host SSR routes; V8-on regardless of detection.\n * - `\"auto\"` — detection-driven; the default.\n *\n * Mirrors `OutputMode` in crates/zfb/src/config.rs.\n */\nexport type OutputMode = \"static\" | \"hybrid\" | \"auto\";\n\n/**\n * Syntect code-highlight options.\n *\n * Unknown theme names are rejected at build start with a clear error\n * rather than silently falling back.\n *\n * **Single-theme mode** (the default): set `theme` to a syntect theme name,\n * or omit it to use the default (`\"base16-ocean.dark\"`). Tokens are colored\n * with inline `color:`.\n *\n * **Dual-theme mode**: set both `themeLight` and `themeDark`. Tokens are\n * colored with CSS custom properties (`--shiki-light` / `--shiki-dark`),\n * and the consumer applies a `light-dark()` rule to pick the active color.\n * The `<pre>` element carries `class=\"syntect-dual\"` and\n * `--shiki-light-bg` / `--shiki-dark-bg` in its `style` attribute.\n *\n * `theme` and the dual pair are mutually exclusive. Setting only one of\n * `themeLight` / `themeDark` is an error.\n *\n * All theme names are **SYNTECT** built-in or user-loaded names (e.g.\n * `\"base16-ocean.light\"`, `\"base16-ocean.dark\"`, `\"InspiredGitHub\"`,\n * `\"Solarized (dark)\"`), NOT Shiki names like `\"dracula\"`.\n *\n * Mirrors `CodeHighlightConfig` in crates/zfb/src/config.rs.\n */\nexport type CodeHighlightConfig = {\n /**\n * Syntect built-in or user-loaded theme name. When absent the\n * pipeline defaults to `\"base16-ocean.dark\"`.\n *\n * Mutually exclusive with {@link themeLight} / {@link themeDark}.\n * Must be a SYNTECT theme name (e.g. `\"InspiredGitHub\"`), NOT a Shiki name.\n */\n theme?: string;\n /**\n * Path to a directory of `.tmTheme` files, relative to the project\n * root. Every `.tmTheme` file in the directory is loaded and becomes\n * available by its declared `name` via {@link theme}, {@link themeLight},\n * or {@link themeDark}. When absent only syntect's bundled themes are\n * available.\n *\n * The path must be relative and must not escape the project root via\n * `..`. A missing directory is reported as an error at build start.\n *\n * Applies to both single-theme and dual-theme mode.\n */\n themesDir?: string;\n /**\n * Light-mode syntect theme name for dual-theme highlighting.\n *\n * Must be set together with {@link themeDark} — setting only one of\n * the two is a build error. When both are set, tokens are colored with\n * CSS custom properties (`--shiki-light` / `--shiki-dark`) instead of\n * inline `color:`. Mutually exclusive with {@link theme}.\n *\n * Must be a SYNTECT theme name (e.g. `\"base16-ocean.light\"`),\n * NOT a Shiki name like `\"dracula\"`.\n */\n themeLight?: string;\n /**\n * Dark-mode syntect theme name for dual-theme highlighting.\n *\n * Must be set together with {@link themeLight} — setting only one of\n * the two is a build error. Mutually exclusive with {@link theme}.\n *\n * Must be a SYNTECT theme name (e.g. `\"base16-ocean.dark\"`),\n * NOT a Shiki name like `\"dracula\"`.\n */\n themeDark?: string;\n};\n\n/**\n * Table-of-contents options. Wire via `markdown.toc` in `zfb.config.ts`.\n *\n * When present, a TOC `<ul>/<li>` list is inserted as the next sibling\n * of the first heading whose text matches `heading` (case-insensitive).\n * Each `<a href=\"#id\">` links to the deduplicated `id` that\n * `HeadingLinksPlugin` placed on the corresponding heading.\n *\n * Mirrors `TocConfig` in `crates/zfb-content/src/plugins/toc.rs`.\n */\nexport type TocConfig = {\n /**\n * Heading text that triggers TOC insertion. Matched\n * case-insensitively after whitespace trimming. Default: `\"TOC\"`.\n */\n heading?: string;\n\n /**\n * Number of heading levels to include starting from `<h2>`.\n *\n * - `1` — h2 only\n * - `2` (default) — h2 + h3\n * - `3` — h2, h3, h4\n * - …up to `5` (h2 through h6)\n */\n maxDepth?: number;\n};\n\n/**\n * Markdown / MDX parsing options.\n *\n * See [`ZfbConfig.markdown`] for the embed point. Fields: [`gfm`],\n * [`toc`], [`externalLinks`], [`cjkFriendly`], and [`features`].\n * Future markdown knobs would also live here.\n *\n * See the \"Markdown Features\" docs category for the per-feature option\n * reference once individual features are ported.\n *\n * Mirrors `MarkdownConfig` in crates/zfb/src/config.rs.\n */\nexport type MarkdownConfig = {\n /**\n * Enable GFM constructs.\n *\n * Accepts three shapes:\n *\n * - `true` — turn every GFM construct ON (strikethrough, table,\n * autolink-literal, task-list-item, footnote-definition).\n * - `false` — turn every GFM construct OFF.\n * - partial object — set individual fields explicitly; fields you\n * omit fall back to the conservative-default values described\n * below.\n *\n * When `markdown` itself is omitted entirely, the conservative\n * default applies: `strikethrough: true`, `table: true`, every other\n * GFM construct off. This is the smallest behavioural delta from\n * zfb's historical effective state (table-only). Projects that want\n * the full GFM surface should opt in with `gfm: true`.\n */\n gfm?: GfmFlag;\n\n /**\n * Table-of-contents options. When present, a `<ul>/<li>` list is\n * inserted after the first heading whose text matches `heading`\n * (default `\"TOC\"`, case-insensitive). Each link points to the\n * deduplicated `id` that `HeadingLinksPlugin` placed on the heading.\n *\n * Omitting this field entirely leaves the build byte-for-byte identical\n * to the pre-TOC build. See [`TocConfig`] for the available options.\n *\n * Mirrors `MarkdownConfig::toc` in crates/zfb/src/config.rs.\n */\n toc?: TocConfig;\n /**\n * External-link rewriter. When set, every `<a>` whose href is\n * classified as external receives the configured `target` and `rel`\n * attributes.\n *\n * An href is external when it is an absolute HTTP/HTTPS URL AND its\n * origin differs from the top-level `site` URL (if `site` is\n * configured). When `site` is absent, any absolute HTTP/HTTPS URL is\n * treated as external.\n *\n * `mailto:`, `tel:`, and other non-HTTP(S) schemes are always left\n * unchanged. Relative URLs (`/internal/`, `./file.mdx`, `#anchor`) are\n * always internal.\n *\n * Omitting this field keeps the output byte-for-byte identical to the\n * pre-feature behaviour.\n *\n * Mirrors `ExternalLinksConfig` in crates/zfb/src/config.rs.\n */\n externalLinks?: ExternalLinksConfig;\n\n /**\n * Enable CJK-friendly markdown handling.\n *\n * Governs two post-parse fixups that adapt CommonMark/GFM rules to CJK\n * text:\n *\n * 1. **Emphasis/strong flanking** (`CjkFriendlyPlugin`). CommonMark's\n * left-/right-flanking delimiter-run rules treat CJK characters as\n * non-whitespace non-punctuation, which causes `**foo**` adjacent to\n * CJK text (e.g. `**テスト。**テスト`) to render as literal stars\n * instead of `<strong>`.\n * 2. **Bare-URL autolink boundary** (`CjkAutolinkBoundaryPlugin`,\n * zfb#1105). The GFM autolink-literal path grammar terminates only on\n * ASCII whitespace, so a bare URL flush against CJK text\n * (`詳細はhttps://example.com参照`) swallows the trailing CJK run into\n * the `href`. This fixup terminates the link at the first CJK\n * character. Only active when `gfm.autolinkLiteral` is also on.\n *\n * - **absent / `true` (default):** CJK-friendly handling is on.\n * Preserves today's behaviour — existing CJK-content sites are\n * unaffected.\n * - **`false`:** opt-out. Neither plugin is added to the pipeline;\n * emphasis markers and bare-URL autolinks adjacent to CJK characters\n * follow base CommonMark/GFM rules. Rarely the right choice; provided\n * as an escape hatch for projects that need strict CommonMark/GFM\n * output.\n *\n * **GFM strikethrough** (`~~foo~~`) at CJK boundaries is unaffected\n * by this toggle — it is handled by markdown-rs's GFM tokeniser, not\n * by these plugins, and works correctly in both modes.\n *\n * Mirrors `MarkdownConfig::cjk_friendly` in crates/zfb/src/config.rs.\n */\n cjkFriendly?: boolean;\n\n /**\n * Convert every soft line break (a single `\\n` inside a paragraph) into\n * `<br>` (remark-breaks parity).\n *\n * - **absent / `false` (default):** soft line breaks follow standard\n * CommonMark behaviour — collapsed into a single space.\n * - **`true`:** every `\\n` inside a paragraph becomes `<br>`. Use this\n * when your content relies on newline→`<br>` fidelity (e.g. product\n * descriptions, lyrics, or other newline-sensitive prose).\n *\n * Mirrors `MarkdownConfig::hard_breaks` in crates/zfb/src/config.rs.\n */\n hardBreaks?: boolean;\n\n /**\n * Per-feature markdown pipeline toggles.\n *\n * Each field is a [`FeatureToggle`] (`true` / `false` / options object)\n * or a feature-specific config type (for features that require extra\n * parameters). Absent / `undefined` means all features are disabled,\n * preserving the behaviour of the pre-features build byte-for-byte.\n *\n * Unknown keys are rejected at deserialization time by the Rust loader\n * so a typo in `zfb.config.ts` surfaces as a clear error.\n *\n * Mirrors `MarkdownFeaturesConfig` in crates/zfb/src/config.rs.\n */\n features?: MarkdownFeaturesConfig;\n};\n\n/**\n * Per-feature toggle: `boolean` shorthand or an options object.\n *\n * `true` enables the feature with defaults; `false` (or absent) disables it.\n * The object form carries per-feature options (fields vary by feature and\n * are filled in by each feature's port sub-issue — stubs today).\n *\n * Mirrors `FeatureToggle` in crates/zfb/src/config.rs.\n */\nexport type FeatureToggle = boolean | FeatureOptions;\n\n/**\n * Empty options object for features that accept `{ ... }` but have no\n * user-facing knobs yet. Fields are filled in by each feature's port\n * sub-issue; this stub satisfies the schema shape requirement.\n *\n * Mirrors `FeatureOptions` in crates/zfb/src/config.rs.\n */\nexport type FeatureOptions = Record<string, never>;\n\n/**\n * Options for the `githubAutolinks` feature — rewrites bare `#123`,\n * `user/repo#456`, and commit-SHA references into GitHub links.\n *\n * `repo` is required: `githubAutolinks: {}` (repo absent) is a config error\n * — the Rust pipeline emits a build-blocking diagnostic rather than\n * silently skipping the feature.\n *\n * Mirrors `GithubAutolinksConfig` in `crates/zfb-md-ast/src/features_config.rs`.\n */\nexport type GithubAutolinksConfig = {\n /**\n * GitHub repository reference (`owner/repo`) used to build autolink URLs\n * (e.g. `\"owner/repo\"` renders `#123` as\n * `https://github.com/owner/repo/issues/123`). Required — see above.\n */\n repo: string;\n};\n\n/**\n * Options stub for the `codeEnrichment` feature.\n *\n * TODO: fill in actual fields when the codeEnrichment feature is ported.\n *\n * Mirrors `CodeEnrichmentConfig` in crates/zfb/src/config.rs.\n */\nexport type CodeEnrichmentConfig = Record<string, never>;\n\n/**\n * Options for the `tocExport` feature.\n *\n * Controls which headings are included in the exported `toc` JSON.\n * `maxDepth` is the **absolute** heading depth (2–6):\n * - `2` → h2 only\n * - `3` (default) → h2 + h3\n *\n * This differs from `headingMarkerToc.maxDepth`, which counts levels\n * starting from h2. The two features are independent.\n *\n * Mirrors `TocExportConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type TocExportConfig = {\n /** Maximum heading depth to include (absolute, 2–6). Default: 3. */\n maxDepth?: number;\n};\n\n/**\n * Options for the `imageDimensions` feature.\n *\n * Auto-detects and injects `width`/`height` on local `<img>` elements. Raster\n * formats are probed header-only; SVGs are read from their markup\n * (`width`/`height`/`viewBox`).\n *\n * Mirrors `ImageDimensionsConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type ImageDimensionsConfig = {\n /**\n * When `true` (the default), `http://` and `https://` image sources are\n * silently skipped and not probed for dimensions. Set to `false` only for\n * testing or unusual setups — remote images require network access at build\n * time and slow the pipeline.\n */\n skipRemote?: boolean;\n};\n\n/**\n * Options for the `linkValidation` feature.\n *\n * Validates internal `[text](file.md#anchor)` and `[text](#anchor)` links at\n * build time. External URLs (`http://`, `https://`, `mailto:`) are always\n * skipped — network validation is out of scope.\n *\n * Mirrors `LinkValidationConfig` in `crates/zfb-md-ast/src/features_config.rs`.\n */\nexport type LinkValidationConfig = {\n /**\n * When `true`, broken links are reported as errors (build can fail).\n * Default: `false` (warn-only).\n */\n failOnBroken?: boolean;\n};\n\n/**\n * Options for the `transclude` feature.\n *\n * Enables `:::include{file=\"./path.md\"}` directives that inline another\n * file's parsed mdast at the include site.\n *\n * Mirrors `TranscludeConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type TranscludeConfig = {\n /**\n * Maximum transclusion depth (chain length A→B→C→…).\n *\n * A depth of `1` allows only direct includes (the included file itself\n * cannot include further files). Default: `5`. A cycle (A→B→A) is\n * always detected regardless of `maxDepth` and treated as an error.\n */\n maxDepth?: number;\n};\n\n/**\n * Options for the `readingTime` feature.\n *\n * Mirrors `ReadingTimeOptions` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type ReadingTimeConfig = {\n /** Words-per-minute rate for the reading-time estimate. Default: 200. */\n wpm?: number;\n};\n\n/**\n * `readingTime` feature value: either a `boolean` shorthand or a\n * {@link ReadingTimeConfig} options object.\n *\n * Mirrors `ReadingTimeFeature` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type ReadingTimeFeature = boolean | ReadingTimeConfig;\n\n/**\n * Per-feature markdown pipeline configuration.\n *\n * All fields are optional; absent = feature disabled, behaviour unchanged\n * from the pre-features build. Unknown keys are rejected at deserialization\n * time by the Rust loader so a typo surfaces as a clear error.\n *\n * Mirrors `MarkdownFeaturesConfig` in crates/zfb/src/config.rs.\n */\nexport type MarkdownFeaturesConfig = {\n /** GitHub-style alert blocks (`> [!NOTE]`, `> [!WARNING]`, etc.). */\n githubAlerts?: FeatureToggle;\n\n /**\n * Reading-time estimate injected into the document frontmatter.\n * Accepts `true` / `false` shorthand or `{ wpm: N }` for a custom rate.\n */\n readingTime?: ReadingTimeFeature;\n\n /** GitHub-style `owner/repo#123` and `SHA` autolinks. Requires `repo`. */\n githubAutolinks?: GithubAutolinksConfig;\n\n /** Code-block enrichment (copy button, language label, etc.). */\n codeEnrichment?: CodeEnrichmentConfig;\n\n /** Grouped code blocks rendered as tabs. */\n codeTabs?: FeatureToggle;\n\n /** Ruby annotation support (`{base}^{ruby}` syntax). */\n ruby?: FeatureToggle;\n\n /** Export the page TOC as structured data (e.g. for sidebar rendering). */\n tocExport?: TocExportConfig;\n\n /** Auto-detect and inject `width`/`height` on `<img>` elements. */\n imageDimensions?: ImageDimensionsConfig;\n\n /**\n * Validate internal links (file-relative paths and anchor fragments) at\n * build time. External URLs are always skipped — network validation is\n * out of scope.\n */\n linkValidation?: LinkValidationConfig;\n\n /**\n * Transclusion of other markdown/MDX files via\n * `:::include{file=\"./path.md\"}` — NOT the Obsidian `[[path]]` wikilink\n * syntax.\n */\n transclude?: TranscludeConfig;\n\n /**\n * Generic `:::name` → component map. You supply the components; no defaults\n * are registered. Keys are directive names (e.g. `\"foo\"`), values are\n * {@link DirectiveSpec} (bare component name string or options object).\n *\n * Mirrors `directives` in `MarkdownFeaturesConfig` in crates/zfb/src/config.rs.\n */\n directives?: Record<string, DirectiveSpec>;\n\n /** Mermaid diagram rendering. */\n mermaid?: FeatureToggle;\n\n /**\n * Inline heading-marker TOC. Accepts either a `boolean` shorthand\n * (`true` = enable with defaults, `false` = disable) or a full\n * {@link TocConfig} options object — same union shape as the Rust\n * `HeadingMarkerTocFeature` enum.\n */\n headingMarkerToc?: HeadingMarkerTocFeature;\n\n /**\n * Heading-ID strategy for the always-on `HeadingLinks` plugin.\n * Absent → `\"flat\"` (the long-standing github-slugger scheme).\n * `{ strategy: \"hierarchical\" }` opts into ancestor-prefixed anchor\n * IDs (`## Foo` / `### Moo` / `#### Mew` → `foo`, `foo-moo`,\n * `foo-moo-mew`) — see {@link HeadingIdsConfig}.\n */\n headingIds?: HeadingIdsConfig;\n};\n\n/**\n * Options for the `headingIds` entry in `markdown.features`.\n *\n * Configures the always-on `HeadingLinks` plugin rather than toggling an\n * opt-in feature. Note: switching to `\"hierarchical\"` is anchor-breaking\n * for existing deep links to nested headings.\n *\n * Mirrors `HeadingIdsConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type HeadingIdsConfig = {\n /**\n * `\"flat\"` (default): github-slugger slugs with a per-document dedup\n * counter shared across h2–h6 (`overview`, `overview-1`, …).\n * `\"hierarchical\"`: each heading's slug is prefixed with its ancestor\n * chain and deduped on the full path — anchors become reconstructible\n * from the heading outline.\n */\n strategy?: \"flat\" | \"hierarchical\";\n};\n\n/**\n * `headingMarkerToc` feature value: either a `boolean` shorthand or a\n * full {@link TocConfig} options object.\n *\n * Mirrors `HeadingMarkerTocFeature` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type HeadingMarkerTocFeature = boolean | TocConfig;\n\n/**\n * Spec for one user-defined directive: either a bare component name string\n * or a full {@link DirectiveFullSpec} options object.\n *\n * Mirrors `DirectiveSpec` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type DirectiveSpec = string | DirectiveFullSpec;\n\n/**\n * Full options object for one user-defined directive.\n *\n * Mirrors `DirectiveFullSpec` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type DirectiveFullSpec = {\n /** JSX component identifier (e.g. `\"Spoiler\"`, `\"Kbd\"`). */\n component: string;\n /** Container/leaf/text shape. Defaults to `\"container\"` when absent. */\n kind?: \"container\" | \"leaf\" | \"text\";\n /** Whether the bracketed `[label]` becomes a `title` attribute. Defaults to `true`. */\n titleFromLabel?: boolean;\n};\n\n/**\n * Options for the external-link rewriter (port of `rehype-external-links`).\n *\n * All fields are optional; omitting a field applies the documented default.\n *\n * Mirrors `ExternalLinksConfig` in crates/zfb/src/config.rs.\n */\nexport type ExternalLinksConfig = {\n /**\n * `rel` tokens applied to external links.\n *\n * Default: `[\"noopener\", \"noreferrer\"]`.\n *\n * Tokens are deduplicated (case-insensitive) and merged with any\n * existing `rel` attribute on the `<a>` element — existing tokens\n * appear first.\n */\n rel?: string[];\n /**\n * `target` value for external links.\n *\n * Default: `\"_blank\"`.\n */\n target?: string;\n};\n\n/**\n * Either the shorthand boolean form (`true` = all GFM constructs on,\n * `false` = all off) or a partial object that toggles individual\n * constructs.\n *\n * Mirrors `GfmFlag` in crates/zfb/src/config.rs.\n */\nexport type GfmFlag = boolean | GfmConstructs;\n\n/**\n * Per-construct opt-in / opt-out for GFM. Every field is optional;\n * omitted fields fall back to the conservative default\n * (`strikethrough: true`, `table: true`, others `false`).\n *\n * Mirrors `GfmConstructs` in crates/zfb/src/config.rs.\n */\nexport type GfmConstructs = {\n /** GFM strikethrough (`~~text~~` → `<del>text</del>`). */\n strikethrough?: boolean;\n /** GFM pipe-style tables. */\n table?: boolean;\n /**\n * GFM autolink literal — bare URLs like `https://example.com` become\n * clickable links without `<…>` brackets.\n */\n autolinkLiteral?: boolean;\n /** GFM task list items (`- [x]` / `- [ ]`). */\n taskListItem?: boolean;\n /** GFM footnote definitions (`[^ref]: …`). */\n footnoteDefinition?: boolean;\n};\n\n/**\n * What to do when a `.md`/`.mdx` link cannot be resolved.\n *\n * Mirrors `OnBrokenLinks` in crates/zfb/src/config.rs.\n */\nexport type OnBrokenLinks = \"warn\" | \"error\" | \"ignore\";\n\n/**\n * Config for the markdown link resolver. See\n * [`ZfbConfig.resolveMarkdownLinks`] for the design rationale.\n */\nexport type ResolveMarkdownLinksConfig = {\n /** Whether to enable link resolution. Default: `false`. */\n enabled?: boolean;\n\n /**\n * Legacy single-dir field. Used only when [`dirs`] is empty. When\n * non-empty, scanned against the hard-coded `/docs/` route prefix.\n */\n docsDir?: string;\n\n /**\n * Explicit per-dir source map. Each entry is one collection (e.g.\n * EN docs at `src/content/docs/` → `/docs/`, JA docs at\n * `src/content/docs-ja/` → `/ja/docs/`). Takes precedence over\n * [`docsDir`] when non-empty.\n */\n dirs?: ResolveMarkdownLinksDir[];\n\n /** What to do with unresolved `.md`/`.mdx` links. Default: `\"warn\"`. */\n onBrokenLinks?: OnBrokenLinks;\n};\n\n/** One source-dir entry for [`ResolveMarkdownLinksConfig.dirs`]. */\nexport type ResolveMarkdownLinksDir = {\n /**\n * Directory (relative to project root) whose `.md`/`.mdx` files are\n * scanned. Must be relative and must not escape the root via `..`.\n */\n dir: string;\n\n /**\n * Route prefix prepended to each file's slug. Include leading and\n * trailing slashes (e.g. `\"/docs/\"` or `\"/ja/docs/\"`).\n */\n routePrefix: string;\n};\n\n/**\n * Identity helper: returns the supplied config as-is, but typed against\n * [`ZfbConfig`]. Use as the default export of `zfb.config.ts` so editors\n * surface field-level types and typos surface at compile time.\n */\nexport function defineConfig(config: ZfbConfig): ZfbConfig {\n return config;\n}\n\n/**\n * Preset authoring helper: stamps each object entry in `config.plugins`\n * with `source_package: sourcePackage` so the Rust loader can attribute\n * plugin contributions back to the preset package that provided them.\n *\n * - Only plain-object plugin entries are stamped; non-object entries pass\n * through unchanged (defensive — the current schema requires objects,\n * but this guard keeps the helper safe if the schema is ever relaxed).\n * - An entry that ALREADY carries a `source_package` is left untouched, so a\n * preset composing another `definePreset`-returned preset (by spreading its\n * `plugins`) keeps the inner preset's provenance instead of clobbering it\n * with the outer package name (the spread below lets the existing marker win).\n * - When `config.plugins` is absent, the config is returned as-is.\n * - All other fields of `config` pass through unchanged.\n *\n * The key `source_package` (snake_case) mirrors the Rust `PluginConfig`\n * serde field added in T4. `PluginConfig` has no `#[serde(rename_all)]`\n * so the serde key is the field name verbatim — do NOT use camelCase.\n *\n * SYNC REQUIREMENT: keep this implementation behaviourally identical to\n * the stub in crates/zfb-config-loader/js/zfb-config-stub.mjs, which is\n * injected at config-eval time when the user's project does not have the\n * zfb npm package installed locally.\n */\nexport function definePreset(\n sourcePackage: string,\n config: Partial<ZfbConfig>,\n): Partial<ZfbConfig> {\n if (!config.plugins) {\n return config;\n }\n return {\n ...config,\n plugins: config.plugins.map((plugin) => {\n if (plugin !== null && typeof plugin === \"object\" && !Array.isArray(plugin)) {\n // Default first, then spread the plugin so an existing `source_package`\n // (from a composed inner preset) wins over the outer package name.\n return { source_package: sourcePackage, ...plugin };\n }\n return plugin;\n }),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,kEAAkE;AAClE,qEAAqE;AACrE,uEAAuE;AACvE,oEAAoE;AACpE,+BAA+B;AAC/B,EAAE;AACF,yEAAyE;AACzE,uEAAuE;AACvE,uEAAuE;AACvE,kEAAkE;AAClE,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AAkuCvE;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,MAAiB;IAC5C,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,YAAY,CAC1B,aAAqB,EACrB,MAA0B;IAE1B,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,OAAO;QACL,GAAG,MAAM;QACT,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;YACrC,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC5E,wEAAwE;gBACxE,mEAAmE;gBACnE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,GAAG,MAAM,EAAE,CAAC;YACtD,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["// `zfb/config` — TypeScript helper for the `zfb.config.ts` form.\n//\n// The zfb config loader (`crates/zfb/src/config.rs`) accepts both\n// `zfb.config.ts` and `zfb.config.json`; TS wins when both files are\n// present. JSON remains accepted for projects predating the TS loader,\n// while new projects should prefer the TS form for editor types and\n// `defineConfig` autocomplete.\n//\n// At parse time, zfb bundles the user's `zfb.config.ts` with esbuild and\n// aliases this `zfb/config` import to an internal stub that re-exports\n// `defineConfig` as the identity function — so a user project does not\n// need the `zfb` npm package installed locally just to be parsed.\n//\n// The shape mirrors the Rust `Config` struct one-for-one. Keep them in\n// sync; the `defineConfig` identity helper is the single anchor point.\n\nexport type Framework = \"preact\" | \"react\";\n\nexport type CollectionDef = {\n /** Identifier used at the call site (e.g. `\"blog\"`). */\n name: string;\n /** Directory (relative to the project root) holding the entries. */\n path: string;\n /** Optional schema. Enforced by `zfb check`. */\n schema?: Record<string, unknown>;\n /**\n * Optional include globs (Astro-style, evaluated relative to `path`).\n * When set and non-empty, an entry is kept only if at least one\n * pattern matches its relative path. When omitted or empty, no\n * include-filtering happens. Patterns use the `globset` dialect\n * (Unix-style: `*`, `**`, `?`, `[…]`).\n */\n include?: string[];\n /**\n * Optional exclude globs. When set, an entry is dropped if any\n * pattern matches its relative path. Evaluated AFTER `include`.\n * Together they mirror Astro's `['**\\/*.mdx', '!**\\/*.en.mdx']`\n * convention (zfb splits the negative side into its own field).\n */\n exclude?: string[];\n /**\n * Optional suffix to strip from each kept entry's slug + module\n * specifier. Use with multi-locale layouts where one source\n * directory holds both `foo.mdx` (default locale) and `foo.en.mdx`\n * (locale override) — set `idStripSuffix: \".en\"` so the EN\n * collection's slugs round-trip as `foo` instead of `foo.en`.\n */\n idStripSuffix?: string;\n /**\n * Opt-in to a `path` that escapes the project root via `..` (e.g. a\n * monorepo-shared content dir living outside this package). Default\n * `false` keeps the standard project-root guard. Absolute paths and\n * Windows drive-relative/prefix forms are rejected regardless of\n * this flag — only `..`-relative escapes are relaxed.\n *\n * Security note: if this collection comes from a preset, the preset\n * author — not the consuming project — controls `path`. Setting\n * `allowOutsideRoot: true` on a preset-provided collection widens\n * the project's read surface to wherever that preset points, so\n * treat it the same as any other preset-granted filesystem access.\n */\n allowOutsideRoot?: boolean;\n};\n\nexport type TailwindConfig = {\n /** Whether Tailwind is enabled. Default: `true`. */\n enabled?: boolean;\n};\n\n/**\n * Prefetch options. Mirrors `PrefetchConfig` in `crates/zfb/src/config.rs`.\n */\nexport type PrefetchConfig = {\n /**\n * Disable prefetch entirely.\n *\n * When `true`, the bundler emits `globalThis.__zfb.prefetchDisabled = true`\n * in `entry.mjs`, and `<ClientRouter />` renders\n * `<meta name=\"zfb-prefetch-disabled\" content=\"true\">` in `<head>`.\n * The sibling prefetch-core module reads that meta tag at `init()` time\n * and short-circuits — no prefetch wiring runs.\n *\n * The flag is site-wide and static — set once at bundle-emit time,\n * never recomputed per-page. Default: `false`.\n */\n disabled?: boolean;\n};\n\n/**\n * Bundler options. Mirrors `BundleConfig` in `crates/zfb/src/config.rs`.\n */\nexport type BundleConfig = {\n /**\n * Project-relative glob patterns (gitignore-style) for source files\n * the bundler must NOT pull into the esbuild graph.\n *\n * Why this exists: an eager `import.meta.glob('components/**\\/*.stories.tsx',\n * { eager: true })` expands to a static import of every matched file. If a\n * matched file imports a CJS-only package whose `package.json` resolves only\n * via `main`/`module` or a `require`-only `exports` condition (e.g.\n * `msw` → `path-to-regexp@6`), esbuild — invoked with `--platform=neutral`\n * for the worker bundle — rejects it with \"Could not resolve … Main fields\n * must be configured explicitly when using the neutral platform.\" Listing the\n * offending file here keeps the migration build green.\n *\n * Each pattern is matched against the file's path RELATIVE TO THE PROJECT\n * ROOT, in POSIX form (e.g. `components/Foo.stories.tsx` or\n * `components/**\\/*.stories.tsx`). A matched file is:\n *\n * - never copied/symlinked into the bundler's shadow tree, and\n * - dropped from any eager `import.meta.glob(...)` expansion that would\n * otherwise statically import it.\n *\n * Unset / empty → behaviour is byte-identical to a build without this knob:\n * no files are skipped.\n *\n * Mirrors `Config::bundle` in crates/zfb/src/config.rs.\n */\n exclude?: string[];\n\n /**\n * Explicit esbuild `main-fields` list for the `--platform=neutral` page/SSR\n * pass. Under `neutral` esbuild's main-fields list is EMPTY by default, so a\n * dep resolved purely via `package.json` `main`/`module` (no `exports` map)\n * is rejected (\"The \"main\" field here was ignored. Main fields must be\n * configured explicitly when using the neutral platform.\"). Set e.g.\n * `[\"main\", \"module\"]` to let such CJS-main-only deps resolve (#676 —\n * `msw` → `path-to-regexp@6`). Applies to every framework; unset/empty →\n * byte-identical to a build without the knob (the React-only `main,module`\n * shim still applies).\n *\n * Mirrors `BundleConfig::main_fields` in `crates/zfb/src/config.rs`.\n */\n mainFields?: string[];\n\n /**\n * Bare specifiers to mark external in the `--platform=neutral` page/SSR\n * pass, so esbuild leaves them unbundled instead of resolving them (the\n * other #676 escape hatch — externalize a CJS-only dep rather than\n * resolving it). Appended to the framework-provided externals. Unset/empty\n * → no extra externals.\n *\n * Mirrors `BundleConfig::external` in `crates/zfb/src/config.rs`.\n */\n external?: string[];\n\n /**\n * Additional esbuild loaders keyed by file extension (for example\n * `{ \".txt\": \"text\" }`). Only inline loaders are supported: `file` and\n * `copy` are intentionally excluded because they emit sibling assets the\n * client bundlers do not publish. `.css`, `.module.css`, `.mdx`, and `.md`\n * are reserved by zfb and rejected during config validation.\n */\n loaders?: Record<string, \"text\" | \"json\" | \"base64\" | \"dataurl\" | \"binary\" | \"empty\">;\n\n /**\n * Operator-authored esbuild define substitutions. Values are raw esbuild\n * expressions; string values must be pre-quoted JSON (for example\n * `{ __APP_NAME__: '\"my-app\"' }`). The mode-owned keys\n * `import.meta.env.PROD`, `import.meta.env.DEV`, and\n * `process.env.NODE_ENV` are reserved and rejected at config-load time.\n */\n define?: Record<string, string>;\n};\n\n/**\n * One plugin entry in `zfb.config.ts`.\n *\n * `name` MUST be a module reference that Node's resolver can locate from\n * the project root. The zfb config loader\n * (`crates/zfb-config-loader/js/config-loader.mjs`) resolves it to an\n * absolute module specifier and the build / dev plugin host loads it via\n * dynamic `import()`:\n *\n * - `\"./plugins/my-plugin.mjs\"` / `\"../shared/plugin.mjs\"` —\n * path-relative to the project root (the dir containing `zfb.config.ts`).\n * - `\"/abs/path/to/plugin.mjs\"` — absolute filesystem path.\n * - `\"@takazudo/zfb-plugin-search\"` / `\"my-plugin\"` — npm bare specifier\n * resolved against the project's `node_modules`.\n *\n * Inline-function hooks are NOT supported; the plugin module's default\n * export must be a [`ZfbPlugin`] (see `@takazudo/zfb/plugins`).\n *\n * `options` is passed verbatim to the plugin's hook contexts; treat\n * the schema as plugin-specific.\n */\nexport type PluginConfig = {\n name: string;\n options?: Record<string, unknown>;\n};\n\nexport type ZfbConfig = {\n /** Output directory for built assets. Default: `dist`. */\n outDir?: string;\n /** Public/static directory copied verbatim. Default: `public`. */\n publicDir?: string;\n /** Optional dev/preview server bind host. */\n host?: string;\n /** Optional dev/preview server port. */\n port?: number;\n /**\n * Host header values the dev/preview server accepts when bound to a\n * non-localhost interface (`--host 0.0.0.0`, the bare `--host` LAN\n * shortcut, or `host` above) — the DNS-rebinding guard, mirroring\n * Vite's `server.allowedHosts`.\n *\n * Defaults: only consulted for non-loopback binds — the default\n * `localhost` bind skips validation entirely. `localhost`, the\n * explicitly bound host, and any IP-literal Host — `127.0.0.1`,\n * `[::1]`, the LAN URLs the startup banner prints — are always\n * allowed (DNS rebinding needs a DNS name, so raw IPs are safe;\n * Vite parity); requests with any other Host get a 403.\n *\n * Matching rules (the request Host's port is stripped first and\n * comparison is case-insensitive):\n *\n * - `\"example.com\"` — matches exactly that host.\n * - `\".example.com\"` (leading dot) — matches `example.com` and every\n * subdomain (`api.example.com`).\n * - IPv6 entries may be written with or without brackets\n * (`\"[::1]\"` / `\"::1\"`).\n *\n * Mirrors `Config::allowed_hosts` in `crates/zfb/src/config.rs`.\n */\n allowedHosts?: string[];\n /** JSX framework runtime. Default: `preact`. */\n framework?: Framework;\n /** Content collections. Mirrors the JSON form one-for-one. */\n collections?: CollectionDef[];\n /** Tailwind options; absent = defaults. */\n tailwind?: TailwindConfig;\n /**\n * Prefetch options. When `disabled: true`, the build emits a meta tag\n * that the runtime's prefetch-core module reads at init time to skip\n * all prefetch wiring. Mirrors `Config::prefetch` in\n * `crates/zfb/src/config.rs`.\n */\n prefetch?: PrefetchConfig;\n /**\n * Minify production HTML output from `zfb build`. Default: `false`.\n *\n * The implementation is Rust-only and does not spawn a Node.js minifier\n * subprocess. The first version is intentionally conservative: rendered\n * `.html` pages are candidates, source `.html` passthrough pages remain\n * verbatim, and non-HTML outputs are skipped.\n *\n * Mirrors `Config::minify_html` in `crates/zfb/src/config.rs`.\n */\n minifyHtml?: boolean;\n /**\n * Bundler options. `bundle.exclude` lists project-relative globs of\n * source files to keep out of the esbuild graph (e.g.\n * `[\"components/*.stories.tsx\"]`) — see {@link BundleConfig.exclude} for\n * why this is needed. Unset → byte-identical to a build without the knob.\n * Mirrors `Config::bundle` in `crates/zfb/src/config.rs`.\n */\n bundle?: BundleConfig;\n /** User-supplied plugins. */\n plugins?: PluginConfig[];\n /**\n * Deploy-target adapter package name. Omit (or `\"none\"`) for a pure\n * static build — any route exporting `prerender = false` is then a\n * hard build error. A package name like\n * `\"@takazudo/zfb-adapter-cloudflare\"` selects the matching adapter,\n * and `zfb build` invokes that package's bin to wrap the SSR bundle\n * into a deploy-ready entry (e.g. `dist/_worker.js` for Cloudflare\n * Workers Static Assets, Pages-compatible).\n *\n * Mirrors `Config::adapter` in crates/zfb/src/config.rs.\n */\n adapter?: string;\n /**\n * Strip `.md` / `.mdx` from internal `<a href>` paths during MDX\n * compilation, and append a trailing `/` so the resulting URL shape\n * converges with the rest of the site (mirrors the JS engine's\n * `rehypeStripMdExtension`). Default: `false`.\n *\n * Enable this when content authors hand-write `[label](other.md)`\n * style references that should resolve to the rendered route URL\n * (e.g. `other/`) instead of a literal file path. Built dist and\n * `pnpm dev` honour the same flag, so previews match shipped output.\n *\n * Mirrors `Config::strip_md_ext` in crates/zfb/src/config.rs.\n */\n stripMdExt?: boolean;\n\n /**\n * Public URL prefix mounted in front of every absolute HTML asset\n * URL the build emits — `<link rel=\"stylesheet\">`, `<script type=\"module\">`,\n * and any other `/assets/...`-prefixed reference rewritten by the\n * production asset pipeline.\n *\n * Use this when the site is deployed under a sub-path (e.g.\n * `https://example.com/pj/zudo-doc/`) instead of the domain root.\n * With `base: \"/pj/zudo-doc/\"` the dist HTML emits\n * `<link rel=\"stylesheet\" href=\"/pj/zudo-doc/assets/styles-<hash>.css\">`\n * instead of the unprefixed `/assets/styles-<hash>.css`.\n *\n * Accepted shapes (all normalised to a single canonical form\n * internally):\n *\n * - omitted / `undefined` / `\"\"` / `\"/\"` — no prefix; behaviour is\n * byte-identical to the pre-`base` build (root-mounted site).\n * - leading-and-trailing-slash path like `\"/pj/zudo-doc/\"` — prefix\n * that path onto every asset URL.\n * - absolute URL like `\"https://cdn.example.com/\"` — emit absolute\n * URLs (CDN-hosted assets).\n *\n * Inputs missing a leading or trailing `/` are normalised at config-\n * load time (paths) or asset-emit time (URL prefixes); callers do\n * not have to pre-trim.\n *\n * Mirrors `Config::base` in crates/zfb/src/config.rs.\n */\n base?: string;\n\n /**\n * Canonical origin URL for the site (e.g. `\"https://example.com\"`).\n *\n * When set, the bundler emits `globalThis.__zfb.site = <value>` in\n * `entry.mjs` so layouts can build canonical `<link>` tags,\n * OpenGraph `og:url` meta, sitemap absolute hrefs, and hreflang\n * `<link rel=\"alternate\">` from a single config-level source of truth.\n *\n * **Distinct from `base`**: `base` is a sub-path mount prefix used\n * for asset URLs (e.g. `\"/pj/my-site/\"`). `site` is the full\n * canonical origin (scheme + host, no path) used to construct\n * absolute page URLs for SEO/social metadata. Both may be set\n * simultaneously.\n *\n * Accepted shape: an absolute HTTP or HTTPS URL. Relative URLs,\n * non-HTTP(S) schemes, and empty strings are rejected at config-load\n * time. Trailing slash normalisation is the consumer's responsibility.\n *\n * When absent, `globalThis.__zfb.site` is not emitted — the build\n * output is byte-for-byte identical to builds without this field.\n *\n * Mirrors `Config::site` in crates/zfb/src/config.rs.\n */\n site?: string;\n\n /**\n * Markdown link resolver (port of `remarkResolveMarkdownLinks`).\n *\n * When `enabled: true`, the build appends `ResolveLinksPlugin` to the\n * mdast pipeline so author-written `[label](./other.mdx)` links are\n * rewritten to the corresponding rendered route URL — bypassing the\n * file→directory transformation that breaks relative paths in dist\n * HTML when `foo.mdx` becomes `foo/index.html`. Extensionless\n * (`./other`) and directory-style (`other/`) targets resolve too,\n * probing `{name}.mdx`, `{name}.md`, `{name}/index.mdx`,\n * `{name}/index.md` in that order. Relative targets resolve from the\n * source file's directory; for a directory-style link written from a\n * non-index page against its rendered URL — which sits one directory\n * deeper, e.g. `../sibling/` from `section/article.mdx` — a URL-space\n * fallback retries the probe from the page's route directory when\n * every file-space candidate misses.\n *\n * Two ways to specify the source dirs:\n *\n * - **Single dir (legacy):** set `docsDir` and the build assumes the\n * `/docs/` route prefix. Convenient for single-locale projects.\n * - **Multi dir (`dirs` non-empty):** explicit `{ dir, routePrefix }`\n * entries — required for any project with locale mirrors (e.g.\n * `docs/` AND `docs-ja/`) so each dir maps to its own route prefix\n * (`/docs/` vs `/ja/docs/`). When `dirs` is non-empty, `docsDir`\n * is ignored.\n *\n * Mirrors `Config::resolve_markdown_links` in crates/zfb/src/config.rs.\n */\n resolveMarkdownLinks?: ResolveMarkdownLinksConfig;\n\n /**\n * Whether the basePath rewriter should append a trailing `/` to\n * extensionless absolute hrefs (`<a href=\"/docs/foo\">` becomes\n * `<a href=\"/pj/zudo-doc/docs/foo/\">` when `base = \"/pj/zudo-doc/\"`\n * and this is `true`).\n *\n * Off by default — preserves byte-for-byte parity with the\n * pre-`trailingSlash` build for projects that haven't opted in.\n * Enable when the deploy target serves canonical URLs with trailing\n * slashes (Cloudflare Pages with `trailingSlash: always`, Netlify\n * pretty URLs, etc.) so the dist HTML doesn't ship non-canonical\n * hrefs that 301-redirect on every click.\n *\n * Only the trailing slash for extensionless hrefs is affected.\n * Hrefs that already end in `/`, that have a file extension\n * (`.png`, `.pdf`, …), or that opt out via `data-no-base` pass\n * through unchanged.\n *\n * Mirrors `Config::trailing_slash` in crates/zfb/src/config.rs.\n */\n trailingSlash?: boolean;\n\n /**\n * Markdown / MDX parsing options. Currently the only knob exposed is\n * [`gfm`](MarkdownConfig.gfm), which toggles GFM constructs\n * (strikethrough, table, autolink-literal, task-list-item,\n * footnote-definition) on or off.\n *\n * Mirrors `Config::markdown` in crates/zfb/src/config.rs.\n */\n markdown?: MarkdownConfig;\n\n /**\n * Extra absolute filesystem paths watched by the dev server in\n * addition to the project-root tree.\n *\n * Use this when project content reads from outside the project root\n * (a sibling knowledge-base repo, a shared filesystem directory, a\n * `file:` dep that ships content alongside code, etc.) and you want\n * `zfb dev` to live-reload when those external files change.\n *\n * Semantics:\n *\n * - Each entry MUST be an absolute path. Relative paths are\n * rejected at config-load time with a clear error message.\n * - Paths are canonicalised when the watcher boots; events match\n * the canonical form.\n * - A path that does NOT exist at boot is skipped with a warning;\n * the watcher does NOT re-watch the path if it appears later.\n * Restart `zfb dev` after creating the path.\n * - Each entry is watched recursively.\n * - Events from outside the project root bypass fine-grained graph\n * classification and may trigger a broader rebuild than equivalent\n * in-tree edits.\n *\n * **Security note:** opt-in only — do NOT point this at unbounded\n * directories like `$HOME` or `/`. On Linux the recursive watcher\n * registers every subdirectory and can hit the inotify\n * `max_user_watches` ceiling on large trees.\n *\n * Mirrors `Config::extra_watch_paths` in crates/zfb/src/config.rs.\n */\n extraWatchPaths?: string[];\n\n /**\n * Whether `zfb build` writes the post-build route manifest to disk\n * at `<outDir>/__zfb/routes.json` (#347).\n *\n * The on-disk file mirrors the in-memory `ctx.routes` shape that the\n * plugin API hands to `postBuild` hooks — same fields, same\n * url-sorted order — so any consumer script wired into `pnpm build`\n * can read the manifest without writing a zfb plugin. The plugin\n * `ctx.routes` and the on-disk `routes.json` are two access shapes\n * over the same data, not two contracts.\n *\n * Default: emit (`undefined` is treated as `true`). Set `false` to\n * skip the write — useful for projects that strip everything but\n * shipped assets out of `dist/` before deploy.\n *\n * Mirrors `Config::emit_routes_manifest` in crates/zfb/src/config.rs.\n */\n emitRoutesManifest?: boolean;\n\n /**\n * Syntect code-highlight options; absent = default theme\n * (`base16-ocean.dark`) and inline color mode. See\n * {@link CodeHighlightConfig} for accepted theme names, custom-theme\n * loading, and the class-emission mode (Highlight Tokens epic).\n *\n * Mirrors `Config::code_highlight` in crates/zfb/src/config.rs.\n */\n codeHighlight?: CodeHighlightConfig;\n\n /**\n * Maximum seconds a single plugin lifecycle hook (preBuild, postBuild,\n * setup, etc.) may run before the build fails with a diagnostic error\n * and the plugin host is force-killed.\n *\n * Absent falls through to the `ZFB_PLUGIN_HOOK_TIMEOUT` env var, then\n * the 120s built-in default. Set this when your plugins do long but\n * bounded work (e.g. large sitemap generation) and you want a tighter\n * or more explicit budget.\n *\n * Mirrors `Config::plugin_hook_timeout_secs` in crates/zfb/src/config.rs.\n */\n pluginHookTimeoutSecs?: number;\n\n /**\n * Whether `copy_public_dir` copies `public/` under the `base`\n * sub-path segment (`true`, default) or flat to the `dist/` root\n * (`false`).\n *\n * - **`true` (default):** files land at\n * `<outDir>/<base-segment>/<rel>`, matching the base-prefixed URLs\n * that `withBase()` emits in the rendered HTML. Use this for\n * projects served directly at their configured sub-path.\n * - **`false`:** files land flat at `<outDir>/<rel>` regardless of\n * `base`. Use this when the deploy pipeline relocates the entire\n * `dist/` tree into the base segment itself (e.g.\n * `cp -a dist/. deploy-root/pj/site/`), so putting the files under\n * `<outDir>/<base>/...` would result in a double-nested path.\n *\n * **Note on `zfb preview`:** with `false`, base-prefixed public-asset\n * URLs 404 under `zfb preview` because the flat copy lives at the\n * dist root and `zfb preview` does not simulate deploy-side\n * relocation. This is a known trade-off of the flat-copy deploy\n * scheme.\n *\n * Mirrors `Config::copy_public_with_base` in crates/zfb/src/config.rs.\n */\n copyPublicWithBase?: boolean;\n\n /**\n * Project output mode. Drives the V8-mode decision the build engine\n * makes right after the no-SSR-without-adapter precondition check\n * (sub-task 4.1b / issue #373):\n *\n * - `\"static\"` — declare a pure-static (SSG-only) project. Errors at\n * build start if any route exports `prerender = false`, pointing\n * at the offending route. Use this on projects that must never\n * accidentally pick up an SSR route as a result of a copy-paste.\n * - `\"hybrid\"` — declare a project that may host SSR routes. V8-on\n * regardless of detection, even when no `prerender = false` route\n * currently exists. Useful for projects that will add SSR routes\n * later and want a stable build topology in the meantime.\n * - `\"auto\"` (default) — detection-driven. Non-empty `prerender =\n * false` route set => V8-on; empty => V8-off.\n *\n * Today's load-bearing role is the `\"static\"` precondition check.\n * The V8-off branch does NOT skip V8 host startup on the shipping\n * `zfb` binary — SSG still needs V8 to render pages. The flag exists\n * as infrastructure for the future shipping path (Tauri sidecar /\n * standalone SSR server). See the\n * [Build engine docs](https://github.com/Takazudo/zudo-front-builder/blob/main/docs/src/content/docs/architecture/build-engine.mdx)\n * for the gate decision table.\n *\n * Mirrors `Config::output` in crates/zfb/src/config.rs.\n */\n output?: OutputMode;\n\n /**\n * Config presets to merge before validation (#1196).\n *\n * Each preset is a partial `ZfbConfig`-shaped object. The merge pass runs\n * BEFORE field validation and folds preset contributions using additive\n * semantics:\n *\n * - **Array fields** (`plugins`, `collections`, `extraWatchPaths`,\n * `allowedHosts`): preset values are prepended so the main config's\n * entries retain their relative position after the preset's.\n * - **Scalar / optional fields**: a preset value fills in only when the\n * main config leaves the field at its default — the main config is\n * authoritative; presets act as defaults.\n *\n * Nested `presets` inside a preset are NOT recursively expanded.\n *\n * Mirrors `Config::presets` in crates/zfb/src/config.rs.\n */\n presets?: Partial<ZfbConfig>[];\n};\n\n/**\n * Project output mode.\n *\n * - `\"static\"` — pure-static (SSG-only); errors on detected SSR routes.\n * - `\"hybrid\"` — may host SSR routes; V8-on regardless of detection.\n * - `\"auto\"` — detection-driven; the default.\n *\n * Mirrors `OutputMode` in crates/zfb/src/config.rs.\n */\nexport type OutputMode = \"static\" | \"hybrid\" | \"auto\";\n\n/**\n * Syntect code-highlight options.\n *\n * Unknown theme names are rejected at build start with a clear error\n * rather than silently falling back.\n *\n * **Single-theme mode** (the default): set `theme` to a syntect theme name,\n * or omit it to use the default (`\"base16-ocean.dark\"`). Tokens are colored\n * with inline `color:`.\n *\n * **Dual-theme mode**: set both `themeLight` and `themeDark`. Tokens are\n * colored with CSS custom properties (`--shiki-light` / `--shiki-dark`),\n * and the consumer applies a `light-dark()` rule to pick the active color.\n * The `<pre>` element carries `class=\"syntect-dual\"` and\n * `--shiki-light-bg` / `--shiki-dark-bg` in its `style` attribute.\n *\n * `theme` and the dual pair are mutually exclusive. Setting only one of\n * `themeLight` / `themeDark` is an error.\n *\n * All theme names are **SYNTECT** built-in or user-loaded names (e.g.\n * `\"base16-ocean.light\"`, `\"base16-ocean.dark\"`, `\"InspiredGitHub\"`,\n * `\"Solarized (dark)\"`), NOT Shiki names like `\"dracula\"`.\n *\n * **Class mode** (Highlight Tokens epic, zfb#1528): set `mode: \"class\"`.\n * Each token gets a semantic role class instead of an inline color, so\n * highlight colors become re-themeable CSS design tokens. Mutually\n * exclusive with `theme` / `themeLight` / `themeDark` / `themesDir` —\n * themes don't affect class emission, so setting both is a build error.\n *\n * Mirrors `CodeHighlightConfig` in crates/zfb/src/config.rs.\n */\nexport type CodeHighlightConfig = {\n /**\n * Syntect built-in or user-loaded theme name. When absent the\n * pipeline defaults to `\"base16-ocean.dark\"`.\n *\n * Mutually exclusive with {@link themeLight} / {@link themeDark}.\n * Must be a SYNTECT theme name (e.g. `\"InspiredGitHub\"`), NOT a Shiki name.\n */\n theme?: string;\n /**\n * Path to a directory of `.tmTheme` files, relative to the project\n * root. Every `.tmTheme` file in the directory is loaded and becomes\n * available by its declared `name` via {@link theme}, {@link themeLight},\n * or {@link themeDark}. When absent only syntect's bundled themes are\n * available.\n *\n * The path must be relative and must not escape the project root via\n * `..`. A missing directory is reported as an error at build start.\n *\n * Applies to both single-theme and dual-theme mode.\n */\n themesDir?: string;\n /**\n * Light-mode syntect theme name for dual-theme highlighting.\n *\n * Must be set together with {@link themeDark} — setting only one of\n * the two is a build error. When both are set, tokens are colored with\n * CSS custom properties (`--shiki-light` / `--shiki-dark`) instead of\n * inline `color:`. Mutually exclusive with {@link theme}.\n *\n * Must be a SYNTECT theme name (e.g. `\"base16-ocean.light\"`),\n * NOT a Shiki name like `\"dracula\"`.\n */\n themeLight?: string;\n /**\n * Dark-mode syntect theme name for dual-theme highlighting.\n *\n * Must be set together with {@link themeLight} — setting only one of\n * the two is a build error. Mutually exclusive with {@link theme}.\n *\n * Must be a SYNTECT theme name (e.g. `\"base16-ocean.dark\"`),\n * NOT a Shiki name like `\"dracula\"`.\n */\n themeDark?: string;\n /**\n * Output mode for fenced-code highlighting (Highlight Tokens epic,\n * zfb#1528). `\"inline\"` (default) bakes per-token colors into\n * `style=\"color:#rrggbb\"` (or the dual `--shiki-*` custom properties).\n * `\"class\"` emits a semantic role class per token instead, so colors\n * become re-themeable CSS design tokens rather than baked-in HTML.\n *\n * Mutually exclusive with {@link theme} / {@link themeLight} /\n * {@link themeDark} / {@link themesDir} — themes don't affect class\n * emission, so setting both is rejected rather than silently ignoring\n * the theme.\n */\n mode?: CodeHighlightMode;\n /**\n * Class-name prefix for class-mode role classes (e.g. the default\n * `\"hi-\"` yields `hi-kw`, `hi-str`, ...). Must match\n * `/^[A-Za-z][A-Za-z0-9_-]*$/`. Only meaningful when {@link mode} is\n * `\"class\"`. Default: `\"hi-\"`.\n */\n classPrefix?: string;\n /**\n * Per-role class overrides for class mode, e.g.\n * `{ keyword: \"text-violet-600 dark:text-violet-400\" }` to map a role\n * onto Tailwind utilities instead of the default `{classPrefix}{role}`\n * class. Keys must be one of the 18 fixed role names (see\n * {@link CodeHighlightRole}); a value may hold multiple\n * space-separated classes and must not contain the bare token `\"line\"`\n * (collides with the code-enrichment line wrapper class). Absent uses\n * `{classPrefix}{role}` for every role.\n *\n * Setting this while `tailwind.enabled` is `false` (the authored-CSS\n * path) is allowed but emits a build warning — no Tailwind safelist can\n * be generated on that path, so the mapped utilities must already exist\n * in your own CSS.\n */\n roleClasses?: Partial<Record<CodeHighlightRole, string>>;\n /**\n * Whether to inject the built-in `--zfb-hi-*` token stylesheet\n * (`zfb-hi.css`) into the combined `styles.css` output. Only meaningful\n * in class mode. Default: `true`.\n */\n defaultStylesheet?: boolean;\n};\n\n/**\n * `codeHighlight.mode` — see {@link CodeHighlightConfig.mode}.\n *\n * Mirrors `CodeHighlightMode` in crates/zfb/src/config.rs.\n */\nexport type CodeHighlightMode = \"inline\" | \"class\";\n\n/**\n * The fixed 18-role semantic taxonomy for class-mode syntax highlighting\n * (Highlight Tokens epic, zfb#1528) — valid {@link CodeHighlightConfig.roleClasses}\n * keys.\n *\n * Mirrors `CODE_HIGHLIGHT_ROLES` in crates/zfb/src/config.rs.\n */\nexport type CodeHighlightRole =\n | \"escape\"\n | \"operator\"\n | \"comment\"\n | \"string\"\n | \"number\"\n | \"constant\"\n | \"keyword\"\n | \"function\"\n | \"type\"\n | \"namespace\"\n | \"property\"\n | \"variable\"\n | \"tag\"\n | \"attribute\"\n | \"punctuation\"\n | \"inserted\"\n | \"deleted\"\n | \"heading\";\n\n/**\n * Table-of-contents options. Wire via `markdown.toc` in `zfb.config.ts`.\n *\n * When present, a TOC `<ul>/<li>` list is inserted as the next sibling\n * of the first heading whose text matches `heading` (case-insensitive).\n * Each `<a href=\"#id\">` links to the deduplicated `id` that\n * `HeadingLinksPlugin` placed on the corresponding heading.\n *\n * Mirrors `TocConfig` in `crates/zfb-content/src/plugins/toc.rs`.\n */\nexport type TocConfig = {\n /**\n * Heading text that triggers TOC insertion. Matched\n * case-insensitively after whitespace trimming. Default: `\"TOC\"`.\n */\n heading?: string;\n\n /**\n * Number of heading levels to include starting from `<h2>`.\n *\n * - `1` — h2 only\n * - `2` (default) — h2 + h3\n * - `3` — h2, h3, h4\n * - …up to `5` (h2 through h6)\n */\n maxDepth?: number;\n};\n\n/**\n * Markdown / MDX parsing options.\n *\n * See [`ZfbConfig.markdown`] for the embed point. Fields: [`gfm`],\n * [`toc`], [`externalLinks`], [`cjkFriendly`], and [`features`].\n * Future markdown knobs would also live here.\n *\n * See the \"Markdown Features\" docs category for the per-feature option\n * reference once individual features are ported.\n *\n * Mirrors `MarkdownConfig` in crates/zfb/src/config.rs.\n */\nexport type MarkdownConfig = {\n /**\n * Enable GFM constructs.\n *\n * Accepts three shapes:\n *\n * - `true` — turn every GFM construct ON (strikethrough, table,\n * autolink-literal, task-list-item, footnote-definition).\n * - `false` — turn every GFM construct OFF.\n * - partial object — set individual fields explicitly; fields you\n * omit fall back to the conservative-default values described\n * below.\n *\n * When `markdown` itself is omitted entirely, the conservative\n * default applies: `strikethrough: true`, `table: true`, every other\n * GFM construct off. This is the smallest behavioural delta from\n * zfb's historical effective state (table-only). Projects that want\n * the full GFM surface should opt in with `gfm: true`.\n */\n gfm?: GfmFlag;\n\n /**\n * Table-of-contents options. When present, a `<ul>/<li>` list is\n * inserted after the first heading whose text matches `heading`\n * (default `\"TOC\"`, case-insensitive). Each link points to the\n * deduplicated `id` that `HeadingLinksPlugin` placed on the heading.\n *\n * Omitting this field entirely leaves the build byte-for-byte identical\n * to the pre-TOC build. See [`TocConfig`] for the available options.\n *\n * Mirrors `MarkdownConfig::toc` in crates/zfb/src/config.rs.\n */\n toc?: TocConfig;\n /**\n * External-link rewriter. When set, every `<a>` whose href is\n * classified as external receives the configured `target` and `rel`\n * attributes.\n *\n * An href is external when it is an absolute HTTP/HTTPS URL AND its\n * origin differs from the top-level `site` URL (if `site` is\n * configured). When `site` is absent, any absolute HTTP/HTTPS URL is\n * treated as external.\n *\n * `mailto:`, `tel:`, and other non-HTTP(S) schemes are always left\n * unchanged. Relative URLs (`/internal/`, `./file.mdx`, `#anchor`) are\n * always internal.\n *\n * Omitting this field keeps the output byte-for-byte identical to the\n * pre-feature behaviour.\n *\n * Mirrors `ExternalLinksConfig` in crates/zfb/src/config.rs.\n */\n externalLinks?: ExternalLinksConfig;\n\n /**\n * Enable CJK-friendly markdown handling.\n *\n * Governs two post-parse fixups that adapt CommonMark/GFM rules to CJK\n * text:\n *\n * 1. **Emphasis/strong flanking** (`CjkFriendlyPlugin`). CommonMark's\n * left-/right-flanking delimiter-run rules treat CJK characters as\n * non-whitespace non-punctuation, which causes `**foo**` adjacent to\n * CJK text (e.g. `**テスト。**テスト`) to render as literal stars\n * instead of `<strong>`.\n * 2. **Bare-URL autolink boundary** (`CjkAutolinkBoundaryPlugin`,\n * zfb#1105). The GFM autolink-literal path grammar terminates only on\n * ASCII whitespace, so a bare URL flush against CJK text\n * (`詳細はhttps://example.com参照`) swallows the trailing CJK run into\n * the `href`. This fixup terminates the link at the first CJK\n * character. Only active when `gfm.autolinkLiteral` is also on.\n *\n * - **absent / `true` (default):** CJK-friendly handling is on.\n * Preserves today's behaviour — existing CJK-content sites are\n * unaffected.\n * - **`false`:** opt-out. Neither plugin is added to the pipeline;\n * emphasis markers and bare-URL autolinks adjacent to CJK characters\n * follow base CommonMark/GFM rules. Rarely the right choice; provided\n * as an escape hatch for projects that need strict CommonMark/GFM\n * output.\n *\n * **GFM strikethrough** (`~~foo~~`) at CJK boundaries is unaffected\n * by this toggle — it is handled by markdown-rs's GFM tokeniser, not\n * by these plugins, and works correctly in both modes.\n *\n * Mirrors `MarkdownConfig::cjk_friendly` in crates/zfb/src/config.rs.\n */\n cjkFriendly?: boolean;\n\n /**\n * Convert every soft line break (a single `\\n` inside a paragraph) into\n * `<br>` (remark-breaks parity).\n *\n * - **absent / `false` (default):** soft line breaks follow standard\n * CommonMark behaviour — collapsed into a single space.\n * - **`true`:** every `\\n` inside a paragraph becomes `<br>`. Use this\n * when your content relies on newline→`<br>` fidelity (e.g. product\n * descriptions, lyrics, or other newline-sensitive prose).\n *\n * Mirrors `MarkdownConfig::hard_breaks` in crates/zfb/src/config.rs.\n */\n hardBreaks?: boolean;\n\n /**\n * Per-feature markdown pipeline toggles.\n *\n * Each field is a [`FeatureToggle`] (`true` / `false` / options object)\n * or a feature-specific config type (for features that require extra\n * parameters). Absent / `undefined` means all features are disabled,\n * preserving the behaviour of the pre-features build byte-for-byte.\n *\n * Unknown keys are rejected at deserialization time by the Rust loader\n * so a typo in `zfb.config.ts` surfaces as a clear error.\n *\n * Mirrors `MarkdownFeaturesConfig` in crates/zfb/src/config.rs.\n */\n features?: MarkdownFeaturesConfig;\n};\n\n/**\n * Per-feature toggle: `boolean` shorthand or an options object.\n *\n * `true` enables the feature with defaults; `false` (or absent) disables it.\n * The object form carries per-feature options (fields vary by feature and\n * are filled in by each feature's port sub-issue — stubs today).\n *\n * Mirrors `FeatureToggle` in crates/zfb/src/config.rs.\n */\nexport type FeatureToggle = boolean | FeatureOptions;\n\n/**\n * Empty options object for features that accept `{ ... }` but have no\n * user-facing knobs yet. Fields are filled in by each feature's port\n * sub-issue; this stub satisfies the schema shape requirement.\n *\n * Mirrors `FeatureOptions` in crates/zfb/src/config.rs.\n */\nexport type FeatureOptions = Record<string, never>;\n\n/**\n * Options for the `githubAutolinks` feature — rewrites bare `#123`,\n * `user/repo#456`, and commit-SHA references into GitHub links.\n *\n * `repo` is required: `githubAutolinks: {}` (repo absent) is a config error\n * — the Rust pipeline emits a build-blocking diagnostic rather than\n * silently skipping the feature.\n *\n * Mirrors `GithubAutolinksConfig` in `crates/zfb-md-ast/src/features_config.rs`.\n */\nexport type GithubAutolinksConfig = {\n /**\n * GitHub repository reference (`owner/repo`) used to build autolink URLs\n * (e.g. `\"owner/repo\"` renders `#123` as\n * `https://github.com/owner/repo/issues/123`). Required — see above.\n */\n repo: string;\n};\n\n/**\n * Options for the `codeEnrichment` feature.\n *\n * Both flags default to `true` when the feature is enabled with\n * `codeEnrichment: {}` or when a field is absent.\n *\n * Mirrors `CodeEnrichmentConfig` in `crates/zfb-md-ast/src/features_config.rs`.\n */\nexport type CodeEnrichmentConfig = {\n /**\n * Enable diff-marker processing for markers such as `// [!code ++]`\n * and `// [!code --]`. Default: `true`.\n */\n diffMarkers?: boolean;\n /**\n * Enable line-highlight processing for fence ranges such as `{1,3-5}`.\n * Default: `true`.\n */\n lineHighlight?: boolean;\n};\n\n/**\n * Options for the `tocExport` feature.\n *\n * Controls which headings are included in the exported `toc` JSON.\n * `maxDepth` is the **absolute** heading depth (2–6):\n * - `2` → h2 only\n * - `3` (default) → h2 + h3\n *\n * This differs from `headingMarkerToc.maxDepth`, which counts levels\n * starting from h2. The two features are independent.\n *\n * Mirrors `TocExportConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type TocExportConfig = {\n /** Maximum heading depth to include (absolute, 2–6). Default: 3. */\n maxDepth?: number;\n};\n\n/**\n * Options for the `imageDimensions` feature.\n *\n * Auto-detects and injects `width`/`height` on local `<img>` elements. Raster\n * formats are probed header-only; SVGs are read from their markup\n * (`width`/`height`/`viewBox`).\n *\n * Mirrors `ImageDimensionsConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type ImageDimensionsConfig = {\n /**\n * When `true` (the default), `http://` and `https://` image sources are\n * silently skipped and not probed for dimensions. Set to `false` only for\n * testing or unusual setups — remote images require network access at build\n * time and slow the pipeline.\n */\n skipRemote?: boolean;\n};\n\n/**\n * Options for the `linkValidation` feature.\n *\n * Validates internal `[text](file.md#anchor)` and `[text](#anchor)` links at\n * build time. External URLs (`http://`, `https://`, `mailto:`) are always\n * skipped — network validation is out of scope.\n *\n * Mirrors `LinkValidationConfig` in `crates/zfb-md-ast/src/features_config.rs`.\n */\nexport type LinkValidationConfig = {\n /**\n * When `true`, broken links are reported as errors (build can fail).\n * Default: `false` (warn-only).\n */\n failOnBroken?: boolean;\n};\n\n/**\n * Options for the `transclude` feature.\n *\n * Enables `:::include{file=\"./path.md\"}` directives that inline another\n * file's parsed mdast at the include site.\n *\n * Mirrors `TranscludeConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type TranscludeConfig = {\n /**\n * Maximum transclusion depth (chain length A→B→C→…).\n *\n * A depth of `1` allows only direct includes (the included file itself\n * cannot include further files). Default: `5`. A cycle (A→B→A) is\n * always detected regardless of `maxDepth` and treated as an error.\n */\n maxDepth?: number;\n};\n\n/**\n * Options for the `readingTime` feature.\n *\n * Mirrors `ReadingTimeOptions` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type ReadingTimeConfig = {\n /** Words-per-minute rate for the reading-time estimate. Default: 200. */\n wpm?: number;\n};\n\n/**\n * `readingTime` feature value: either a `boolean` shorthand or a\n * {@link ReadingTimeConfig} options object.\n *\n * Mirrors `ReadingTimeFeature` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type ReadingTimeFeature = boolean | ReadingTimeConfig;\n\n/**\n * Per-feature markdown pipeline configuration.\n *\n * All fields are optional; absent = feature disabled, behaviour unchanged\n * from the pre-features build. Unknown keys are rejected at deserialization\n * time by the Rust loader so a typo surfaces as a clear error.\n *\n * Mirrors `MarkdownFeaturesConfig` in crates/zfb/src/config.rs.\n */\nexport type MarkdownFeaturesConfig = {\n /** GitHub-style alert blocks (`> [!NOTE]`, `> [!WARNING]`, etc.). */\n githubAlerts?: FeatureToggle;\n\n /**\n * Reading-time estimate injected into the document frontmatter.\n * Accepts `true` / `false` shorthand or `{ wpm: N }` for a custom rate.\n */\n readingTime?: ReadingTimeFeature;\n\n /** GitHub-style `owner/repo#123` and `SHA` autolinks. Requires `repo`. */\n githubAutolinks?: GithubAutolinksConfig;\n\n /** Code-block enrichment (copy button, language label, etc.). */\n codeEnrichment?: CodeEnrichmentConfig;\n\n /** Grouped code blocks rendered as tabs. */\n codeTabs?: FeatureToggle;\n\n /** Ruby annotation support (`{base}^{ruby}` syntax). */\n ruby?: FeatureToggle;\n\n /** Export the page TOC as structured data (e.g. for sidebar rendering). */\n tocExport?: TocExportConfig;\n\n /** Auto-detect and inject `width`/`height` on `<img>` elements. */\n imageDimensions?: ImageDimensionsConfig;\n\n /**\n * Validate internal links (file-relative paths and anchor fragments) at\n * build time. External URLs are always skipped — network validation is\n * out of scope.\n */\n linkValidation?: LinkValidationConfig;\n\n /**\n * Transclusion of other markdown/MDX files via\n * `:::include{file=\"./path.md\"}` — NOT the Obsidian `[[path]]` wikilink\n * syntax.\n */\n transclude?: TranscludeConfig;\n\n /**\n * Generic `:::name` → component map. You supply the components; no defaults\n * are registered. Keys are directive names (e.g. `\"foo\"`), values are\n * {@link DirectiveSpec} (bare component name string or options object).\n *\n * Mirrors `directives` in `MarkdownFeaturesConfig` in crates/zfb/src/config.rs.\n */\n directives?: Record<string, DirectiveSpec>;\n\n /** Mermaid diagram rendering. */\n mermaid?: FeatureToggle;\n\n /**\n * Inline heading-marker TOC. Accepts either a `boolean` shorthand\n * (`true` = enable with defaults, `false` = disable) or a full\n * {@link TocConfig} options object — same union shape as the Rust\n * `HeadingMarkerTocFeature` enum.\n */\n headingMarkerToc?: HeadingMarkerTocFeature;\n\n /**\n * Heading-ID strategy for the always-on `HeadingLinks` plugin.\n * Absent → `\"flat\"` (the long-standing github-slugger scheme).\n * `{ strategy: \"hierarchical\" }` opts into ancestor-prefixed anchor\n * IDs (`## Foo` / `### Moo` / `#### Mew` → `foo`, `foo-moo`,\n * `foo-moo-mew`) — see {@link HeadingIdsConfig}.\n */\n headingIds?: HeadingIdsConfig;\n};\n\n/**\n * Options for the `headingIds` entry in `markdown.features`.\n *\n * Configures the always-on `HeadingLinks` plugin rather than toggling an\n * opt-in feature. Note: switching to `\"hierarchical\"` is anchor-breaking\n * for existing deep links to nested headings.\n *\n * Mirrors `HeadingIdsConfig` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type HeadingIdsConfig = {\n /**\n * `\"flat\"` (default): github-slugger slugs with a per-document dedup\n * counter shared across h2–h6 (`overview`, `overview-1`, …).\n * `\"hierarchical\"`: each heading's slug is prefixed with its ancestor\n * chain and deduped on the full path — anchors become reconstructible\n * from the heading outline.\n */\n strategy?: \"flat\" | \"hierarchical\";\n};\n\n/**\n * `headingMarkerToc` feature value: either a `boolean` shorthand or a\n * full {@link TocConfig} options object.\n *\n * Mirrors `HeadingMarkerTocFeature` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type HeadingMarkerTocFeature = boolean | TocConfig;\n\n/**\n * Spec for one user-defined directive: either a bare component name string\n * or a full {@link DirectiveFullSpec} options object.\n *\n * Mirrors `DirectiveSpec` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type DirectiveSpec = string | DirectiveFullSpec;\n\n/**\n * Full options object for one user-defined directive.\n *\n * Mirrors `DirectiveFullSpec` in crates/zfb-md-ast/src/features_config.rs.\n */\nexport type DirectiveFullSpec = {\n /** JSX component identifier (e.g. `\"Spoiler\"`, `\"Kbd\"`). */\n component: string;\n /** Container/leaf/text shape. Defaults to `\"container\"` when absent. */\n kind?: \"container\" | \"leaf\" | \"text\";\n /** Whether the bracketed `[label]` becomes a `title` attribute. Defaults to `true`. */\n titleFromLabel?: boolean;\n};\n\n/**\n * Options for the external-link rewriter (port of `rehype-external-links`).\n *\n * All fields are optional; omitting a field applies the documented default.\n *\n * Mirrors `ExternalLinksConfig` in crates/zfb/src/config.rs.\n */\nexport type ExternalLinksConfig = {\n /**\n * `rel` tokens applied to external links.\n *\n * Default: `[\"noopener\", \"noreferrer\"]`.\n *\n * Tokens are deduplicated (case-insensitive) and merged with any\n * existing `rel` attribute on the `<a>` element — existing tokens\n * appear first.\n */\n rel?: string[];\n /**\n * `target` value for external links.\n *\n * Default: `\"_blank\"`.\n */\n target?: string;\n};\n\n/**\n * Either the shorthand boolean form (`true` = all GFM constructs on,\n * `false` = all off) or a partial object that toggles individual\n * constructs.\n *\n * Mirrors `GfmFlag` in crates/zfb/src/config.rs.\n */\nexport type GfmFlag = boolean | GfmConstructs;\n\n/**\n * Per-construct opt-in / opt-out for GFM. Every field is optional;\n * omitted fields fall back to the conservative default\n * (`strikethrough: true`, `table: true`, others `false`).\n *\n * Mirrors `GfmConstructs` in crates/zfb/src/config.rs.\n */\nexport type GfmConstructs = {\n /** GFM strikethrough (`~~text~~` → `<del>text</del>`). */\n strikethrough?: boolean;\n /** GFM pipe-style tables. */\n table?: boolean;\n /**\n * GFM autolink literal — bare URLs like `https://example.com` become\n * clickable links without `<…>` brackets.\n */\n autolinkLiteral?: boolean;\n /** GFM task list items (`- [x]` / `- [ ]`). */\n taskListItem?: boolean;\n /** GFM footnote definitions (`[^ref]: …`). */\n footnoteDefinition?: boolean;\n};\n\n/**\n * What to do when a `.md`/`.mdx` link cannot be resolved.\n *\n * Mirrors `OnBrokenLinks` in crates/zfb/src/config.rs.\n */\nexport type OnBrokenLinks = \"warn\" | \"error\" | \"ignore\";\n\n/**\n * Config for the markdown link resolver. See\n * [`ZfbConfig.resolveMarkdownLinks`] for the design rationale.\n */\nexport type ResolveMarkdownLinksConfig = {\n /** Whether to enable link resolution. Default: `false`. */\n enabled?: boolean;\n\n /**\n * Legacy single-dir field. Used only when [`dirs`] is empty. When\n * non-empty, scanned against the hard-coded `/docs/` route prefix.\n */\n docsDir?: string;\n\n /**\n * Explicit per-dir source map. Each entry is one collection (e.g.\n * EN docs at `src/content/docs/` → `/docs/`, JA docs at\n * `src/content/docs-ja/` → `/ja/docs/`). Takes precedence over\n * [`docsDir`] when non-empty.\n */\n dirs?: ResolveMarkdownLinksDir[];\n\n /** What to do with unresolved `.md`/`.mdx` links. Default: `\"warn\"`. */\n onBrokenLinks?: OnBrokenLinks;\n};\n\n/** One source-dir entry for [`ResolveMarkdownLinksConfig.dirs`]. */\nexport type ResolveMarkdownLinksDir = {\n /**\n * Directory (relative to project root) whose `.md`/`.mdx` files are\n * scanned. Must be relative and must not escape the root via `..`.\n */\n dir: string;\n\n /**\n * Route prefix prepended to each file's slug. Include leading and\n * trailing slashes (e.g. `\"/docs/\"` or `\"/ja/docs/\"`).\n */\n routePrefix: string;\n};\n\n/**\n * Identity helper: returns the supplied config as-is, but typed against\n * [`ZfbConfig`]. Use as the default export of `zfb.config.ts` so editors\n * surface field-level types and typos surface at compile time.\n */\nexport function defineConfig(config: ZfbConfig): ZfbConfig {\n return config;\n}\n\n/**\n * Preset authoring helper: stamps each object entry in `config.plugins`\n * with `source_package: sourcePackage` so the Rust loader can attribute\n * plugin contributions back to the preset package that provided them.\n *\n * - Only plain-object plugin entries are stamped; non-object entries pass\n * through unchanged (defensive — the current schema requires objects,\n * but this guard keeps the helper safe if the schema is ever relaxed).\n * - An entry that ALREADY carries a `source_package` is left untouched, so a\n * preset composing another `definePreset`-returned preset (by spreading its\n * `plugins`) keeps the inner preset's provenance instead of clobbering it\n * with the outer package name (the spread below lets the existing marker win).\n * - When `config.plugins` is absent, the config is returned as-is.\n * - All other fields of `config` pass through unchanged.\n *\n * The key `source_package` (snake_case) mirrors the Rust `PluginConfig`\n * serde field added in T4. `PluginConfig` has no `#[serde(rename_all)]`\n * so the serde key is the field name verbatim — do NOT use camelCase.\n *\n * SYNC REQUIREMENT: keep this implementation behaviourally identical to\n * the stub in crates/zfb-config-loader/js/zfb-config-stub.mjs, which is\n * injected at config-eval time when the user's project does not have the\n * zfb npm package installed locally.\n */\nexport function definePreset(\n sourcePackage: string,\n config: Partial<ZfbConfig>,\n): Partial<ZfbConfig> {\n if (!config.plugins) {\n return config;\n }\n return {\n ...config,\n plugins: config.plugins.map((plugin) => {\n if (plugin !== null && typeof plugin === \"object\" && !Array.isArray(plugin)) {\n // Default first, then spread the plugin so an existing `source_package`\n // (from a composed inner preset) wins over the outer package name.\n return { source_package: sourcePackage, ...plugin };\n }\n return plugin;\n }),\n };\n}\n"]}
|
package/dist/content.d.ts
CHANGED
|
@@ -160,9 +160,10 @@ export declare function getCollection<T = Record<string, unknown>>(name: string)
|
|
|
160
160
|
*
|
|
161
161
|
* **Runtime vs. generated types divergence.** The generated `types.d.ts`
|
|
162
162
|
* emits a keyed overload (`K extends keyof ZfbCollections`) that ties the
|
|
163
|
-
* return type to the collection's declared schema.
|
|
164
|
-
* intentionally structural — it does
|
|
165
|
-
* does not attempt to reconcile with the
|
|
163
|
+
* return type to the collection's declared schema. That schema is enforced
|
|
164
|
+
* by `zfb check`; this runtime form is intentionally structural — it does
|
|
165
|
+
* not reference `ZfbCollections` and does not attempt to reconcile with the
|
|
166
|
+
* keyed shape. (#857)
|
|
166
167
|
*
|
|
167
168
|
* @example
|
|
168
169
|
* const post = getEntry<{ title: string }>("blog", "hello-zfb");
|
package/dist/content.js
CHANGED
|
@@ -326,9 +326,10 @@ export function getCollection(name) {
|
|
|
326
326
|
*
|
|
327
327
|
* **Runtime vs. generated types divergence.** The generated `types.d.ts`
|
|
328
328
|
* emits a keyed overload (`K extends keyof ZfbCollections`) that ties the
|
|
329
|
-
* return type to the collection's declared schema.
|
|
330
|
-
* intentionally structural — it does
|
|
331
|
-
* does not attempt to reconcile with the
|
|
329
|
+
* return type to the collection's declared schema. That schema is enforced
|
|
330
|
+
* by `zfb check`; this runtime form is intentionally structural — it does
|
|
331
|
+
* not reference `ZfbCollections` and does not attempt to reconcile with the
|
|
332
|
+
* keyed shape. (#857)
|
|
332
333
|
*
|
|
333
334
|
* @example
|
|
334
335
|
* const post = getEntry<{ title: string }>("blog", "hello-zfb");
|
package/dist/content.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content.js","sourceRoot":"","sources":["../src/content.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,sEAAsE;AACtE,uEAAuE;AACvE,kFAAkF;AAClF,0EAA0E;AAC1E,0EAA0E;AAC1E,2CAA2C;AAC3C,EAAE;AACF,cAAc;AACd,2EAA2E;AAC3E,6DAA6D;AAC7D,0EAA0E;AAC1E,oEAAoE;AACpE,wEAAwE;AACxE,QAAQ;AACR,qCAAqC;AACrC,uEAAuE;AACvE,wEAAwE;AACxE,EAAE;AACF,4EAA4E;AAC5E,4CAA4C;AAE5C,yEAAyE;AACzE,iBAAiB;AACjB,EAAE;AACF,6EAA6E;AAC7E,kEAAkE;AAClE,8EAA8E;AAC9E,0EAA0E;AAC1E,sEAAsE;AACtE,yEAAyE;AACzE,kEAAkE;AAClE,mEAAmE;AACnE,qEAAqE;AACrE,sEAAsE;AACtE,0EAA0E;AAC1E,wEAAwE;AACxE,uEAAuE;AACvE,gEAAgE;AAChE,8CAA8C;AAC9C,EAAE;AACF,sEAAsE;AACtE,0EAA0E;AAC1E,yEAAyE;AACzE,0CAA0C;AAC1C,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAKxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAIpD,wEAAwE;AACxE,mEAAmE;AACnE,2EAA2E;AAC3E,qEAAqE;AACrE,8BA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K,EAAE,YAAY;IACnB,IAAI,EAAE,WAAW;CACT,CAAC;AAEX;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAChC,UAAqC,EACrC,OAAkC;IAElC,OAAO,EAAE,GAAG,iBAAiB,EAAE,GAAG,UAAU,EAAE,GAAG,OAAO,EAAE,CAAC;AAC7D,CAAC","sourcesContent":["// `zfb/content` — minimal v0 content collection loader.\n//\n// Reads `*.md` files from a content collection directory, parses YAML\n// frontmatter, and returns typed entries. This is a deliberately small\n// stub so the bundled basic-blog template can call `getCollection(\"blog\")` today;\n// the production path lives in `crates/zfb-content` and will replace this\n// once the JS-runtime decision (ADR-001) lands and the renderer wires the\n// Rust pipeline back through to user code.\n//\n// Scope (v0):\n// - YAML-ish frontmatter only: `key: value`, plus `key:\\n - item` arrays.\n// Quoted strings are unwrapped. ISO dates stay as strings.\n// - Body is the post content **after** the closing `---`, returned as raw\n// text. This is intentionally NOT pre-rendered HTML: the markdown\n// pipeline lives in the Rust crate and the JS stub does not duplicate\n// it.\n// - Collection root is resolved from\n// `process.env.ZFB_CONTENT_ROOT` (set by the dev/build pipeline), or\n// `<cwd>/content` as a fallback for unit tests and direct invocation.\n//\n// TODO(zfb-content): swap this stub for the runtime-provided implementation\n// once the content engine ships end-to-end.\n\n// `node:fs` and `node:path` are intentionally NOT imported statically at\n// the top level.\n//\n// Why: this module is reachable via the package root (`@takazudo/zfb`) — the\n// barrel re-exports `defaultComponents` / `ContentH2` / etc. from\n// `./content.js`. The islands per-island bundler (`crates/zfb-islands`) walks\n// `import * as Mod from \"@takazudo/zfb\"` and esbuild's static tree-shaker\n// cannot prune a module behind a wildcard barrel access, so the WHOLE\n// content.ts module ends up in the browser-side island bundle. Top-level\n// `node:fs` / `node:path` imports would then fail the bundle with\n// `Could not resolve \"node:fs\"`. Loading them indirectly through a\n// runtime-constructed `createRequire` keeps the Node-runtime fs path\n// working while letting the islands bundler emit browser-safe output.\n// (Discovered while investigating zudolab/zudo-doc#1355 Wave 3 — see also\n// upstream PR #134 / #130 Gap A.) Defense-in-depth: the islands esbuild\n// invocation also passes `--platform=browser --external:node:*` so any\n// stray `node:*` import that does end up in a browser bundle is\n// externalized rather than failing the build.\n//\n// `getCollection` is synchronous per ADR-004, so the node modules are\n// loaded synchronously on first fs-path use. Type-only imports below stay\n// at the top because TypeScript erases them at compile time — they leave\n// no runtime traces for esbuild to chase.\nimport { jsx } from \"react/jsx-runtime\";\n\nimport type * as NodeFs from \"node:fs\";\nimport type * as NodePath from \"node:path\";\n\nimport { parseFrontmatter } from \"./frontmatter.js\";\nimport type { ParsedFrontmatter } from \"./frontmatter.js\";\nimport type { VNode } from \"./jsx-types.js\";\n\n// Re-export the parser surface so existing `zfb/content` consumers that\n// import `parseFrontmatter` / `ParsedFrontmatter` from the content\n// subpath keep working. The implementation now lives in `./frontmatter.ts`\n// (BCI-3 fs-free subpath) — this re-export is the bridge for callers\n// that have not migrated yet.\nexport { parseFrontmatter };\nexport type { ParsedFrontmatter };\n\n// ---------------------------------------------------------------------------\n// In-memory ContentSnapshot bridge (consumed by `@takazudo/zfb-runtime`).\n//\n// At build time, the Rust pipeline produces a `ContentSnapshot` (see\n// `crates/zfb-content/src/content_bridge.rs`) and embeds it into the\n// Worker bundle. On Worker boot, `createPageRouter` calls\n// `setContentSnapshot(snapshot)` (below) before serving the first\n// request. From that point on, `getCollection(name)` resolves from the\n// embedded snapshot rather than the Node `fs` API — required because the\n// workerd / Cloudflare Workers runtime has no filesystem.\n//\n// The fs path remains the source of truth in two contexts:\n// 1. unit tests for this module (no snapshot installed → fs path),\n// 2. dev-preview / direct-Node invocations of `getCollection` outside\n// the Worker bundle (kept as v0 fallback so older callers still work).\n//\n// Keep [`SnapshotEntry`] / [`Snapshot`] aligned with the Rust struct\n// (`EntrySnapshot` / `ContentSnapshot`) and the runtime-package mirror\n// (`@takazudo/zfb-runtime/snapshot`). Field names are snake_case to\n// match the JSON serialization (`module_specifier`, `rel_path`).\n// ---------------------------------------------------------------------------\n\n/**\n * One entry in an embedded content snapshot. Mirrors\n * `crates/zfb-content/src/content_bridge.rs::EntrySnapshot`. Re-exported\n * by `@takazudo/zfb-runtime/snapshot` for the runtime-side bundle. See\n * that module for field-by-field documentation.\n */\nexport interface SnapshotEntry {\n readonly slug: string;\n readonly frontmatter: unknown;\n readonly body: string;\n readonly module_specifier: string;\n readonly rel_path: string;\n}\n\n/**\n * Point-in-time snapshot of every configured collection. Mirrors\n * `crates/zfb-content/src/content_bridge.rs::ContentSnapshot`.\n */\nexport interface Snapshot {\n readonly collections: Readonly<Record<string, readonly SnapshotEntry[]>>;\n}\n\n/**\n * Where the installed [`Snapshot`] lives.\n *\n * The state hangs off `globalThis.__zfb.contentSnapshot`, NOT a\n * module-level `let`. This matters because under the production worker\n * bundle the consumer's pnpm-strict `node_modules` layout exposes\n * two physical paths to `@takazudo/zfb`:\n *\n * - top-level `node_modules/@takazudo/zfb` (imported by user pages), AND\n * - nested `node_modules/.pnpm/@takazudo+zfb-runtime@.../node_modules/\n * @takazudo/zfb` (imported by `@takazudo/zfb-runtime` itself).\n *\n * The bundler passes `esbuild --preserve-symlinks` whenever a custom\n * `node_modules_dir` is configured (see `crates/zfb-build/src/bundler.rs`\n * around `--external:node:*`), so esbuild treats those two symlink\n * targets as distinct sources and inlines `content.js` TWICE — yielding\n * two module instances of `zfb/content` in the final worker bundle.\n *\n * If `installedSnapshot` were a per-module `let`, `createPageRouter`\n * would install the snapshot on the runtime's copy and `getCollection`\n * (called from a user `paths()` export) would read from the user\n * page's copy — see `undefined`, and fall through to the `node:fs`\n * branch, which then throws because `node:*` is externalized in the\n * worker bundle. This is the regression #442 / #449 surfaced.\n *\n * Routing the slot through `globalThis` makes the snapshot bridge\n * symmetric with the existing `globalThis.__zfb.content` MDX-component\n * bridge (set by the build pipeline at `crates/zfb-build/src/bundler.rs`,\n * read by `Content` below): both pieces of cross-module state share\n * one well-known global, so any number of `zfb/content` module\n * instances in the same JS realm see the same value.\n *\n * Tracked under #449 (production fix for #442); the test-fixture\n * counterpart was #413.\n */\ntype SnapshotBridgeNamespace = {\n contentSnapshot?: Snapshot | undefined;\n};\n\ntype SnapshotBridgeGlobal = typeof globalThis & {\n __zfb?: SnapshotBridgeNamespace;\n};\n\n/**\n * Register a [`Snapshot`] so [`getCollection`] resolves from memory.\n *\n * Pass `undefined` to clear (used by tests that need to restore the v0\n * filesystem path between runs). Idempotent: the latest call wins.\n *\n * Stored on `globalThis.__zfb.contentSnapshot` rather than a\n * module-level `let` so a worker bundle that ends up with two\n * `zfb/content` module instances still sees a single shared snapshot —\n * see the [`SnapshotBridgeNamespace`] doc above for the full\n * pnpm-symlink rationale.\n */\nexport function setContentSnapshot(snapshot: Snapshot | undefined): void {\n const g = globalThis as SnapshotBridgeGlobal;\n const ns = (g.__zfb ?? {}) as SnapshotBridgeNamespace;\n ns.contentSnapshot = snapshot;\n g.__zfb = ns;\n}\n\n/**\n * Read the currently-installed [`Snapshot`], or `undefined` if none is\n * registered. Exposed mostly for tests; production callers should not\n * need to introspect the bridge state.\n *\n * Reads from `globalThis.__zfb.contentSnapshot`; see\n * [`setContentSnapshot`] for why the slot lives on `globalThis`.\n */\nexport function getContentSnapshot(): Snapshot | undefined {\n return (globalThis as SnapshotBridgeGlobal).__zfb?.contentSnapshot;\n}\n\n/**\n * Flat map of element-name → override component, used by both\n * [`ContentProps.components`] and the global slot\n * (`globalThis.__zfb?.mdxComponents`). Keys are lowercase HTML tag names\n * (`h2`, `p`, `a`, …) or PascalCase custom-component names.\n */\nexport type MdxComponents = Record<string, unknown>;\n\n/**\n * Props accepted by an entry's [`CollectionEntry.Content`] component.\n *\n * `components` mirrors Astro's `<Content components={...}>` contract:\n * a flat record of element-name → override component (e.g. `{ h1: MyH1 }`).\n * The default-components convention ships from `zfb`'s root export\n * (`defaultComponents`, lands in Sub 6) and users compose with their own\n * via `{ ...defaultComponents, ...mine }`.\n */\nexport interface ContentProps {\n /** Element-name → override component map. Optional. */\n components?: MdxComponents;\n}\n\n/**\n * Public JSX-element shape returned by [`CollectionEntry.Content`].\n *\n * Matches the structural shape that both Preact's and React's `jsx-runtime`\n * accept on either side of the boundary, mirroring the Island wrapper's\n * approach. Consumers should treat this as opaque — its only contract is\n * \"renderable JSX value\".\n *\n * Aliased as `JSX.Element` in the field signature: the JS runtime is\n * type-erased and the actual VNode shape is supplied by the framework\n * adapter at evaluation time.\n */\nexport type ContentElement = {\n readonly type: string | ((...args: unknown[]) => unknown);\n readonly props: Readonly<Record<string, unknown>>;\n readonly key: unknown;\n};\n\n/**\n * Bridge contract published by the Rust-side `zfb-render` `Renderer` before\n * evaluating each page module. Cross-referenced from the Rust side in\n * `crates/zfb-render/src/loader.rs` so the two halves stay in sync — see\n * `packages/zfb/CONTRIBUTING.md` for the full contract narrative.\n *\n * The renderer installs `globalThis.__zfb.content.get(specifier)` keyed on\n * the entry's `module_specifier` (Sub 4 convention: `mdx://<collection>/<slug>#<hash>`,\n * collapsed to `mdx://<collection>/<slug>` from the JS stub side which has\n * no hash to compute). When `get` returns `undefined` (or the bridge as a\n * whole is absent — typical of unit tests, dev sandboxes, and any\n * non-renderer evaluation context), `Content` renders a clearly-marked\n * `<pre data-zfb-content-fallback>` fallback so the visual distinction is\n * obvious even in unstyled environments.\n */\ntype ContentBridge = {\n get(specifier: string): ((props: ContentProps) => unknown) | undefined;\n};\n\ntype ZfbBridgeNamespace = {\n content?: ContentBridge;\n /**\n * Global component-override slot. Populated by sub-task A2 (bridge\n * installer); A1 only reads it. Absent ⇒ no-op in the merge.\n */\n mdxComponents?: MdxComponents;\n};\n\ntype BridgeGlobal = typeof globalThis & {\n __zfb?: ZfbBridgeNamespace;\n};\n\n/**\n * Generic shape returned for one entry in a content collection. The `data`\n * field carries parsed frontmatter, typed by the caller via the generic\n * parameter.\n */\nexport type CollectionEntry<T = Record<string, unknown>> = {\n /** Filename without `.md` extension. Stable across runs. */\n slug: string;\n /** Parsed frontmatter. */\n data: T;\n /** Raw markdown body (frontmatter stripped). */\n body: string;\n /**\n * Stable module specifier used as the bridge lookup key. Format:\n * `mdx://<collection>/<slug>` (no hash component — the JS stub does\n * not compile MDX, so it has no body hash to attach; the production\n * Rust-side `zfb-content::collection::Entry::module_specifier` adds a\n * `#<hash>` suffix and the bridge is responsible for matching either\n * form against its registered components).\n *\n * This field is part of the v0+ JS surface so the bridge has something\n * deterministic to key on without consulting per-call state.\n */\n module_specifier: string;\n /**\n * Renderable component for this entry.\n *\n * **Bridge contract.** At call time, `Content` consults\n * `globalThis.__zfb?.content?.get(entry.module_specifier)`. If the\n * bridge is present and returns a function, that function is invoked\n * with `props` and its result returned verbatim.\n *\n * **Fallback.** Outside the renderer (unit tests, dev sandboxes, or any\n * environment where `globalThis.__zfb.content.get` is absent or returns\n * `undefined`), `Content` returns a JSX-shaped element rendering the\n * raw markdown body inside a `<pre data-zfb-content-fallback>` block,\n * with a leading `[zfb fallback render]` marker line so the visual\n * distinction survives unstyled environments. The marker is also a\n * grep target for \"did the production renderer not run?\" diagnostics.\n *\n * **Typed signature.** Returns `ContentElement` (a structural alias for\n * `JSX.Element`) so consumers can drop `<entry.Content components={...} />`\n * into both React and Preact JSX without per-framework type setup.\n *\n * @example\n * const post = (await getCollection(\"blog\"))[0];\n * return <post.Content components={{ ...defaultComponents, h1: MyH1 }} />;\n */\n Content: (props: ContentProps) => ContentElement;\n};\n\n// Cached node:fs / node:path module references. Populated lazily on first\n// fs-path use (see [`loadNodeModules`]); reused on subsequent calls.\nlet cachedNodeFs: typeof NodeFs | undefined;\nlet cachedNodePath: typeof NodePath | undefined;\n\n/**\n * Synchronously load `node:fs` and `node:path`, caching the results.\n *\n * The node specifiers are concatenated at runtime (`\"node:\" + \"fs\"`) so\n * esbuild's static analyzer cannot follow them — that's the load-bearing\n * detail here, because this module is reachable from browser-bundled\n * island chains via the `@takazudo/zfb` root barrel (see top-of-file note).\n *\n * Uses CommonJS `require` via [`createRequire`] (stable, sync) rather than\n * `await import()` (async, would force `getCollection` async and violate\n * ADR-004). `createRequire` itself is fetched from `node:module` through\n * the same runtime-built specifier pattern.\n *\n * If `createRequire` cannot be obtained at all (i.e. truly running in a\n * browser-shaped runtime — which would mean a misconfigured island\n * bundle), throws so the failure is loud rather than silent.\n */\nfunction loadNodeModules(): { fs: typeof NodeFs; path: typeof NodePath } {\n if (cachedNodeFs !== undefined && cachedNodePath !== undefined) {\n return { fs: cachedNodeFs, path: cachedNodePath };\n }\n // Runtime-built specifiers: opaque to esbuild's static analyzer.\n const moduleSpecifier = \"node:\" + \"module\";\n const fsSpecifier = \"node:\" + \"fs\";\n const pathSpecifier = \"node:\" + \"path\";\n // Strategy A: prefer the host `require` from a CommonJS context. We\n // probe via `globalThis` and `Function`-built lookup so neither esbuild\n // nor stricter ESM tooling errors out at the lookup site.\n const dynamicGlobal = globalThis as unknown as { require?: NodeJS.Require };\n let nodeRequire: NodeJS.Require | undefined = dynamicGlobal.require;\n // Strategy B: ESM context — synthesize a require via `node:module`'s\n // `createRequire`. Loading `node:module` itself through the same\n // dynamic specifier shields it from esbuild's static walker.\n if (typeof nodeRequire !== \"function\") {\n // `Function(\"return require\")()` returns the enclosing `require` when\n // the bundler/loader injects one (Node CJS, esbuild default). Falls\n // through if undefined — caught below.\n try {\n nodeRequire = new Function(\"return typeof require === 'function' ? require : undefined\")() as\n | NodeJS.Require\n | undefined;\n } catch {\n nodeRequire = undefined;\n }\n }\n if (typeof nodeRequire !== \"function\") {\n // Last resort: synthesize via createRequire. Reaches `node:module`\n // through a dynamic require we have to bootstrap somehow — the only\n // way without a static `import` is `process.getBuiltinModule` (Node\n // 22+) which exposes built-ins synchronously without a require.\n const proc = (\n globalThis as unknown as { process?: { getBuiltinModule?: (id: string) => unknown } }\n ).process;\n const getBuiltin = proc?.getBuiltinModule;\n if (typeof getBuiltin === \"function\") {\n const mod = getBuiltin(moduleSpecifier) as typeof import(\"node:module\");\n nodeRequire = mod.createRequire(import.meta.url);\n }\n }\n if (typeof nodeRequire !== \"function\") {\n throw new Error(\n \"zfb/content: cannot load node:fs / node:path — no Node-style require available. \" +\n \"This module's filesystem path requires a Node runtime; if you see this in a browser \" +\n \"bundle, the bundler should externalize node:* imports (the islands bundler does so).\",\n );\n }\n cachedNodeFs = nodeRequire(fsSpecifier) as typeof NodeFs;\n cachedNodePath = nodeRequire(pathSpecifier) as typeof NodePath;\n return { fs: cachedNodeFs, path: cachedNodePath };\n}\n\n/**\n * Resolve the directory that holds a named content collection. Override\n * via `ZFB_CONTENT_ROOT` so tests / fixtures can point at an arbitrary\n * directory.\n */\nfunction resolveCollectionDir(name: string): string {\n const { path } = loadNodeModules();\n const envRoot = process.env[\"ZFB_CONTENT_ROOT\"];\n const root = envRoot ? path.resolve(envRoot) : path.resolve(process.cwd(), \"content\");\n return path.join(root, name);\n}\n\n/**\n * Build the v0 stub's bridge specifier for an entry. Mirrors the Rust-side\n * convention (`mdx://<collection>/<slug>`) minus the body hash — the JS\n * stub does not compile MDX, so it has no hash to attach. The bridge\n * resolver on the renderer side is responsible for matching either form.\n */\nfunction buildModuleSpecifier(collection: string, slug: string): string {\n return `mdx://${collection}/${slug}`;\n}\n\n/**\n * Build the `Content` component for an entry. Captures `module_specifier`\n * + `body` in the closure so the returned function takes only `props`.\n *\n * The bridge lookup is done lazily on every call (not at entry-construction\n * time) so the renderer can install / swap `globalThis.__zfb.content` at\n * any point before the first render without ordering hazards.\n */\nfunction buildContentComponent(\n module_specifier: string,\n body: string,\n): (props: ContentProps) => ContentElement {\n return function Content(props: ContentProps): ContentElement {\n const zfb = (globalThis as BridgeGlobal).__zfb;\n const bridge = zfb?.content;\n const renderer = bridge?.get(module_specifier);\n if (typeof renderer === \"function\") {\n // Merge components in documented precedence order before delegating:\n // defaultComponents → globalThis.__zfb.mdxComponents → props.components\n // This is output-neutral because defaultComponents entries are pure\n // passthroughs; the seam is established here for A2 to populate.\n const mergedProps: ContentProps = {\n ...props,\n components: mergeMdxComponents(zfb?.mdxComponents, props.components),\n };\n // Trust the bridge to return a JSX-element-shaped value — we don't\n // try to validate; both Preact and React JSX runtimes accept any\n // structural `{ type, props, key }` object on either side of the\n // boundary, and the renderer is the source of truth here.\n return renderer(mergedProps) as ContentElement;\n }\n return renderFallback(body);\n };\n}\n\n/**\n * Mint a content element through the per-project JSX runtime.\n *\n * Calls `jsx` from `react/jsx-runtime` — alias-rewritten to\n * `preact/jsx-runtime` in Preact mode by the engine (bundler.rs ~2886),\n * native in React mode — so the returned value is a real element for\n * whichever framework the project configured. This replaces the previous\n * hand-rolled `{ type, props, key, constructor: undefined }` object literal\n * (the Preact diff-path sentinel): that shape made `preact-render-to-string`\n * treat it as a VNode, but React's renderer rejects it as a child with\n * error #31 (\"Objects are not valid as a React child\") because a real React\n * element carries `$$typeof: Symbol.for(\"react.element\")`. `children` is\n * passed inside `props` so a single child or an array both pass through\n * verbatim. Same migration as `Island` in this package. Kept private so\n * callers keep treating `ContentElement` / `ContentComponentElement` as\n * opaque. (Empty-MDX-body history: zudo-doc#505.)\n */\nfunction mintElement(type: string, props: Record<string, unknown>): ContentElement {\n // `jsx`'s `type` param is typed `ElementType` (string-literal intrinsic\n // tags or component types), which rejects an arbitrary runtime `string`.\n // The tag is dynamic here, so cast to the factory's own first-param type —\n // robust whether the engine aliases `jsx` to react or preact at build time.\n return jsx(type as Parameters<typeof jsx>[0], props) as unknown as ContentElement;\n}\n\n/**\n * Build the structural JSX element returned when the bridge is absent.\n *\n * Shape: `<pre data-zfb-content-fallback>{marker}\\n{body}</pre>` — the\n * leading `[zfb fallback render]` marker line is part of the public\n * fallback contract (it's both a visual signal and a grep target). Tests\n * pin both the attribute and the marker line.\n */\nfunction renderFallback(body: string): ContentElement {\n return mintElement(\"pre\", {\n \"data-zfb-content-fallback\": \"\",\n children: `${FALLBACK_MARKER}\\n${body}`,\n });\n}\n\n/** Leading marker line emitted by [`renderFallback`]. Public contract. */\nconst FALLBACK_MARKER = \"[zfb fallback render]\";\n\n/**\n * Load every `*.md` file in the named collection. Files starting with `.`\n * or that lack a `.md` extension are ignored.\n *\n * **ADR-004 contract: this function is synchronous.** TSX page modules\n * call it from anywhere — top-level, inside a render body, inside a\n * `useMemo` — and SSR completes in a single pass without yielding. The\n * snapshot path returns from memory; the filesystem fallback uses sync\n * `node:fs` APIs so the surface stays unified. (The legacy async\n * implementation was an oversight — the ADR predates it; SSG paths\n * always saw a Promise where ADR-004 says they should see an array,\n * which is why migrations from Astro tripped on `getCollection().filter\n * is not a function`.)\n *\n * @example\n * const posts = getCollection<{ title: string; date: string }>(\"blog\");\n */\nexport function getCollection<T = Record<string, unknown>>(name: string): CollectionEntry<T>[] {\n // Snapshot path: installed by `@takazudo/zfb-runtime`'s\n // `createPageRouter` at Worker boot. Worker runtimes have no `fs`, so\n // this branch is the production path under the embedded V8 host.\n //\n // The snapshot lookup reads `globalThis.__zfb.contentSnapshot`\n // (see `setContentSnapshot` above) rather than a per-module slot so\n // the cross-`zfb/content`-instance case under `--preserve-symlinks`\n // resolves through the same shared state — see #449.\n const installedSnapshot = (globalThis as SnapshotBridgeGlobal).__zfb?.contentSnapshot;\n if (installedSnapshot !== undefined) {\n const list = installedSnapshot.collections[name] ?? [];\n return list.map((entry) => entryFromSnapshot<T>(entry));\n }\n // Filesystem fallback (v0 path). Used by unit tests and direct Node\n // invocations outside the Worker bundle.\n //\n // BCI-6: traversal is now recursive — subdirectories are walked so a\n // collection rooted at `content/blog/` can contain nested `*.md` files\n // (e.g. `content/blog/2024/hello.md`). Slugs are derived from the\n // relative path so callers get stable, unique identifiers across nesting\n // levels.\n const dir = resolveCollectionDir(name);\n let mdPaths: string[];\n try {\n mdPaths = collectMdFilesSync(dir);\n } catch (err) {\n // Guard the `code` access at runtime — a thrown non-`Error` value\n // (rare, but possible) would otherwise crash here. We only swallow\n // a true ENOENT; anything else propagates.\n if (\n err !== null &&\n typeof err === \"object\" &&\n \"code\" in err &&\n (err as { code: unknown }).code === \"ENOENT\"\n ) {\n return [];\n }\n throw err;\n }\n const { fs, path } = loadNodeModules();\n return mdPaths.map((fullPath) => {\n const raw = fs.readFileSync(fullPath, \"utf8\");\n const { data, body } = parseFrontmatter(raw);\n // Derive a stable slug from the relative path (relative to collection\n // root), stripping the `.md` extension. For top-level files this\n // produces the same value as before; for nested files it produces a\n // path-based slug (e.g. `2024/hello`).\n const rel = path.relative(dir, fullPath);\n const slug = _relPathToSlug(rel);\n const module_specifier = buildModuleSpecifier(name, slug);\n return {\n slug,\n data: data as T,\n body,\n module_specifier,\n Content: buildContentComponent(module_specifier, body),\n };\n });\n}\n\n/**\n * Look up a single entry in a content collection by slug.\n *\n * Thin wrapper over [`getCollection`]: inherits both resolution paths\n * (snapshot via `globalThis.__zfb.contentSnapshot` and the `node:fs`\n * fallback) for free. Returns `undefined` when either the collection does\n * not exist or no entry matches `slug`.\n *\n * **Runtime vs. generated types divergence.** The generated `types.d.ts`\n * emits a keyed overload (`K extends keyof ZfbCollections`) that ties the\n * return type to the collection's declared schema. This runtime form is\n * intentionally structural — it does not reference `ZfbCollections` and\n * does not attempt to reconcile with the keyed shape. (#857)\n *\n * @example\n * const post = getEntry<{ title: string }>(\"blog\", \"hello-zfb\");\n * if (!post) return null;\n * return <post.Content />;\n */\nexport function getEntry<T = Record<string, unknown>>(\n name: string,\n slug: string,\n): CollectionEntry<T> | undefined {\n return getCollection<T>(name).find((e) => e.slug === slug);\n}\n\n/**\n * Construct a [`CollectionEntry`] from a [`SnapshotEntry`]. The snapshot\n * carries `frontmatter` as a possibly-`null` JSON value (matches the\n * Rust contract for entries with no frontmatter); we normalise `null` /\n * `undefined` to an empty object so consumers' `.data.title` reads\n * never have to deal with `null`.\n *\n * **Type-safety note:** `T` is the caller-supplied frontmatter shape\n * but we do **not** validate it at runtime — if the page declares a\n * shape that the actual frontmatter doesn't match, the cast below\n * lies. Callers are expected to keep their `getCollection<MySchema>()`\n * generic in sync with the actual frontmatter; we acknowledge the\n * unsafety with the explicit `unknown` indirection rather than a\n * direct (and silently lossy) cast.\n */\nfunction entryFromSnapshot<T>(entry: SnapshotEntry): CollectionEntry<T> {\n const data =\n entry.frontmatter === null || entry.frontmatter === undefined\n ? ({} as T)\n : (entry.frontmatter as unknown as T);\n return {\n slug: entry.slug,\n data,\n body: entry.body,\n module_specifier: entry.module_specifier,\n Content: buildContentComponent(entry.module_specifier, entry.body),\n };\n}\n\n/**\n * Recursively collect every `*.md` file under `dir` (synchronous).\n *\n * BCI-6: replaces the old flat `readdir(dir).filter(n => n.endsWith(\".md\"))`\n * approach. Hidden files (names starting with `.`) and hidden directories\n * are skipped at every nesting level, matching the top-level behaviour of\n * the previous implementation.\n *\n * Returns absolute paths sorted lexicographically so the result order is\n * deterministic across platforms and Node versions.\n *\n * Synchronous to honour ADR-004 — see [`getCollection`].\n */\nfunction collectMdFilesSync(dir: string): string[] {\n const result: string[] = [];\n const { fs, path } = loadNodeModules();\n walkDirSync(fs, path, dir, result);\n result.sort();\n return result;\n}\n\nfunction walkDirSync(\n fs: typeof NodeFs,\n path: typeof NodePath,\n current: string,\n out: string[],\n): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name.startsWith(\".\")) continue;\n const fullPath = path.join(current, entry.name);\n // Skip symlinks to avoid infinite loops caused by cycles (e.g. a symlink\n // pointing at a parent directory). Content files are expected to be plain\n // regular files; following symlinks provides no value here.\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory()) {\n walkDirSync(fs, path, fullPath, out);\n } else if (entry.isFile() && entry.name.endsWith(\".md\")) {\n out.push(fullPath);\n }\n }\n}\n\n/**\n * @internal\n *\n * Convert a `path.relative()` result into a forward-slash-separated\n * slug with the trailing `.md` extension stripped.\n *\n * Slugs are URL-flavored identifiers, not filesystem paths — they\n * MUST use `/` regardless of the host OS so a nested entry like\n * `2024/hello.md` produces the slug `2024/hello` on both POSIX and\n * Windows. Without this normalisation, Windows callers would see\n * `2024\\hello`, which then leaks through to `module_specifier` and\n * any URL the consumer derives from the slug.\n *\n * Exported solely so the unit test suite can pin the Windows\n * behaviour without needing an actual Windows host. Do not depend on\n * this from application code — name and signature may change.\n */\nexport function _relPathToSlug(relPath: string): string {\n const { path } = loadNodeModules();\n const posix = path.sep === \"/\" ? relPath : relPath.split(path.sep).join(\"/\");\n // Some Node versions normalise `\\` even when sep is `/`, so be\n // defensive: collapse any straggling backslashes too.\n const normalised = posix.includes(\"\\\\\") ? posix.split(\"\\\\\").join(\"/\") : posix;\n return normalised.endsWith(\".md\") ? normalised.slice(0, -\".md\".length) : normalised;\n}\n\n// ---------------------------------------------------------------------------\n// `defaultComponents` — htmlOverrides convention\n//\n// Ported from zudo-doc's `src/components/content/component-map.ts`. Users opt\n// in by spreading the map into their own `components` prop:\n//\n// import { defaultComponents } from \"zfb\";\n// <entry.Content components={{ ...defaultComponents, h2: MyH2 }} />\n//\n// Each component is a thin passthrough mirroring its zudo-doc counterpart\n// (e.g. `ContentParagraph` → `<p {...rest}>{children}</p>`). v0 ships the\n// passthroughs unstyled; layering smart-break / heading-anchor / link-icon\n// behaviour on top is independent follow-up — keeping the v0 deliverable\n// focused on infrastructure (issue #33).\n//\n// **`h1` is deliberately not in the map** — page titles render `<h1>` from\n// frontmatter, per the zudo-doc convention. Adding `h1` here would silently\n// double-render the page title.\n//\n// **Each override is exported as a named const AND included in\n// `defaultComponents`** so consumers can tree-shake-import a single component\n// (`import { ContentLink } from \"zfb\"`) without dragging in the whole map.\n//\n// Implementation note: components return the structural JSX-element shape\n// directly — same pattern as `Island`. This keeps the package\n// JSX-runtime-agnostic so it works under either Preact or React without\n// importing a runtime. Both `jsx-runtime` implementations accept the\n// `{ type, props, key }` object on either side of the boundary.\n// ---------------------------------------------------------------------------\n\n/**\n * Public JSX-element shape returned by every override in [`defaultComponents`].\n *\n * Mirrors [`ContentElement`] and [`IslandElement`]: a structural alias for\n * `JSX.Element` so consumers can drop these overrides into both React and\n * Preact JSX without per-framework type setup.\n */\nexport type ContentComponentElement = {\n readonly type: string;\n readonly props: Readonly<Record<string, unknown>>;\n readonly key: unknown;\n};\n\n/**\n * Props accepted by every default override. `children` and any extra\n * attributes (`className`, `id`, `href`, …) are passed through verbatim\n * to the underlying HTML element.\n */\nexport interface ContentComponentProps {\n children?: VNode;\n [key: string]: unknown;\n}\n\n/** Internal helper: build a structural JSX element of the given tag. */\nfunction buildOverrideElement(tag: string, props: ContentComponentProps): ContentComponentElement {\n const { children, ...rest } = props;\n // Minted through the per-project JSX runtime (`mintElement`) so the\n // override is a real element under both React and Preact — see the\n // helper's docblock (zudo-doc#505; React error #31 rationale).\n return mintElement(tag, { ...rest, children }) as unknown as ContentComponentElement;\n}\n\n/**\n * `<h2>` passthrough override. Ported from zudo-doc's `HeadingH2`, stripped\n * of styling — v0 ships pass-through behaviour; visual treatment is layered\n * on by the consumer (or by a follow-up enhancement pass).\n */\nexport function ContentH2(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"h2\", props);\n}\n\n/** `<h3>` passthrough override. See [`ContentH2`] for the contract. */\nexport function ContentH3(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"h3\", props);\n}\n\n/** `<h4>` passthrough override. See [`ContentH2`] for the contract. */\nexport function ContentH4(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"h4\", props);\n}\n\n/** `<p>` passthrough override. Mirrors zudo-doc's `ContentParagraph`. */\nexport function ContentParagraph(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"p\", props);\n}\n\n/** `<a>` passthrough override. Mirrors zudo-doc's `ContentLink`. */\nexport function ContentLink(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"a\", props);\n}\n\n/** `<strong>` passthrough override. Mirrors zudo-doc's `ContentStrong`. */\nexport function ContentStrong(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"strong\", props);\n}\n\n/** `<blockquote>` passthrough override. Mirrors zudo-doc's `ContentBlockquote`. */\nexport function ContentBlockquote(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"blockquote\", props);\n}\n\n/** `<ul>` passthrough override. Mirrors zudo-doc's `ContentUl`. */\nexport function ContentUl(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"ul\", props);\n}\n\n/** `<ol>` passthrough override. Mirrors zudo-doc's `ContentOl`. */\nexport function ContentOl(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"ol\", props);\n}\n\n/** `<table>` passthrough override. Mirrors zudo-doc's `ContentTable`. */\nexport function ContentTable(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"table\", props);\n}\n\n/** `<code>` passthrough override. Mirrors zudo-doc's `ContentCode`. */\nexport function ContentCode(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"code\", props);\n}\n\n/**\n * Default per-element override map — eleven entries covering the markdown\n * tags the zudo-doc convention overrides (`h2`, `h3`, `h4`, `p`, `a`,\n * `strong`, `blockquote`, `ul`, `ol`, `table`, `code`).\n *\n * `h1` is intentionally absent: page titles render from frontmatter, per\n * the zudo-doc convention.\n *\n * Spread into a `components` prop to compose with custom overrides:\n *\n * ```tsx\n * import { defaultComponents } from \"zfb\";\n *\n * <entry.Content components={{ ...defaultComponents, h2: MyFancyH2 }} />\n * ```\n */\nexport const defaultComponents = {\n h2: ContentH2,\n h3: ContentH3,\n h4: ContentH4,\n p: ContentParagraph,\n a: ContentLink,\n strong: ContentStrong,\n blockquote: ContentBlockquote,\n ul: ContentUl,\n ol: ContentOl,\n table: ContentTable,\n code: ContentCode,\n} as const;\n\n/**\n * Merge component maps with the documented precedence order:\n * built-in `defaultComponents` → global slot (`globalThis.__zfb?.mdxComponents`)\n * → per-call `props.components`.\n *\n * Spread in stable key order so the resulting map is deterministic; later\n * entries in the spread win on collision (lowest → highest priority). Absent\n * layers (`undefined`) are no-ops via spread-of-undefined.\n *\n * **Output-neutral by design:** `defaultComponents` entries are pure\n * passthroughs (e.g. `ContentH2` → `<h2>{...props}</h2>`), so introducing\n * this merge into `buildContentComponent` does not change the rendered output.\n */\nexport function mergeMdxComponents(\n globalSlot: MdxComponents | undefined,\n perCall: MdxComponents | undefined,\n): MdxComponents {\n return { ...defaultComponents, ...globalSlot, ...perCall };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"content.js","sourceRoot":"","sources":["../src/content.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,sEAAsE;AACtE,uEAAuE;AACvE,kFAAkF;AAClF,0EAA0E;AAC1E,0EAA0E;AAC1E,2CAA2C;AAC3C,EAAE;AACF,cAAc;AACd,2EAA2E;AAC3E,6DAA6D;AAC7D,0EAA0E;AAC1E,oEAAoE;AACpE,wEAAwE;AACxE,QAAQ;AACR,qCAAqC;AACrC,uEAAuE;AACvE,wEAAwE;AACxE,EAAE;AACF,4EAA4E;AAC5E,4CAA4C;AAE5C,yEAAyE;AACzE,iBAAiB;AACjB,EAAE;AACF,6EAA6E;AAC7E,kEAAkE;AAClE,8EAA8E;AAC9E,0EAA0E;AAC1E,sEAAsE;AACtE,yEAAyE;AACzE,kEAAkE;AAClE,mEAAmE;AACnE,qEAAqE;AACrE,sEAAsE;AACtE,0EAA0E;AAC1E,wEAAwE;AACxE,uEAAuE;AACvE,gEAAgE;AAChE,8CAA8C;AAC9C,EAAE;AACF,sEAAsE;AACtE,0EAA0E;AAC1E,yEAAyE;AACzE,0CAA0C;AAC1C,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAKxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAIpD,wEAAwE;AACxE,mEAAmE;AACnE,2EAA2E;AAC3E,qEAAqE;AACrE,8BAA8B;AAC9B,OAAO,EAAE,gBAAgB,EAAE,CAAC;AA0F5B;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,kBAAkB,CAAC,QAA8B;IAC/D,MAAM,CAAC,GAAG,UAAkC,CAAC;IAC7C,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAA4B,CAAC;IACtD,EAAE,CAAC,eAAe,GAAG,QAAQ,CAAC;I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`*.md` files from a content collection directory, parses YAML\n// frontmatter, and returns typed entries. This is a deliberately small\n// stub so the bundled basic-blog template can call `getCollection(\"blog\")` today;\n// the production path lives in `crates/zfb-content` and will replace this\n// once the JS-runtime decision (ADR-001) lands and the renderer wires the\n// Rust pipeline back through to user code.\n//\n// Scope (v0):\n// - YAML-ish frontmatter only: `key: value`, plus `key:\\n - item` arrays.\n// Quoted strings are unwrapped. ISO dates stay as strings.\n// - Body is the post content **after** the closing `---`, returned as raw\n// text. This is intentionally NOT pre-rendered HTML: the markdown\n// pipeline lives in the Rust crate and the JS stub does not duplicate\n// it.\n// - Collection root is resolved from\n// `process.env.ZFB_CONTENT_ROOT` (set by the dev/build pipeline), or\n// `<cwd>/content` as a fallback for unit tests and direct invocation.\n//\n// TODO(zfb-content): swap this stub for the runtime-provided implementation\n// once the content engine ships end-to-end.\n\n// `node:fs` and `node:path` are intentionally NOT imported statically at\n// the top level.\n//\n// Why: this module is reachable via the package root (`@takazudo/zfb`) — the\n// barrel re-exports `defaultComponents` / `ContentH2` / etc. from\n// `./content.js`. The islands per-island bundler (`crates/zfb-islands`) walks\n// `import * as Mod from \"@takazudo/zfb\"` and esbuild's static tree-shaker\n// cannot prune a module behind a wildcard barrel access, so the WHOLE\n// content.ts module ends up in the browser-side island bundle. Top-level\n// `node:fs` / `node:path` imports would then fail the bundle with\n// `Could not resolve \"node:fs\"`. Loading them indirectly through a\n// runtime-constructed `createRequire` keeps the Node-runtime fs path\n// working while letting the islands bundler emit browser-safe output.\n// (Discovered while investigating zudolab/zudo-doc#1355 Wave 3 — see also\n// upstream PR #134 / #130 Gap A.) Defense-in-depth: the islands esbuild\n// invocation also passes `--platform=browser --external:node:*` so any\n// stray `node:*` import that does end up in a browser bundle is\n// externalized rather than failing the build.\n//\n// `getCollection` is synchronous per ADR-004, so the node modules are\n// loaded synchronously on first fs-path use. Type-only imports below stay\n// at the top because TypeScript erases them at compile time — they leave\n// no runtime traces for esbuild to chase.\nimport { jsx } from \"react/jsx-runtime\";\n\nimport type * as NodeFs from \"node:fs\";\nimport type * as NodePath from \"node:path\";\n\nimport { parseFrontmatter } from \"./frontmatter.js\";\nimport type { ParsedFrontmatter } from \"./frontmatter.js\";\nimport type { VNode } from \"./jsx-types.js\";\n\n// Re-export the parser surface so existing `zfb/content` consumers that\n// import `parseFrontmatter` / `ParsedFrontmatter` from the content\n// subpath keep working. The implementation now lives in `./frontmatter.ts`\n// (BCI-3 fs-free subpath) — this re-export is the bridge for callers\n// that have not migrated yet.\nexport { parseFrontmatter };\nexport type { ParsedFrontmatter };\n\n// ---------------------------------------------------------------------------\n// In-memory ContentSnapshot bridge (consumed by `@takazudo/zfb-runtime`).\n//\n// At build time, the Rust pipeline produces a `ContentSnapshot` (see\n// `crates/zfb-content/src/content_bridge.rs`) and embeds it into the\n// Worker bundle. On Worker boot, `createPageRouter` calls\n// `setContentSnapshot(snapshot)` (below) before serving the first\n// request. From that point on, `getCollection(name)` resolves from the\n// embedded snapshot rather than the Node `fs` API — required because the\n// workerd / Cloudflare Workers runtime has no filesystem.\n//\n// The fs path remains the source of truth in two contexts:\n// 1. unit tests for this module (no snapshot installed → fs path),\n// 2. dev-preview / direct-Node invocations of `getCollection` outside\n// the Worker bundle (kept as v0 fallback so older callers still work).\n//\n// Keep [`SnapshotEntry`] / [`Snapshot`] aligned with the Rust struct\n// (`EntrySnapshot` / `ContentSnapshot`) and the runtime-package mirror\n// (`@takazudo/zfb-runtime/snapshot`). Field names are snake_case to\n// match the JSON serialization (`module_specifier`, `rel_path`).\n// ---------------------------------------------------------------------------\n\n/**\n * One entry in an embedded content snapshot. Mirrors\n * `crates/zfb-content/src/content_bridge.rs::EntrySnapshot`. Re-exported\n * by `@takazudo/zfb-runtime/snapshot` for the runtime-side bundle. See\n * that module for field-by-field documentation.\n */\nexport interface SnapshotEntry {\n readonly slug: string;\n readonly frontmatter: unknown;\n readonly body: string;\n readonly module_specifier: string;\n readonly rel_path: string;\n}\n\n/**\n * Point-in-time snapshot of every configured collection. Mirrors\n * `crates/zfb-content/src/content_bridge.rs::ContentSnapshot`.\n */\nexport interface Snapshot {\n readonly collections: Readonly<Record<string, readonly SnapshotEntry[]>>;\n}\n\n/**\n * Where the installed [`Snapshot`] lives.\n *\n * The state hangs off `globalThis.__zfb.contentSnapshot`, NOT a\n * module-level `let`. This matters because under the production worker\n * bundle the consumer's pnpm-strict `node_modules` layout exposes\n * two physical paths to `@takazudo/zfb`:\n *\n * - top-level `node_modules/@takazudo/zfb` (imported by user pages), AND\n * - nested `node_modules/.pnpm/@takazudo+zfb-runtime@.../node_modules/\n * @takazudo/zfb` (imported by `@takazudo/zfb-runtime` itself).\n *\n * The bundler passes `esbuild --preserve-symlinks` whenever a custom\n * `node_modules_dir` is configured (see `crates/zfb-build/src/bundler.rs`\n * around `--external:node:*`), so esbuild treats those two symlink\n * targets as distinct sources and inlines `content.js` TWICE — yielding\n * two module instances of `zfb/content` in the final worker bundle.\n *\n * If `installedSnapshot` were a per-module `let`, `createPageRouter`\n * would install the snapshot on the runtime's copy and `getCollection`\n * (called from a user `paths()` export) would read from the user\n * page's copy — see `undefined`, and fall through to the `node:fs`\n * branch, which then throws because `node:*` is externalized in the\n * worker bundle. This is the regression #442 / #449 surfaced.\n *\n * Routing the slot through `globalThis` makes the snapshot bridge\n * symmetric with the existing `globalThis.__zfb.content` MDX-component\n * bridge (set by the build pipeline at `crates/zfb-build/src/bundler.rs`,\n * read by `Content` below): both pieces of cross-module state share\n * one well-known global, so any number of `zfb/content` module\n * instances in the same JS realm see the same value.\n *\n * Tracked under #449 (production fix for #442); the test-fixture\n * counterpart was #413.\n */\ntype SnapshotBridgeNamespace = {\n contentSnapshot?: Snapshot | undefined;\n};\n\ntype SnapshotBridgeGlobal = typeof globalThis & {\n __zfb?: SnapshotBridgeNamespace;\n};\n\n/**\n * Register a [`Snapshot`] so [`getCollection`] resolves from memory.\n *\n * Pass `undefined` to clear (used by tests that need to restore the v0\n * filesystem path between runs). Idempotent: the latest call wins.\n *\n * Stored on `globalThis.__zfb.contentSnapshot` rather than a\n * module-level `let` so a worker bundle that ends up with two\n * `zfb/content` module instances still sees a single shared snapshot —\n * see the [`SnapshotBridgeNamespace`] doc above for the full\n * pnpm-symlink rationale.\n */\nexport function setContentSnapshot(snapshot: Snapshot | undefined): void {\n const g = globalThis as SnapshotBridgeGlobal;\n const ns = (g.__zfb ?? {}) as SnapshotBridgeNamespace;\n ns.contentSnapshot = snapshot;\n g.__zfb = ns;\n}\n\n/**\n * Read the currently-installed [`Snapshot`], or `undefined` if none is\n * registered. Exposed mostly for tests; production callers should not\n * need to introspect the bridge state.\n *\n * Reads from `globalThis.__zfb.contentSnapshot`; see\n * [`setContentSnapshot`] for why the slot lives on `globalThis`.\n */\nexport function getContentSnapshot(): Snapshot | undefined {\n return (globalThis as SnapshotBridgeGlobal).__zfb?.contentSnapshot;\n}\n\n/**\n * Flat map of element-name → override component, used by both\n * [`ContentProps.components`] and the global slot\n * (`globalThis.__zfb?.mdxComponents`). Keys are lowercase HTML tag names\n * (`h2`, `p`, `a`, …) or PascalCase custom-component names.\n */\nexport type MdxComponents = Record<string, unknown>;\n\n/**\n * Props accepted by an entry's [`CollectionEntry.Content`] component.\n *\n * `components` mirrors Astro's `<Content components={...}>` contract:\n * a flat record of element-name → override component (e.g. `{ h1: MyH1 }`).\n * The default-components convention ships from `zfb`'s root export\n * (`defaultComponents`, lands in Sub 6) and users compose with their own\n * via `{ ...defaultComponents, ...mine }`.\n */\nexport interface ContentProps {\n /** Element-name → override component map. Optional. */\n components?: MdxComponents;\n}\n\n/**\n * Public JSX-element shape returned by [`CollectionEntry.Content`].\n *\n * Matches the structural shape that both Preact's and React's `jsx-runtime`\n * accept on either side of the boundary, mirroring the Island wrapper's\n * approach. Consumers should treat this as opaque — its only contract is\n * \"renderable JSX value\".\n *\n * Aliased as `JSX.Element` in the field signature: the JS runtime is\n * type-erased and the actual VNode shape is supplied by the framework\n * adapter at evaluation time.\n */\nexport type ContentElement = {\n readonly type: string | ((...args: unknown[]) => unknown);\n readonly props: Readonly<Record<string, unknown>>;\n readonly key: unknown;\n};\n\n/**\n * Bridge contract published by the Rust-side `zfb-render` `Renderer` before\n * evaluating each page module. Cross-referenced from the Rust side in\n * `crates/zfb-render/src/loader.rs` so the two halves stay in sync — see\n * `packages/zfb/CONTRIBUTING.md` for the full contract narrative.\n *\n * The renderer installs `globalThis.__zfb.content.get(specifier)` keyed on\n * the entry's `module_specifier` (Sub 4 convention: `mdx://<collection>/<slug>#<hash>`,\n * collapsed to `mdx://<collection>/<slug>` from the JS stub side which has\n * no hash to compute). When `get` returns `undefined` (or the bridge as a\n * whole is absent — typical of unit tests, dev sandboxes, and any\n * non-renderer evaluation context), `Content` renders a clearly-marked\n * `<pre data-zfb-content-fallback>` fallback so the visual distinction is\n * obvious even in unstyled environments.\n */\ntype ContentBridge = {\n get(specifier: string): ((props: ContentProps) => unknown) | undefined;\n};\n\ntype ZfbBridgeNamespace = {\n content?: ContentBridge;\n /**\n * Global component-override slot. Populated by sub-task A2 (bridge\n * installer); A1 only reads it. Absent ⇒ no-op in the merge.\n */\n mdxComponents?: MdxComponents;\n};\n\ntype BridgeGlobal = typeof globalThis & {\n __zfb?: ZfbBridgeNamespace;\n};\n\n/**\n * Generic shape returned for one entry in a content collection. The `data`\n * field carries parsed frontmatter, typed by the caller via the generic\n * parameter.\n */\nexport type CollectionEntry<T = Record<string, unknown>> = {\n /** Filename without `.md` extension. Stable across runs. */\n slug: string;\n /** Parsed frontmatter. */\n data: T;\n /** Raw markdown body (frontmatter stripped). */\n body: string;\n /**\n * Stable module specifier used as the bridge lookup key. Format:\n * `mdx://<collection>/<slug>` (no hash component — the JS stub does\n * not compile MDX, so it has no body hash to attach; the production\n * Rust-side `zfb-content::collection::Entry::module_specifier` adds a\n * `#<hash>` suffix and the bridge is responsible for matching either\n * form against its registered components).\n *\n * This field is part of the v0+ JS surface so the bridge has something\n * deterministic to key on without consulting per-call state.\n */\n module_specifier: string;\n /**\n * Renderable component for this entry.\n *\n * **Bridge contract.** At call time, `Content` consults\n * `globalThis.__zfb?.content?.get(entry.module_specifier)`. If the\n * bridge is present and returns a function, that function is invoked\n * with `props` and its result returned verbatim.\n *\n * **Fallback.** Outside the renderer (unit tests, dev sandboxes, or any\n * environment where `globalThis.__zfb.content.get` is absent or returns\n * `undefined`), `Content` returns a JSX-shaped element rendering the\n * raw markdown body inside a `<pre data-zfb-content-fallback>` block,\n * with a leading `[zfb fallback render]` marker line so the visual\n * distinction survives unstyled environments. The marker is also a\n * grep target for \"did the production renderer not run?\" diagnostics.\n *\n * **Typed signature.** Returns `ContentElement` (a structural alias for\n * `JSX.Element`) so consumers can drop `<entry.Content components={...} />`\n * into both React and Preact JSX without per-framework type setup.\n *\n * @example\n * const post = (await getCollection(\"blog\"))[0];\n * return <post.Content components={{ ...defaultComponents, h1: MyH1 }} />;\n */\n Content: (props: ContentProps) => ContentElement;\n};\n\n// Cached node:fs / node:path module references. Populated lazily on first\n// fs-path use (see [`loadNodeModules`]); reused on subsequent calls.\nlet cachedNodeFs: typeof NodeFs | undefined;\nlet cachedNodePath: typeof NodePath | undefined;\n\n/**\n * Synchronously load `node:fs` and `node:path`, caching the results.\n *\n * The node specifiers are concatenated at runtime (`\"node:\" + \"fs\"`) so\n * esbuild's static analyzer cannot follow them — that's the load-bearing\n * detail here, because this module is reachable from browser-bundled\n * island chains via the `@takazudo/zfb` root barrel (see top-of-file note).\n *\n * Uses CommonJS `require` via [`createRequire`] (stable, sync) rather than\n * `await import()` (async, would force `getCollection` async and violate\n * ADR-004). `createRequire` itself is fetched from `node:module` through\n * the same runtime-built specifier pattern.\n *\n * If `createRequire` cannot be obtained at all (i.e. truly running in a\n * browser-shaped runtime — which would mean a misconfigured island\n * bundle), throws so the failure is loud rather than silent.\n */\nfunction loadNodeModules(): { fs: typeof NodeFs; path: typeof NodePath } {\n if (cachedNodeFs !== undefined && cachedNodePath !== undefined) {\n return { fs: cachedNodeFs, path: cachedNodePath };\n }\n // Runtime-built specifiers: opaque to esbuild's static analyzer.\n const moduleSpecifier = \"node:\" + \"module\";\n const fsSpecifier = \"node:\" + \"fs\";\n const pathSpecifier = \"node:\" + \"path\";\n // Strategy A: prefer the host `require` from a CommonJS context. We\n // probe via `globalThis` and `Function`-built lookup so neither esbuild\n // nor stricter ESM tooling errors out at the lookup site.\n const dynamicGlobal = globalThis as unknown as { require?: NodeJS.Require };\n let nodeRequire: NodeJS.Require | undefined = dynamicGlobal.require;\n // Strategy B: ESM context — synthesize a require via `node:module`'s\n // `createRequire`. Loading `node:module` itself through the same\n // dynamic specifier shields it from esbuild's static walker.\n if (typeof nodeRequire !== \"function\") {\n // `Function(\"return require\")()` returns the enclosing `require` when\n // the bundler/loader injects one (Node CJS, esbuild default). Falls\n // through if undefined — caught below.\n try {\n nodeRequire = new Function(\"return typeof require === 'function' ? require : undefined\")() as\n | NodeJS.Require\n | undefined;\n } catch {\n nodeRequire = undefined;\n }\n }\n if (typeof nodeRequire !== \"function\") {\n // Last resort: synthesize via createRequire. Reaches `node:module`\n // through a dynamic require we have to bootstrap somehow — the only\n // way without a static `import` is `process.getBuiltinModule` (Node\n // 22+) which exposes built-ins synchronously without a require.\n const proc = (\n globalThis as unknown as { process?: { getBuiltinModule?: (id: string) => unknown } }\n ).process;\n const getBuiltin = proc?.getBuiltinModule;\n if (typeof getBuiltin === \"function\") {\n const mod = getBuiltin(moduleSpecifier) as typeof import(\"node:module\");\n nodeRequire = mod.createRequire(import.meta.url);\n }\n }\n if (typeof nodeRequire !== \"function\") {\n throw new Error(\n \"zfb/content: cannot load node:fs / node:path — no Node-style require available. \" +\n \"This module's filesystem path requires a Node runtime; if you see this in a browser \" +\n \"bundle, the bundler should externalize node:* imports (the islands bundler does so).\",\n );\n }\n cachedNodeFs = nodeRequire(fsSpecifier) as typeof NodeFs;\n cachedNodePath = nodeRequire(pathSpecifier) as typeof NodePath;\n return { fs: cachedNodeFs, path: cachedNodePath };\n}\n\n/**\n * Resolve the directory that holds a named content collection. Override\n * via `ZFB_CONTENT_ROOT` so tests / fixtures can point at an arbitrary\n * directory.\n */\nfunction resolveCollectionDir(name: string): string {\n const { path } = loadNodeModules();\n const envRoot = process.env[\"ZFB_CONTENT_ROOT\"];\n const root = envRoot ? path.resolve(envRoot) : path.resolve(process.cwd(), \"content\");\n return path.join(root, name);\n}\n\n/**\n * Build the v0 stub's bridge specifier for an entry. Mirrors the Rust-side\n * convention (`mdx://<collection>/<slug>`) minus the body hash — the JS\n * stub does not compile MDX, so it has no hash to attach. The bridge\n * resolver on the renderer side is responsible for matching either form.\n */\nfunction buildModuleSpecifier(collection: string, slug: string): string {\n return `mdx://${collection}/${slug}`;\n}\n\n/**\n * Build the `Content` component for an entry. Captures `module_specifier`\n * + `body` in the closure so the returned function takes only `props`.\n *\n * The bridge lookup is done lazily on every call (not at entry-construction\n * time) so the renderer can install / swap `globalThis.__zfb.content` at\n * any point before the first render without ordering hazards.\n */\nfunction buildContentComponent(\n module_specifier: string,\n body: string,\n): (props: ContentProps) => ContentElement {\n return function Content(props: ContentProps): ContentElement {\n const zfb = (globalThis as BridgeGlobal).__zfb;\n const bridge = zfb?.content;\n const renderer = bridge?.get(module_specifier);\n if (typeof renderer === \"function\") {\n // Merge components in documented precedence order before delegating:\n // defaultComponents → globalThis.__zfb.mdxComponents → props.components\n // This is output-neutral because defaultComponents entries are pure\n // passthroughs; the seam is established here for A2 to populate.\n const mergedProps: ContentProps = {\n ...props,\n components: mergeMdxComponents(zfb?.mdxComponents, props.components),\n };\n // Trust the bridge to return a JSX-element-shaped value — we don't\n // try to validate; both Preact and React JSX runtimes accept any\n // structural `{ type, props, key }` object on either side of the\n // boundary, and the renderer is the source of truth here.\n return renderer(mergedProps) as ContentElement;\n }\n return renderFallback(body);\n };\n}\n\n/**\n * Mint a content element through the per-project JSX runtime.\n *\n * Calls `jsx` from `react/jsx-runtime` — alias-rewritten to\n * `preact/jsx-runtime` in Preact mode by the engine (bundler.rs ~2886),\n * native in React mode — so the returned value is a real element for\n * whichever framework the project configured. This replaces the previous\n * hand-rolled `{ type, props, key, constructor: undefined }` object literal\n * (the Preact diff-path sentinel): that shape made `preact-render-to-string`\n * treat it as a VNode, but React's renderer rejects it as a child with\n * error #31 (\"Objects are not valid as a React child\") because a real React\n * element carries `$$typeof: Symbol.for(\"react.element\")`. `children` is\n * passed inside `props` so a single child or an array both pass through\n * verbatim. Same migration as `Island` in this package. Kept private so\n * callers keep treating `ContentElement` / `ContentComponentElement` as\n * opaque. (Empty-MDX-body history: zudo-doc#505.)\n */\nfunction mintElement(type: string, props: Record<string, unknown>): ContentElement {\n // `jsx`'s `type` param is typed `ElementType` (string-literal intrinsic\n // tags or component types), which rejects an arbitrary runtime `string`.\n // The tag is dynamic here, so cast to the factory's own first-param type —\n // robust whether the engine aliases `jsx` to react or preact at build time.\n return jsx(type as Parameters<typeof jsx>[0], props) as unknown as ContentElement;\n}\n\n/**\n * Build the structural JSX element returned when the bridge is absent.\n *\n * Shape: `<pre data-zfb-content-fallback>{marker}\\n{body}</pre>` — the\n * leading `[zfb fallback render]` marker line is part of the public\n * fallback contract (it's both a visual signal and a grep target). Tests\n * pin both the attribute and the marker line.\n */\nfunction renderFallback(body: string): ContentElement {\n return mintElement(\"pre\", {\n \"data-zfb-content-fallback\": \"\",\n children: `${FALLBACK_MARKER}\\n${body}`,\n });\n}\n\n/** Leading marker line emitted by [`renderFallback`]. Public contract. */\nconst FALLBACK_MARKER = \"[zfb fallback render]\";\n\n/**\n * Load every `*.md` file in the named collection. Files starting with `.`\n * or that lack a `.md` extension are ignored.\n *\n * **ADR-004 contract: this function is synchronous.** TSX page modules\n * call it from anywhere — top-level, inside a render body, inside a\n * `useMemo` — and SSR completes in a single pass without yielding. The\n * snapshot path returns from memory; the filesystem fallback uses sync\n * `node:fs` APIs so the surface stays unified. (The legacy async\n * implementation was an oversight — the ADR predates it; SSG paths\n * always saw a Promise where ADR-004 says they should see an array,\n * which is why migrations from Astro tripped on `getCollection().filter\n * is not a function`.)\n *\n * @example\n * const posts = getCollection<{ title: string; date: string }>(\"blog\");\n */\nexport function getCollection<T = Record<string, unknown>>(name: string): CollectionEntry<T>[] {\n // Snapshot path: installed by `@takazudo/zfb-runtime`'s\n // `createPageRouter` at Worker boot. Worker runtimes have no `fs`, so\n // this branch is the production path under the embedded V8 host.\n //\n // The snapshot lookup reads `globalThis.__zfb.contentSnapshot`\n // (see `setContentSnapshot` above) rather than a per-module slot so\n // the cross-`zfb/content`-instance case under `--preserve-symlinks`\n // resolves through the same shared state — see #449.\n const installedSnapshot = (globalThis as SnapshotBridgeGlobal).__zfb?.contentSnapshot;\n if (installedSnapshot !== undefined) {\n const list = installedSnapshot.collections[name] ?? [];\n return list.map((entry) => entryFromSnapshot<T>(entry));\n }\n // Filesystem fallback (v0 path). Used by unit tests and direct Node\n // invocations outside the Worker bundle.\n //\n // BCI-6: traversal is now recursive — subdirectories are walked so a\n // collection rooted at `content/blog/` can contain nested `*.md` files\n // (e.g. `content/blog/2024/hello.md`). Slugs are derived from the\n // relative path so callers get stable, unique identifiers across nesting\n // levels.\n const dir = resolveCollectionDir(name);\n let mdPaths: string[];\n try {\n mdPaths = collectMdFilesSync(dir);\n } catch (err) {\n // Guard the `code` access at runtime — a thrown non-`Error` value\n // (rare, but possible) would otherwise crash here. We only swallow\n // a true ENOENT; anything else propagates.\n if (\n err !== null &&\n typeof err === \"object\" &&\n \"code\" in err &&\n (err as { code: unknown }).code === \"ENOENT\"\n ) {\n return [];\n }\n throw err;\n }\n const { fs, path } = loadNodeModules();\n return mdPaths.map((fullPath) => {\n const raw = fs.readFileSync(fullPath, \"utf8\");\n const { data, body } = parseFrontmatter(raw);\n // Derive a stable slug from the relative path (relative to collection\n // root), stripping the `.md` extension. For top-level files this\n // produces the same value as before; for nested files it produces a\n // path-based slug (e.g. `2024/hello`).\n const rel = path.relative(dir, fullPath);\n const slug = _relPathToSlug(rel);\n const module_specifier = buildModuleSpecifier(name, slug);\n return {\n slug,\n data: data as T,\n body,\n module_specifier,\n Content: buildContentComponent(module_specifier, body),\n };\n });\n}\n\n/**\n * Look up a single entry in a content collection by slug.\n *\n * Thin wrapper over [`getCollection`]: inherits both resolution paths\n * (snapshot via `globalThis.__zfb.contentSnapshot` and the `node:fs`\n * fallback) for free. Returns `undefined` when either the collection does\n * not exist or no entry matches `slug`.\n *\n * **Runtime vs. generated types divergence.** The generated `types.d.ts`\n * emits a keyed overload (`K extends keyof ZfbCollections`) that ties the\n * return type to the collection's declared schema. That schema is enforced\n * by `zfb check`; this runtime form is intentionally structural — it does\n * not reference `ZfbCollections` and does not attempt to reconcile with the\n * keyed shape. (#857)\n *\n * @example\n * const post = getEntry<{ title: string }>(\"blog\", \"hello-zfb\");\n * if (!post) return null;\n * return <post.Content />;\n */\nexport function getEntry<T = Record<string, unknown>>(\n name: string,\n slug: string,\n): CollectionEntry<T> | undefined {\n return getCollection<T>(name).find((e) => e.slug === slug);\n}\n\n/**\n * Construct a [`CollectionEntry`] from a [`SnapshotEntry`]. The snapshot\n * carries `frontmatter` as a possibly-`null` JSON value (matches the\n * Rust contract for entries with no frontmatter); we normalise `null` /\n * `undefined` to an empty object so consumers' `.data.title` reads\n * never have to deal with `null`.\n *\n * **Type-safety note:** `T` is the caller-supplied frontmatter shape\n * but we do **not** validate it at runtime — if the page declares a\n * shape that the actual frontmatter doesn't match, the cast below\n * lies. Callers are expected to keep their `getCollection<MySchema>()`\n * generic in sync with the actual frontmatter; we acknowledge the\n * unsafety with the explicit `unknown` indirection rather than a\n * direct (and silently lossy) cast.\n */\nfunction entryFromSnapshot<T>(entry: SnapshotEntry): CollectionEntry<T> {\n const data =\n entry.frontmatter === null || entry.frontmatter === undefined\n ? ({} as T)\n : (entry.frontmatter as unknown as T);\n return {\n slug: entry.slug,\n data,\n body: entry.body,\n module_specifier: entry.module_specifier,\n Content: buildContentComponent(entry.module_specifier, entry.body),\n };\n}\n\n/**\n * Recursively collect every `*.md` file under `dir` (synchronous).\n *\n * BCI-6: replaces the old flat `readdir(dir).filter(n => n.endsWith(\".md\"))`\n * approach. Hidden files (names starting with `.`) and hidden directories\n * are skipped at every nesting level, matching the top-level behaviour of\n * the previous implementation.\n *\n * Returns absolute paths sorted lexicographically so the result order is\n * deterministic across platforms and Node versions.\n *\n * Synchronous to honour ADR-004 — see [`getCollection`].\n */\nfunction collectMdFilesSync(dir: string): string[] {\n const result: string[] = [];\n const { fs, path } = loadNodeModules();\n walkDirSync(fs, path, dir, result);\n result.sort();\n return result;\n}\n\nfunction walkDirSync(\n fs: typeof NodeFs,\n path: typeof NodePath,\n current: string,\n out: string[],\n): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name.startsWith(\".\")) continue;\n const fullPath = path.join(current, entry.name);\n // Skip symlinks to avoid infinite loops caused by cycles (e.g. a symlink\n // pointing at a parent directory). Content files are expected to be plain\n // regular files; following symlinks provides no value here.\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory()) {\n walkDirSync(fs, path, fullPath, out);\n } else if (entry.isFile() && entry.name.endsWith(\".md\")) {\n out.push(fullPath);\n }\n }\n}\n\n/**\n * @internal\n *\n * Convert a `path.relative()` result into a forward-slash-separated\n * slug with the trailing `.md` extension stripped.\n *\n * Slugs are URL-flavored identifiers, not filesystem paths — they\n * MUST use `/` regardless of the host OS so a nested entry like\n * `2024/hello.md` produces the slug `2024/hello` on both POSIX and\n * Windows. Without this normalisation, Windows callers would see\n * `2024\\hello`, which then leaks through to `module_specifier` and\n * any URL the consumer derives from the slug.\n *\n * Exported solely so the unit test suite can pin the Windows\n * behaviour without needing an actual Windows host. Do not depend on\n * this from application code — name and signature may change.\n */\nexport function _relPathToSlug(relPath: string): string {\n const { path } = loadNodeModules();\n const posix = path.sep === \"/\" ? relPath : relPath.split(path.sep).join(\"/\");\n // Some Node versions normalise `\\` even when sep is `/`, so be\n // defensive: collapse any straggling backslashes too.\n const normalised = posix.includes(\"\\\\\") ? posix.split(\"\\\\\").join(\"/\") : posix;\n return normalised.endsWith(\".md\") ? normalised.slice(0, -\".md\".length) : normalised;\n}\n\n// ---------------------------------------------------------------------------\n// `defaultComponents` — htmlOverrides convention\n//\n// Ported from zudo-doc's `src/components/content/component-map.ts`. Users opt\n// in by spreading the map into their own `components` prop:\n//\n// import { defaultComponents } from \"zfb\";\n// <entry.Content components={{ ...defaultComponents, h2: MyH2 }} />\n//\n// Each component is a thin passthrough mirroring its zudo-doc counterpart\n// (e.g. `ContentParagraph` → `<p {...rest}>{children}</p>`). v0 ships the\n// passthroughs unstyled; layering smart-break / heading-anchor / link-icon\n// behaviour on top is independent follow-up — keeping the v0 deliverable\n// focused on infrastructure (issue #33).\n//\n// **`h1` is deliberately not in the map** — page titles render `<h1>` from\n// frontmatter, per the zudo-doc convention. Adding `h1` here would silently\n// double-render the page title.\n//\n// **Each override is exported as a named const AND included in\n// `defaultComponents`** so consumers can tree-shake-import a single component\n// (`import { ContentLink } from \"zfb\"`) without dragging in the whole map.\n//\n// Implementation note: components return the structural JSX-element shape\n// directly — same pattern as `Island`. This keeps the package\n// JSX-runtime-agnostic so it works under either Preact or React without\n// importing a runtime. Both `jsx-runtime` implementations accept the\n// `{ type, props, key }` object on either side of the boundary.\n// ---------------------------------------------------------------------------\n\n/**\n * Public JSX-element shape returned by every override in [`defaultComponents`].\n *\n * Mirrors [`ContentElement`] and [`IslandElement`]: a structural alias for\n * `JSX.Element` so consumers can drop these overrides into both React and\n * Preact JSX without per-framework type setup.\n */\nexport type ContentComponentElement = {\n readonly type: string;\n readonly props: Readonly<Record<string, unknown>>;\n readonly key: unknown;\n};\n\n/**\n * Props accepted by every default override. `children` and any extra\n * attributes (`className`, `id`, `href`, …) are passed through verbatim\n * to the underlying HTML element.\n */\nexport interface ContentComponentProps {\n children?: VNode;\n [key: string]: unknown;\n}\n\n/** Internal helper: build a structural JSX element of the given tag. */\nfunction buildOverrideElement(tag: string, props: ContentComponentProps): ContentComponentElement {\n const { children, ...rest } = props;\n // Minted through the per-project JSX runtime (`mintElement`) so the\n // override is a real element under both React and Preact — see the\n // helper's docblock (zudo-doc#505; React error #31 rationale).\n return mintElement(tag, { ...rest, children }) as unknown as ContentComponentElement;\n}\n\n/**\n * `<h2>` passthrough override. Ported from zudo-doc's `HeadingH2`, stripped\n * of styling — v0 ships pass-through behaviour; visual treatment is layered\n * on by the consumer (or by a follow-up enhancement pass).\n */\nexport function ContentH2(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"h2\", props);\n}\n\n/** `<h3>` passthrough override. See [`ContentH2`] for the contract. */\nexport function ContentH3(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"h3\", props);\n}\n\n/** `<h4>` passthrough override. See [`ContentH2`] for the contract. */\nexport function ContentH4(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"h4\", props);\n}\n\n/** `<p>` passthrough override. Mirrors zudo-doc's `ContentParagraph`. */\nexport function ContentParagraph(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"p\", props);\n}\n\n/** `<a>` passthrough override. Mirrors zudo-doc's `ContentLink`. */\nexport function ContentLink(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"a\", props);\n}\n\n/** `<strong>` passthrough override. Mirrors zudo-doc's `ContentStrong`. */\nexport function ContentStrong(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"strong\", props);\n}\n\n/** `<blockquote>` passthrough override. Mirrors zudo-doc's `ContentBlockquote`. */\nexport function ContentBlockquote(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"blockquote\", props);\n}\n\n/** `<ul>` passthrough override. Mirrors zudo-doc's `ContentUl`. */\nexport function ContentUl(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"ul\", props);\n}\n\n/** `<ol>` passthrough override. Mirrors zudo-doc's `ContentOl`. */\nexport function ContentOl(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"ol\", props);\n}\n\n/** `<table>` passthrough override. Mirrors zudo-doc's `ContentTable`. */\nexport function ContentTable(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"table\", props);\n}\n\n/** `<code>` passthrough override. Mirrors zudo-doc's `ContentCode`. */\nexport function ContentCode(props: ContentComponentProps): ContentComponentElement {\n return buildOverrideElement(\"code\", props);\n}\n\n/**\n * Default per-element override map — eleven entries covering the markdown\n * tags the zudo-doc convention overrides (`h2`, `h3`, `h4`, `p`, `a`,\n * `strong`, `blockquote`, `ul`, `ol`, `table`, `code`).\n *\n * `h1` is intentionally absent: page titles render from frontmatter, per\n * the zudo-doc convention.\n *\n * Spread into a `components` prop to compose with custom overrides:\n *\n * ```tsx\n * import { defaultComponents } from \"zfb\";\n *\n * <entry.Content components={{ ...defaultComponents, h2: MyFancyH2 }} />\n * ```\n */\nexport const defaultComponents = {\n h2: ContentH2,\n h3: ContentH3,\n h4: ContentH4,\n p: ContentParagraph,\n a: ContentLink,\n strong: ContentStrong,\n blockquote: ContentBlockquote,\n ul: ContentUl,\n ol: ContentOl,\n table: ContentTable,\n code: ContentCode,\n} as const;\n\n/**\n * Merge component maps with the documented precedence order:\n * built-in `defaultComponents` → global slot (`globalThis.__zfb?.mdxComponents`)\n * → per-call `props.components`.\n *\n * Spread in stable key order so the resulting map is deterministic; later\n * entries in the spread win on collision (lowest → highest priority). Absent\n * layers (`undefined`) are no-ops via spread-of-undefined.\n *\n * **Output-neutral by design:** `defaultComponents` entries are pure\n * passthroughs (e.g. `ContentH2` → `<h2>{...props}</h2>`), so introducing\n * this merge into `buildContentComponent` does not change the rendered output.\n */\nexport function mergeMdxComponents(\n globalSlot: MdxComponents | undefined,\n perCall: MdxComponents | undefined,\n): MdxComponents {\n return { ...defaultComponents, ...globalSlot, ...perCall };\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { scheduleHydrate, mountIslands, mountNewIslands, cancelPendingIslands, u
|
|
|
3
3
|
export type { IslandManifest, IslandManifestValue } from "./runtime.js";
|
|
4
4
|
export type { VNode, VNodeArray, VNodeObject } from "./jsx-types.js";
|
|
5
5
|
export { DEFAULT_WHEN, isWhen, WHEN_VALUES, type When } from "./types.js";
|
|
6
|
-
export { definePlugin, type ZfbBuildHookContext, type ZfbDevMiddlewareContext, type ZfbDevMiddlewareHandler, type ZfbDevMiddlewareRequest, type ZfbDevMiddlewareResponse, type ZfbPlugin, type ZfbPluginLogger, } from "./plugins.js";
|
|
6
|
+
export { definePlugin, type ZfbBuildHookContext, type ZfbDevMiddlewareContext, type ZfbDevMiddlewareHandler, type ZfbDevMiddlewareRequest, type ZfbDevMiddlewareResponse, type ZfbPlugin, type ZfbPluginLogger, type ZfbPreviewMiddlewareContext, type ZfbPreviewMiddlewareHandler, } from "./plugins.js";
|
|
7
7
|
export { slugify, SlugAllocator } from "./slugify.js";
|
|
8
8
|
export { clientScript } from "./client-script.js";
|
|
9
9
|
export { ContentBlockquote, ContentCode, ContentH2, ContentH3, ContentH4, ContentLink, ContentOl, ContentParagraph, ContentStrong, ContentTable, ContentUl, defaultComponents, mergeMdxComponents, type ContentComponentElement, type ContentComponentProps, type MdxComponents, } from "./content.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,EAAE;AACF,iFAAiF;AACjF,uDAAuD;AACvD,gFAAgF;AAChF,uCAAuC;AAEvC,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,MAAM,EACN,oBAAoB,EACpB,WAAW,GAGZ,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,eAAe,EACf,YAAY,EACZ,eAAe,EACf,oBAAoB,EACpB,cAAc,GACf,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAAa,MAAM,YAAY,CAAC;AAE1E,yEAAyE;AACzE,iFAAiF;AACjF,oEAAoE;AACpE,+FAA+F;AAC/F,qCAAqC;AACrC,kEAAkE;AAClE,sEAAsE;AACtE,wEAAwE;AACxE,YAAY;AACZ,OAAO,EACL,YAAY,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,EAAE;AACF,iFAAiF;AACjF,uDAAuD;AACvD,gFAAgF;AAChF,uCAAuC;AAEvC,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,MAAM,EACN,oBAAoB,EACpB,WAAW,GAGZ,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,eAAe,EACf,YAAY,EACZ,eAAe,EACf,oBAAoB,EACpB,cAAc,GACf,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAAa,MAAM,YAAY,CAAC;AAE1E,yEAAyE;AACzE,iFAAiF;AACjF,oEAAoE;AACpE,+FAA+F;AAC/F,qCAAqC;AACrC,kEAAkE;AAClE,sEAAsE;AACtE,wEAAwE;AACxE,YAAY;AACZ,OAAO,EACL,YAAY,GAUb,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAEtD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EACL,iBAAiB,EACjB,WAAW,EACX,SAAS,EACT,SAAS,EACT,SAAS,EACT,WAAW,EACX,SAAS,EACT,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,SAAS,EACT,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,cAAc,CAAC","sourcesContent":["// Public entry point for the \"@takazudo/zfb\" package.\n//\n// User TSX pages reach this module via `import { Island } from \"@takazudo/zfb\"`.\n// The hydration runtime (Sub 3) reaches the helper via\n// `import { scheduleHydrate } from \"@takazudo/zfb/runtime\"` (or by inlining the\n// same logic; coordinated separately).\n\nexport {\n ANONYMOUS_COMPONENT_NAME,\n HYDRATE_MARKER_ATTR,\n Island,\n SKIP_SSR_MARKER_ATTR,\n resolveWhen,\n type IslandElement,\n type IslandProps,\n} from \"./island.js\";\nexport {\n scheduleHydrate,\n mountIslands,\n mountNewIslands,\n cancelPendingIslands,\n unmountIslands,\n} from \"./runtime.js\";\nexport type { IslandManifest, IslandManifestValue } from \"./runtime.js\";\nexport type { VNode, VNodeArray, VNodeObject } from \"./jsx-types.js\";\nexport { DEFAULT_WHEN, isWhen, WHEN_VALUES, type When } from \"./types.js\";\n\n// `defaultComponents` (htmlOverrides convention) is re-exported from the\n// root entry point so `import { defaultComponents } from \"@takazudo/zfb\"` is the\n// canonical access path. Each named override is also re-exported so\n// consumers can tree-shake-import a single one (`import { ContentLink } from \"@takazudo/zfb\"`)\n// without dragging in the whole map.\n// Plugin lifecycle types + `definePlugin` identity helper. Plugin\n// authors typically import these from \"@takazudo/zfb/plugins\" but the\n// root entry re-exports them so simple plugins can pull everything from\n// one path.\nexport {\n definePlugin,\n type ZfbBuildHookContext,\n type ZfbDevMiddlewareContext,\n type ZfbDevMiddlewareHandler,\n type ZfbDevMiddlewareRequest,\n type ZfbDevMiddlewareResponse,\n type ZfbPlugin,\n type ZfbPluginLogger,\n type ZfbPreviewMiddlewareContext,\n type ZfbPreviewMiddlewareHandler,\n} from \"./plugins.js\";\n\nexport { slugify, SlugAllocator } from \"./slugify.js\";\n\nexport { clientScript } from \"./client-script.js\";\n\nexport {\n ContentBlockquote,\n ContentCode,\n ContentH2,\n ContentH3,\n ContentH4,\n ContentLink,\n ContentOl,\n ContentParagraph,\n ContentStrong,\n ContentTable,\n ContentUl,\n defaultComponents,\n mergeMdxComponents,\n type ContentComponentElement,\n type ContentComponentProps,\n type MdxComponents,\n} from \"./content.js\";\n"]}
|
package/dist/plugins.d.ts
CHANGED
|
@@ -120,6 +120,38 @@ export type ZfbDevMiddlewareContext = {
|
|
|
120
120
|
/** Register an HTTP handler at `path`. Calling twice on the same path overwrites. */
|
|
121
121
|
register(path: string, handler: ZfbDevMiddlewareHandler): void;
|
|
122
122
|
};
|
|
123
|
+
/**
|
|
124
|
+
* Handler signature for a `previewMiddleware` registration (#1542).
|
|
125
|
+
* Deliberately reuses [`ZfbDevMiddlewareRequest`] /
|
|
126
|
+
* [`ZfbDevMiddlewareResponse`] verbatim — the wire shape crossing the
|
|
127
|
+
* Rust↔JS boundary is genuinely the SAME for dev and preview (mirrors
|
|
128
|
+
* the Rust side, which shares `DevRequest`/`DevResponse` between both
|
|
129
|
+
* hooks too), so there is nothing preview-specific to say about the
|
|
130
|
+
* request/response contract itself. `next` is likewise reserved for
|
|
131
|
+
* future composition; returning `undefined` signals "I did not handle
|
|
132
|
+
* this request" and the preview server falls through to its built-in
|
|
133
|
+
* routes (static-file serving, or the wrangler-backed adapter in
|
|
134
|
+
* adapter mode).
|
|
135
|
+
*/
|
|
136
|
+
export type ZfbPreviewMiddlewareHandler = (req: ZfbDevMiddlewareRequest) => Promise<ZfbDevMiddlewareResponse | undefined> | ZfbDevMiddlewareResponse | undefined;
|
|
137
|
+
/**
|
|
138
|
+
* Context passed to `previewMiddleware` (#1542). Structurally identical
|
|
139
|
+
* to [`ZfbDevMiddlewareContext`] today — one handler per URL path
|
|
140
|
+
* prefix, matched the same way — but declared as its own named type
|
|
141
|
+
* (unlike the request/response types above, which are reused verbatim)
|
|
142
|
+
* because the *context* is where a hook-specific capability would land
|
|
143
|
+
* first if one were ever added (e.g. something preview-only that
|
|
144
|
+
* `devMiddleware` has no equivalent for). Keeping it a separate
|
|
145
|
+
* declaration costs nothing today and avoids a breaking rename later.
|
|
146
|
+
*/
|
|
147
|
+
export type ZfbPreviewMiddlewareContext = {
|
|
148
|
+
projectRoot: string;
|
|
149
|
+
config: import("./config.js").ZfbConfig;
|
|
150
|
+
options: Record<string, unknown>;
|
|
151
|
+
logger: ZfbPluginLogger;
|
|
152
|
+
/** Register an HTTP handler at `path`. Calling twice on the same path overwrites. */
|
|
153
|
+
register(path: string, handler: ZfbPreviewMiddlewareHandler): void;
|
|
154
|
+
};
|
|
123
155
|
/**
|
|
124
156
|
* Loader signature for a virtual-module registration. Must return the
|
|
125
157
|
* **complete ESM module source text** as a string — the bundler /
|
|
@@ -167,11 +199,23 @@ export type ZfbVirtualModuleLoader = () => string | Promise<string>;
|
|
|
167
199
|
export type ZfbSetupContext = {
|
|
168
200
|
/**
|
|
169
201
|
* Active zfb command. `"build"` during `zfb build`; `"dev"` during
|
|
170
|
-
* `zfb dev
|
|
171
|
-
*
|
|
172
|
-
*
|
|
202
|
+
* `zfb dev`; `"preview"` during `zfb preview` (#1542). Affects
|
|
203
|
+
* `injectRoute`: in `"dev"`, `"/"` is reserved for the devMiddleware
|
|
204
|
+
* catch-all and is rejected; in `"build"`, a `"/"` package route is
|
|
205
|
+
* allowed (see [`injectRoute`](#injectRoute)).
|
|
206
|
+
*
|
|
207
|
+
* Under `"preview"`, `setup` still fires (Rust-side via the minimal
|
|
208
|
+
* non-V8 `run_preview_setup` path) so plugin-side state
|
|
209
|
+
* initialisation runs, but `zfb preview` serves an ALREADY-BUILT
|
|
210
|
+
* `dist/` verbatim and never re-enters the scan → bundle → render
|
|
211
|
+
* pipeline. Consequently `injectRoute` / `addVirtualModule` /
|
|
212
|
+
* `addAlias` / `addClientEntry` calls made under `"preview"` are
|
|
213
|
+
* accepted (for shape-consistency with `"build"`/`"dev"`) but are
|
|
214
|
+
* **inert** — nothing downstream ever reads them. Only the hook's
|
|
215
|
+
* side effects and a subsequent `previewMiddleware` registration do
|
|
216
|
+
* anything meaningful under `"preview"`.
|
|
173
217
|
*/
|
|
174
|
-
command: "build" | "dev";
|
|
218
|
+
command: "build" | "dev" | "preview";
|
|
175
219
|
/** Project root — the directory containing `zfb.config.ts`. */
|
|
176
220
|
projectRoot: string;
|
|
177
221
|
/** The full loaded `ZfbConfig` (data-only view). */
|
|
@@ -278,19 +322,31 @@ export type ZfbSetupContext = {
|
|
|
278
322
|
* specifier wins for identification on the Rust side) and helps the
|
|
279
323
|
* plugin self-identify in logs.
|
|
280
324
|
*
|
|
281
|
-
*
|
|
325
|
+
* Five optional hooks; declaration-order matters when multiple plugins
|
|
282
326
|
* touch the same surface. Each hook is independent — a plugin may
|
|
283
327
|
* declare any subset:
|
|
284
328
|
*
|
|
285
329
|
* - `setup` (#255) — register virtual modules, aliases, injected
|
|
286
|
-
* routes. Runs once at host boot, before `preBuild`.
|
|
330
|
+
* routes. Runs once at host boot, before `preBuild`. Also runs under
|
|
331
|
+
* `zfb preview` (#1542) via the minimal non-V8 `run_preview_setup`
|
|
332
|
+
* path — see [`ZfbSetupContext.command`](#command) for what is and
|
|
333
|
+
* isn't meaningful there.
|
|
287
334
|
* - `preBuild` — file-generation work that downstream stages will
|
|
288
|
-
* see. Runs once per `zfb build` and once per `zfb dev` boot.
|
|
335
|
+
* see. Runs once per `zfb build` and once per `zfb dev` boot. Does
|
|
336
|
+
* **NOT** fire under `zfb preview` (#1542) — preview serves an
|
|
337
|
+
* already-built `dist/` and never re-triggers file generation.
|
|
289
338
|
* - `postBuild` — finalisation work that runs after `dist/` has been
|
|
290
|
-
* written.
|
|
339
|
+
* written. Does not fire under `zfb preview` either, for the same
|
|
340
|
+
* reason as `preBuild`.
|
|
291
341
|
* - `devMiddleware` — register HTTP handlers for ad-hoc dev-only
|
|
292
342
|
* URLs. Per-request dispatch, distinct from `injectRoute` (which
|
|
293
|
-
* goes through the page renderer).
|
|
343
|
+
* goes through the page renderer). Fires only during `zfb dev`.
|
|
344
|
+
* - `previewMiddleware` (#1542) — register HTTP handlers for ad-hoc
|
|
345
|
+
* preview-only URLs. Same register-context shape as `devMiddleware`,
|
|
346
|
+
* fires only during `zfb preview`. A plugin wanting coverage in both
|
|
347
|
+
* modes registers the same handler under both hooks — `zfb` does
|
|
348
|
+
* NOT reuse a `devMiddleware` registration for preview automatically
|
|
349
|
+
* (explicit per-mode opt-in, by design).
|
|
294
350
|
*/
|
|
295
351
|
export type ZfbPlugin = {
|
|
296
352
|
/** Plugin display name; surfaces in error / log lines. */
|
|
@@ -299,6 +355,7 @@ export type ZfbPlugin = {
|
|
|
299
355
|
preBuild?(ctx: ZfbBuildHookContext): Promise<void> | void;
|
|
300
356
|
postBuild?(ctx: ZfbBuildHookContext): Promise<void> | void;
|
|
301
357
|
devMiddleware?(ctx: ZfbDevMiddlewareContext): Promise<void> | void;
|
|
358
|
+
previewMiddleware?(ctx: ZfbPreviewMiddlewareContext): Promise<void> | void;
|
|
302
359
|
};
|
|
303
360
|
/**
|
|
304
361
|
* Identity helper that types the supplied object as a [`ZfbPlugin`].
|
package/dist/plugins.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.js","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,0EAA0E;AAC1E,wEAAwE;AACxE,wEAAwE;AACxE,oEAAoE;AACpE,oEAAoE;AACpE,EAAE;AACF,uEAAuE;AACvE,sEAAsE;AACtE,qEAAqE;AACrE,sEAAsE;AACtE,sEAAsE;AACtE,6CAA6C;AAC7C,EAAE;AACF,wCAAwC;AACxC,EAAE;AACF,qEAAqE;AACrE,mEAAmE;AACnE,oEAAoE;AACpE,oEAAoE;AACpE,+BAA+B;AA+T/B;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,YAAY,CAAC,MAAiB;IAC5C,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// `zfb/plugins` — TypeScript helper for the zfb plugin lifecycle.\n//\n// A plugin is a JS module whose default export is a [`ZfbPlugin`] object.\n// `zfb.config.ts` references plugins by `name` (npm bare specifier or a\n// `./`-relative path); the zfb config loader resolves each `name` to an\n// absolute module specifier and the Rust-side plugin host loads the\n// module via dynamic `import()` and dispatches the lifecycle hooks.\n//\n// Sub 3 / issue #108 — initial drop. Three optional hooks: `preBuild`,\n// `postBuild`, `devMiddleware`. Astro-migration epic #253 / sub-issue\n// #255 adds a fourth: `setup`, which runs once before `preBuild` and\n// lets plugins register virtual modules, import aliases, and dev-only\n// injected routes. None of the hooks see real Node IPC objects across\n// the boundary; everything is JSON-friendly.\n//\n// ## Inline functions are NOT supported\n//\n// `PluginConfig` (in `./config.ts`) carries only data. A user cannot\n// inline a function in `zfb.config.ts` — the config goes through a\n// JSON round-trip and any function value would be silently dropped.\n// Plugins must live in their own module (npm package or local file)\n// and be referenced by `name`.\n\n/**\n * Logger handed to every plugin hook. The Rust side wraps `tracing` so\n * the same lines show up alongside the rest of the build's structured\n * logs. Hooks should prefer this over `console.log`.\n */\nexport type ZfbPluginLogger = {\n info(msg: string): void;\n warn(msg: string): void;\n error(msg: string): void;\n};\n\n/**\n * One emitted route in the `postBuild` route manifest (#262).\n * Present on `ctx.routes.routes` so a `postBuild` plugin can iterate\n * every URL the build produced (e.g. to write a `sitemap.xml`).\n */\nexport type ZfbRouteEntry = {\n /** Emitted URL path, e.g. `/`, `/blog/hello/`, `/sitemap.xml`. */\n url: string;\n /** Path under `outDir`, e.g. `index.html`, `blog/hello/index.html`, `sitemap.xml`. */\n output: string;\n /** File extension: `html`, `xml`, `rss`, `txt`, `json`, … */\n extension: string;\n /** Source page module relative to the project root, e.g. `pages/blog/[slug].tsx`. */\n source: string;\n /**\n * `true` when the page is prerendered to disk (default / SSG); `false`\n * when the page exports `prerender = false` and is served by the\n * runtime adapter (SSR — no on-disk artifact under `outDir`).\n *\n * Indexes that enumerate on-disk URLs (sitemap.xml, search-index.json,\n * etc.) should filter `r.prerender !== false` to avoid surfacing SSR\n * routes that have no static output.\n */\n prerender: boolean;\n /**\n * Bound route parameters. Absent for static routes.\n * Dynamic (`[slug]`) params are string scalars; catchall (`[...rest]`)\n * params are string arrays.\n */\n params?: Record<string, string | string[]>;\n};\n\n/**\n * The route manifest exposed on `ctx.routes` during a `postBuild` callback\n * (#262). Sorted by `url` for byte-stable output across runs.\n */\nexport type ZfbRouteManifest = {\n routes: ZfbRouteEntry[];\n};\n\n/**\n * Context passed to `preBuild` and `postBuild`. `outDir` is the\n * resolved absolute path of the configured `outDir` (default\n * `<projectRoot>/dist`). `projectRoot` is the directory containing\n * `zfb.config.ts`.\n *\n * `routes` is **only present on `postBuild`** calls; it is `undefined`\n * on `preBuild`. This is intentional: the route manifest is not\n * available until the build finishes writing `dist/` (#262).\n */\nexport type ZfbBuildHookContext = {\n /** Project root — the directory containing `zfb.config.ts`. */\n projectRoot: string;\n /** Resolved absolute path of the build output directory. */\n outDir: string;\n /** The full loaded `ZfbConfig` (data-only view). */\n config: import(\"./config.js\").ZfbConfig;\n /** Plugin-specific options block, copied verbatim from the matching `PluginConfig.options`. */\n options: Record<string, unknown>;\n /** Logger that wraps the Rust-side `tracing` subscriber. */\n logger: ZfbPluginLogger;\n /**\n * All routes emitted by this build, sorted by URL (#262).\n * Present only on `postBuild` calls; `undefined` on `preBuild`.\n */\n routes?: ZfbRouteManifest;\n};\n\n/**\n * A request handed to a `devMiddleware` handler. Subset of the Node\n * `http.IncomingMessage` surface intentionally — the dev server is\n * Rust-side `axum`, not Node, so we expose only what survives a JSON\n * envelope hop.\n */\nexport type ZfbDevMiddlewareRequest = {\n method: string;\n url: string;\n /** Lower-cased header names → first value. */\n headers: Record<string, string>;\n /** Raw request body; absent for GET/HEAD. UTF-8 only — binary is out of scope for v1 dev plugins. */\n body?: string;\n};\n\n/**\n * Response returned by a `devMiddleware` handler. All fields optional\n * except `status`. `body` may be a string (UTF-8) or a base64-encoded\n * binary payload (set `bodyEncoding` to `\"base64\"` in that case).\n */\nexport type ZfbDevMiddlewareResponse = {\n status: number;\n headers?: Record<string, string>;\n body?: string;\n bodyEncoding?: \"utf8\" | \"base64\";\n};\n\n/**\n * Handler signature for a `devMiddleware` registration. The `next` callback\n * is reserved for future composition; v1 plugins should produce a response\n * directly. Returning `undefined` from the handler signals \"I did not handle\n * this request\" — the dev server then falls through to its built-in routes\n * (the page cache, /__zfb/livereload.js, etc.).\n */\nexport type ZfbDevMiddlewareHandler = (\n req: ZfbDevMiddlewareRequest,\n) => Promise<ZfbDevMiddlewareResponse | undefined> | ZfbDevMiddlewareResponse | undefined;\n\n/**\n * Context passed to `devMiddleware`. The `register` callback installs\n * one handler per URL path prefix. `path` is matched as an exact prefix\n * — a registration on `/doc-history` matches `/doc-history` and\n * `/doc-history/foo`, but NOT `/doc-historyx`.\n */\nexport type ZfbDevMiddlewareContext = {\n projectRoot: string;\n config: import(\"./config.js\").ZfbConfig;\n options: Record<string, unknown>;\n logger: ZfbPluginLogger;\n /** Register an HTTP handler at `path`. Calling twice on the same path overwrites. */\n register(path: string, handler: ZfbDevMiddlewareHandler): void;\n};\n\n/**\n * Loader signature for a virtual-module registration. Must return the\n * **complete ESM module source text** as a string — the bundler /\n * embedded V8 host feeds the returned string in as the module's\n * source verbatim. The loader is invoked **exactly once per build**\n * (and once per `zfb dev` host boot) the first time any consumer\n * imports the registered specifier; subsequent imports of the same\n * specifier re-use the memoised result.\n *\n * Example:\n *\n * ```ts\n * addVirtualModule(\"virtual:my-data\", () =>\n * `export default ${JSON.stringify(myJson)}`,\n * );\n * ```\n */\nexport type ZfbVirtualModuleLoader = () => string | Promise<string>;\n\n/**\n * Context passed to the new `setup` hook (#255). Runs once per host\n * boot, in `Config.plugins` declaration order, **before** `preBuild`.\n *\n * `ctx.command` tells the plugin which lifecycle is active so it can\n * gate per-lifecycle registrations. A dev-only mock route stays gated\n * to `\"dev\"`; a package-owned page route is registered unconditionally\n * (it is prerendered during a build and dev-routed during dev):\n *\n * ```ts\n * setup({ command, injectRoute }) {\n * // package-owned page route (prerendered at BUILD; see injectRoute for\n * // the dev caveat)\n * injectRoute(\"/preset-page\", \"./pages/preset-page.tsx\");\n * // dev-only mock endpoint\n * if (command === \"dev\") {\n * injectRoute(\"/api/dev/x\", \"./scripts/dev-x.ts\");\n * }\n * }\n * ```\n *\n * The hook's surface is intentionally **closed**: only `injectRoute`,\n * `addVirtualModule`, `addAlias`, and `addClientEntry`. There is no\n * `addRemarkPlugin` / `addRehypePlugin` / `addMarkdownVisitor` — by\n * design (see the concept doc for the rationale).\n */\nexport type ZfbSetupContext = {\n /**\n * Active zfb command. `\"build\"` during `zfb build`; `\"dev\"` during\n * `zfb dev`. Affects `injectRoute`: in `\"dev\"`, `\"/\"` is reserved for\n * the devMiddleware catch-all and is rejected; in `\"build\"`, a `\"/\"`\n * package route is allowed (see [`injectRoute`](#injectRoute)).\n */\n command: \"build\" | \"dev\";\n /** Project root — the directory containing `zfb.config.ts`. */\n projectRoot: string;\n /** The full loaded `ZfbConfig` (data-only view). */\n config: import(\"./config.js\").ZfbConfig;\n /** Plugin-specific options block, copied verbatim from `PluginConfig.options`. */\n options: Record<string, unknown>;\n /** Logger that wraps the Rust-side `tracing` subscriber. */\n logger: ZfbPluginLogger;\n\n /**\n * Register an import alias. **Exact-match-only in v1**:\n * `addAlias(\"@/foo\", \"./src/foo.tsx\")` rewrites `import \"@/foo\"`\n * but does NOT match `import \"@/foo/bar\"`. Prefix-matching is\n * explicitly deferred to v2 — switch to one bare alias per file\n * until then.\n *\n * `to` is resolved relative to the project root. Two plugins\n * registering the same `from` with different `to` raises\n * `AliasConflict` and aborts the build.\n */\n addAlias(from: string, to: string): void;\n\n /**\n * Register a virtual module. `specifier` is a bare import\n * specifier (recommended `virtual:` prefix, not enforced).\n * `loader` returns the complete ESM source text as a string and\n * runs **exactly once per build** at first import.\n *\n * Two plugins registering the same `specifier` raises\n * `VirtualModuleConflict` and aborts the build.\n */\n addVirtualModule(specifier: string, loader: ZfbVirtualModuleLoader): void;\n\n /**\n * Register a synthetic / package-owned page route. `pattern` uses the\n * same grammar as `pages/` filenames (`/blog/[slug]`, `/api/dev/x`,\n * `/docs/[...rest]`).\n *\n * - In **build** (package-owned routes), the route is materialised\n * into a per-build overlay pages root and **prerendered** through\n * the normal scan → bundle → render pipeline, so a preset can own a\n * route without the project shipping a `pages/` stub file. A `\"/\"`\n * package route is allowed (it becomes the project's root page,\n * enabling a truly empty/absent user `pages/`). A package route\n * whose URL shape collides with a user `pages/` route is dropped\n * (user `pages/` wins). This is the supported, complete path.\n * - In **dev**, both static and dynamic injected routes are rendered\n * by `zfb dev`. Static routes (where the URL equals the pattern,\n * e.g. `/preset-about`) are seeded into the dev route universe at\n * boot; dynamic routes (e.g. `/preset-docs/[slug]`) are rendered\n * on first request via a request-time synthetic entry — params are\n * extracted from the URL by the Hono router inside the live bundle.\n * User `pages/` files take precedence over any injected route of\n * the same shape (including the dev-only `\"/\"` reservation, which\n * is still rejected at registration in dev). **HMR:** content the\n * route reads from watched collections live-refreshes normally.\n * Editing the package's **compiled entrypoint under `node_modules`**\n * is NOT watched and requires a `zfb dev` restart (restart-only\n * contract — a published package is not project source). **Per-route\n * data:** an injected route loads per-route data via a **dynamic\n * route's `paths()` export** (which returns `{ params, props }`);\n * `getStaticProps` on a package page is not forwarded by the overlay\n * (only `default` + the `prerender` hint are forwarded — same as\n * `zfb build`). A route that needs per-route data should be a\n * dynamic route whose `paths()` reads the data.\n *\n * `opts.prerender` controls the route's prerender shape during a\n * build: omit it (or `true`) for the SSG default; `false` marks an\n * SSR-shaped route, which `output: 'static'` rejects. It is build-only\n * metadata and ignored in dev.\n *\n * Two plugins registering the same `pattern` (or one plugin\n * re-registering it with a different entrypoint) raises\n * `InjectRouteConflict`.\n */\n injectRoute(pattern: string, entrypoint: string, opts?: { prerender?: boolean }): void;\n\n /**\n * Register a package-owned client-side side-effect entry (#1196).\n *\n * `entrypoint` **must** point to a `*.client.{ts,tsx,js,jsx}` file —\n * this is enforced (#1191 review [9]): a path missing the `.client.`\n * infix, or a bare `.client.ts` with an empty stem, throws an error\n * (`addClientEntry` JS-host validation + Rust `InvalidClientEntry`)\n * rather than being silently accepted under an invented name. The entry\n * name is derived from the filename stem minus `.client`\n * (e.g. `my-lib.client.ts` → `my-lib`), via the same canonical helper\n * as user-authored `*.client.*` discovery.\n *\n * The entry is bundled and shipped as\n * `/assets/client/<name>.js` (stable URL) / `/assets/client/<name>-<hash>.js`\n * (production, hashed). User-authored files win on name collision —\n * the registered entry is silently dropped when a user-authored file of\n * the same name exists in the discovery roots.\n *\n * Two plugins registering the same entry name with different entrypoints\n * raises `ClientEntryConflict` and aborts the build.\n *\n * `entrypoint` is resolved relative to the project root if given as a\n * relative path (same rule as `injectRoute`).\n */\n addClientEntry(entrypoint: string): void;\n};\n\n/**\n * The plugin-module shape. `name` is informational (the resolved module\n * specifier wins for identification on the Rust side) and helps the\n * plugin self-identify in logs.\n *\n * Four optional hooks; declaration-order matters when multiple plugins\n * touch the same surface. Each hook is independent — a plugin may\n * declare any subset:\n *\n * - `setup` (#255) — register virtual modules, aliases, injected\n * routes. Runs once at host boot, before `preBuild`.\n * - `preBuild` — file-generation work that downstream stages will\n * see. Runs once per `zfb build` and once per `zfb dev` boot.\n * - `postBuild` — finalisation work that runs after `dist/` has been\n * written.\n * - `devMiddleware` — register HTTP handlers for ad-hoc dev-only\n * URLs. Per-request dispatch, distinct from `injectRoute` (which\n * goes through the page renderer).\n */\nexport type ZfbPlugin = {\n /** Plugin display name; surfaces in error / log lines. */\n name: string;\n setup?(ctx: ZfbSetupContext): Promise<void> | void;\n preBuild?(ctx: ZfbBuildHookContext): Promise<void> | void;\n postBuild?(ctx: ZfbBuildHookContext): Promise<void> | void;\n devMiddleware?(ctx: ZfbDevMiddlewareContext): Promise<void> | void;\n};\n\n/**\n * Identity helper that types the supplied object as a [`ZfbPlugin`].\n * Use as the default export of a plugin module so editors surface\n * field-level types and typos surface at compile time.\n *\n * ```ts\n * import { definePlugin } from \"@takazudo/zfb/plugins\";\n *\n * export default definePlugin({\n * name: \"my-plugin\",\n * async preBuild({ outDir, logger }) {\n * logger.info(`generating index into ${outDir}`);\n * },\n * });\n * ```\n */\nexport function definePlugin(plugin: ZfbPlugin): ZfbPlugin {\n return plugin;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"plugins.js","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,0EAA0E;AAC1E,wEAAwE;AACxE,wEAAwE;AACxE,oEAAoE;AACpE,oEAAoE;AACpE,EAAE;AACF,uEAAuE;AACvE,sEAAsE;AACtE,qEAAqE;AACrE,sEAAsE;AACtE,sEAAsE;AACtE,6CAA6C;AAC7C,EAAE;AACF,wCAAwC;AACxC,EAAE;AACF,qEAAqE;AACrE,mEAAmE;AACnE,oEAAoE;AACpE,oEAAoE;AACpE,+BAA+B;AA4X/B;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,YAAY,CAAC,MAAiB;IAC5C,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// `zfb/plugins` — TypeScript helper for the zfb plugin lifecycle.\n//\n// A plugin is a JS module whose default export is a [`ZfbPlugin`] object.\n// `zfb.config.ts` references plugins by `name` (npm bare specifier or a\n// `./`-relative path); the zfb config loader resolves each `name` to an\n// absolute module specifier and the Rust-side plugin host loads the\n// module via dynamic `import()` and dispatches the lifecycle hooks.\n//\n// Sub 3 / issue #108 — initial drop. Three optional hooks: `preBuild`,\n// `postBuild`, `devMiddleware`. Astro-migration epic #253 / sub-issue\n// #255 adds a fourth: `setup`, which runs once before `preBuild` and\n// lets plugins register virtual modules, import aliases, and dev-only\n// injected routes. None of the hooks see real Node IPC objects across\n// the boundary; everything is JSON-friendly.\n//\n// ## Inline functions are NOT supported\n//\n// `PluginConfig` (in `./config.ts`) carries only data. A user cannot\n// inline a function in `zfb.config.ts` — the config goes through a\n// JSON round-trip and any function value would be silently dropped.\n// Plugins must live in their own module (npm package or local file)\n// and be referenced by `name`.\n\n/**\n * Logger handed to every plugin hook. The Rust side wraps `tracing` so\n * the same lines show up alongside the rest of the build's structured\n * logs. Hooks should prefer this over `console.log`.\n */\nexport type ZfbPluginLogger = {\n info(msg: string): void;\n warn(msg: string): void;\n error(msg: string): void;\n};\n\n/**\n * One emitted route in the `postBuild` route manifest (#262).\n * Present on `ctx.routes.routes` so a `postBuild` plugin can iterate\n * every URL the build produced (e.g. to write a `sitemap.xml`).\n */\nexport type ZfbRouteEntry = {\n /** Emitted URL path, e.g. `/`, `/blog/hello/`, `/sitemap.xml`. */\n url: string;\n /** Path under `outDir`, e.g. `index.html`, `blog/hello/index.html`, `sitemap.xml`. */\n output: string;\n /** File extension: `html`, `xml`, `rss`, `txt`, `json`, … */\n extension: string;\n /** Source page module relative to the project root, e.g. `pages/blog/[slug].tsx`. */\n source: string;\n /**\n * `true` when the page is prerendered to disk (default / SSG); `false`\n * when the page exports `prerender = false` and is served by the\n * runtime adapter (SSR — no on-disk artifact under `outDir`).\n *\n * Indexes that enumerate on-disk URLs (sitemap.xml, search-index.json,\n * etc.) should filter `r.prerender !== false` to avoid surfacing SSR\n * routes that have no static output.\n */\n prerender: boolean;\n /**\n * Bound route parameters. Absent for static routes.\n * Dynamic (`[slug]`) params are string scalars; catchall (`[...rest]`)\n * params are string arrays.\n */\n params?: Record<string, string | string[]>;\n};\n\n/**\n * The route manifest exposed on `ctx.routes` during a `postBuild` callback\n * (#262). Sorted by `url` for byte-stable output across runs.\n */\nexport type ZfbRouteManifest = {\n routes: ZfbRouteEntry[];\n};\n\n/**\n * Context passed to `preBuild` and `postBuild`. `outDir` is the\n * resolved absolute path of the configured `outDir` (default\n * `<projectRoot>/dist`). `projectRoot` is the directory containing\n * `zfb.config.ts`.\n *\n * `routes` is **only present on `postBuild`** calls; it is `undefined`\n * on `preBuild`. This is intentional: the route manifest is not\n * available until the build finishes writing `dist/` (#262).\n */\nexport type ZfbBuildHookContext = {\n /** Project root — the directory containing `zfb.config.ts`. */\n projectRoot: string;\n /** Resolved absolute path of the build output directory. */\n outDir: string;\n /** The full loaded `ZfbConfig` (data-only view). */\n config: import(\"./config.js\").ZfbConfig;\n /** Plugin-specific options block, copied verbatim from the matching `PluginConfig.options`. */\n options: Record<string, unknown>;\n /** Logger that wraps the Rust-side `tracing` subscriber. */\n logger: ZfbPluginLogger;\n /**\n * All routes emitted by this build, sorted by URL (#262).\n * Present only on `postBuild` calls; `undefined` on `preBuild`.\n */\n routes?: ZfbRouteManifest;\n};\n\n/**\n * A request handed to a `devMiddleware` handler. Subset of the Node\n * `http.IncomingMessage` surface intentionally — the dev server is\n * Rust-side `axum`, not Node, so we expose only what survives a JSON\n * envelope hop.\n */\nexport type ZfbDevMiddlewareRequest = {\n method: string;\n url: string;\n /** Lower-cased header names → first value. */\n headers: Record<string, string>;\n /** Raw request body; absent for GET/HEAD. UTF-8 only — binary is out of scope for v1 dev plugins. */\n body?: string;\n};\n\n/**\n * Response returned by a `devMiddleware` handler. All fields optional\n * except `status`. `body` may be a string (UTF-8) or a base64-encoded\n * binary payload (set `bodyEncoding` to `\"base64\"` in that case).\n */\nexport type ZfbDevMiddlewareResponse = {\n status: number;\n headers?: Record<string, string>;\n body?: string;\n bodyEncoding?: \"utf8\" | \"base64\";\n};\n\n/**\n * Handler signature for a `devMiddleware` registration. The `next` callback\n * is reserved for future composition; v1 plugins should produce a response\n * directly. Returning `undefined` from the handler signals \"I did not handle\n * this request\" — the dev server then falls through to its built-in routes\n * (the page cache, /__zfb/livereload.js, etc.).\n */\nexport type ZfbDevMiddlewareHandler = (\n req: ZfbDevMiddlewareRequest,\n) => Promise<ZfbDevMiddlewareResponse | undefined> | ZfbDevMiddlewareResponse | undefined;\n\n/**\n * Context passed to `devMiddleware`. The `register` callback installs\n * one handler per URL path prefix. `path` is matched as an exact prefix\n * — a registration on `/doc-history` matches `/doc-history` and\n * `/doc-history/foo`, but NOT `/doc-historyx`.\n */\nexport type ZfbDevMiddlewareContext = {\n projectRoot: string;\n config: import(\"./config.js\").ZfbConfig;\n options: Record<string, unknown>;\n logger: ZfbPluginLogger;\n /** Register an HTTP handler at `path`. Calling twice on the same path overwrites. */\n register(path: string, handler: ZfbDevMiddlewareHandler): void;\n};\n\n/**\n * Handler signature for a `previewMiddleware` registration (#1542).\n * Deliberately reuses [`ZfbDevMiddlewareRequest`] /\n * [`ZfbDevMiddlewareResponse`] verbatim — the wire shape crossing the\n * Rust↔JS boundary is genuinely the SAME for dev and preview (mirrors\n * the Rust side, which shares `DevRequest`/`DevResponse` between both\n * hooks too), so there is nothing preview-specific to say about the\n * request/response contract itself. `next` is likewise reserved for\n * future composition; returning `undefined` signals \"I did not handle\n * this request\" and the preview server falls through to its built-in\n * routes (static-file serving, or the wrangler-backed adapter in\n * adapter mode).\n */\nexport type ZfbPreviewMiddlewareHandler = (\n req: ZfbDevMiddlewareRequest,\n) => Promise<ZfbDevMiddlewareResponse | undefined> | ZfbDevMiddlewareResponse | undefined;\n\n/**\n * Context passed to `previewMiddleware` (#1542). Structurally identical\n * to [`ZfbDevMiddlewareContext`] today — one handler per URL path\n * prefix, matched the same way — but declared as its own named type\n * (unlike the request/response types above, which are reused verbatim)\n * because the *context* is where a hook-specific capability would land\n * first if one were ever added (e.g. something preview-only that\n * `devMiddleware` has no equivalent for). Keeping it a separate\n * declaration costs nothing today and avoids a breaking rename later.\n */\nexport type ZfbPreviewMiddlewareContext = {\n projectRoot: string;\n config: import(\"./config.js\").ZfbConfig;\n options: Record<string, unknown>;\n logger: ZfbPluginLogger;\n /** Register an HTTP handler at `path`. Calling twice on the same path overwrites. */\n register(path: string, handler: ZfbPreviewMiddlewareHandler): void;\n};\n\n/**\n * Loader signature for a virtual-module registration. Must return the\n * **complete ESM module source text** as a string — the bundler /\n * embedded V8 host feeds the returned string in as the module's\n * source verbatim. The loader is invoked **exactly once per build**\n * (and once per `zfb dev` host boot) the first time any consumer\n * imports the registered specifier; subsequent imports of the same\n * specifier re-use the memoised result.\n *\n * Example:\n *\n * ```ts\n * addVirtualModule(\"virtual:my-data\", () =>\n * `export default ${JSON.stringify(myJson)}`,\n * );\n * ```\n */\nexport type ZfbVirtualModuleLoader = () => string | Promise<string>;\n\n/**\n * Context passed to the new `setup` hook (#255). Runs once per host\n * boot, in `Config.plugins` declaration order, **before** `preBuild`.\n *\n * `ctx.command` tells the plugin which lifecycle is active so it can\n * gate per-lifecycle registrations. A dev-only mock route stays gated\n * to `\"dev\"`; a package-owned page route is registered unconditionally\n * (it is prerendered during a build and dev-routed during dev):\n *\n * ```ts\n * setup({ command, injectRoute }) {\n * // package-owned page route (prerendered at BUILD; see injectRoute for\n * // the dev caveat)\n * injectRoute(\"/preset-page\", \"./pages/preset-page.tsx\");\n * // dev-only mock endpoint\n * if (command === \"dev\") {\n * injectRoute(\"/api/dev/x\", \"./scripts/dev-x.ts\");\n * }\n * }\n * ```\n *\n * The hook's surface is intentionally **closed**: only `injectRoute`,\n * `addVirtualModule`, `addAlias`, and `addClientEntry`. There is no\n * `addRemarkPlugin` / `addRehypePlugin` / `addMarkdownVisitor` — by\n * design (see the concept doc for the rationale).\n */\nexport type ZfbSetupContext = {\n /**\n * Active zfb command. `\"build\"` during `zfb build`; `\"dev\"` during\n * `zfb dev`; `\"preview\"` during `zfb preview` (#1542). Affects\n * `injectRoute`: in `\"dev\"`, `\"/\"` is reserved for the devMiddleware\n * catch-all and is rejected; in `\"build\"`, a `\"/\"` package route is\n * allowed (see [`injectRoute`](#injectRoute)).\n *\n * Under `\"preview\"`, `setup` still fires (Rust-side via the minimal\n * non-V8 `run_preview_setup` path) so plugin-side state\n * initialisation runs, but `zfb preview` serves an ALREADY-BUILT\n * `dist/` verbatim and never re-enters the scan → bundle → render\n * pipeline. Consequently `injectRoute` / `addVirtualModule` /\n * `addAlias` / `addClientEntry` calls made under `\"preview\"` are\n * accepted (for shape-consistency with `\"build\"`/`\"dev\"`) but are\n * **inert** — nothing downstream ever reads them. Only the hook's\n * side effects and a subsequent `previewMiddleware` registration do\n * anything meaningful under `\"preview\"`.\n */\n command: \"build\" | \"dev\" | \"preview\";\n /** Project root — the directory containing `zfb.config.ts`. */\n projectRoot: string;\n /** The full loaded `ZfbConfig` (data-only view). */\n config: import(\"./config.js\").ZfbConfig;\n /** Plugin-specific options block, copied verbatim from `PluginConfig.options`. */\n options: Record<string, unknown>;\n /** Logger that wraps the Rust-side `tracing` subscriber. */\n logger: ZfbPluginLogger;\n\n /**\n * Register an import alias. **Exact-match-only in v1**:\n * `addAlias(\"@/foo\", \"./src/foo.tsx\")` rewrites `import \"@/foo\"`\n * but does NOT match `import \"@/foo/bar\"`. Prefix-matching is\n * explicitly deferred to v2 — switch to one bare alias per file\n * until then.\n *\n * `to` is resolved relative to the project root. Two plugins\n * registering the same `from` with different `to` raises\n * `AliasConflict` and aborts the build.\n */\n addAlias(from: string, to: string): void;\n\n /**\n * Register a virtual module. `specifier` is a bare import\n * specifier (recommended `virtual:` prefix, not enforced).\n * `loader` returns the complete ESM source text as a string and\n * runs **exactly once per build** at first import.\n *\n * Two plugins registering the same `specifier` raises\n * `VirtualModuleConflict` and aborts the build.\n */\n addVirtualModule(specifier: string, loader: ZfbVirtualModuleLoader): void;\n\n /**\n * Register a synthetic / package-owned page route. `pattern` uses the\n * same grammar as `pages/` filenames (`/blog/[slug]`, `/api/dev/x`,\n * `/docs/[...rest]`).\n *\n * - In **build** (package-owned routes), the route is materialised\n * into a per-build overlay pages root and **prerendered** through\n * the normal scan → bundle → render pipeline, so a preset can own a\n * route without the project shipping a `pages/` stub file. A `\"/\"`\n * package route is allowed (it becomes the project's root page,\n * enabling a truly empty/absent user `pages/`). A package route\n * whose URL shape collides with a user `pages/` route is dropped\n * (user `pages/` wins). This is the supported, complete path.\n * - In **dev**, both static and dynamic injected routes are rendered\n * by `zfb dev`. Static routes (where the URL equals the pattern,\n * e.g. `/preset-about`) are seeded into the dev route universe at\n * boot; dynamic routes (e.g. `/preset-docs/[slug]`) are rendered\n * on first request via a request-time synthetic entry — params are\n * extracted from the URL by the Hono router inside the live bundle.\n * User `pages/` files take precedence over any injected route of\n * the same shape (including the dev-only `\"/\"` reservation, which\n * is still rejected at registration in dev). **HMR:** content the\n * route reads from watched collections live-refreshes normally.\n * Editing the package's **compiled entrypoint under `node_modules`**\n * is NOT watched and requires a `zfb dev` restart (restart-only\n * contract — a published package is not project source). **Per-route\n * data:** an injected route loads per-route data via a **dynamic\n * route's `paths()` export** (which returns `{ params, props }`);\n * `getStaticProps` on a package page is not forwarded by the overlay\n * (only `default` + the `prerender` hint are forwarded — same as\n * `zfb build`). A route that needs per-route data should be a\n * dynamic route whose `paths()` reads the data.\n *\n * `opts.prerender` controls the route's prerender shape during a\n * build: omit it (or `true`) for the SSG default; `false` marks an\n * SSR-shaped route, which `output: 'static'` rejects. It is build-only\n * metadata and ignored in dev.\n *\n * Two plugins registering the same `pattern` (or one plugin\n * re-registering it with a different entrypoint) raises\n * `InjectRouteConflict`.\n */\n injectRoute(pattern: string, entrypoint: string, opts?: { prerender?: boolean }): void;\n\n /**\n * Register a package-owned client-side side-effect entry (#1196).\n *\n * `entrypoint` **must** point to a `*.client.{ts,tsx,js,jsx}` file —\n * this is enforced (#1191 review [9]): a path missing the `.client.`\n * infix, or a bare `.client.ts` with an empty stem, throws an error\n * (`addClientEntry` JS-host validation + Rust `InvalidClientEntry`)\n * rather than being silently accepted under an invented name. The entry\n * name is derived from the filename stem minus `.client`\n * (e.g. `my-lib.client.ts` → `my-lib`), via the same canonical helper\n * as user-authored `*.client.*` discovery.\n *\n * The entry is bundled and shipped as\n * `/assets/client/<name>.js` (stable URL) / `/assets/client/<name>-<hash>.js`\n * (production, hashed). User-authored files win on name collision —\n * the registered entry is silently dropped when a user-authored file of\n * the same name exists in the discovery roots.\n *\n * Two plugins registering the same entry name with different entrypoints\n * raises `ClientEntryConflict` and aborts the build.\n *\n * `entrypoint` is resolved relative to the project root if given as a\n * relative path (same rule as `injectRoute`).\n */\n addClientEntry(entrypoint: string): void;\n};\n\n/**\n * The plugin-module shape. `name` is informational (the resolved module\n * specifier wins for identification on the Rust side) and helps the\n * plugin self-identify in logs.\n *\n * Five optional hooks; declaration-order matters when multiple plugins\n * touch the same surface. Each hook is independent — a plugin may\n * declare any subset:\n *\n * - `setup` (#255) — register virtual modules, aliases, injected\n * routes. Runs once at host boot, before `preBuild`. Also runs under\n * `zfb preview` (#1542) via the minimal non-V8 `run_preview_setup`\n * path — see [`ZfbSetupContext.command`](#command) for what is and\n * isn't meaningful there.\n * - `preBuild` — file-generation work that downstream stages will\n * see. Runs once per `zfb build` and once per `zfb dev` boot. Does\n * **NOT** fire under `zfb preview` (#1542) — preview serves an\n * already-built `dist/` and never re-triggers file generation.\n * - `postBuild` — finalisation work that runs after `dist/` has been\n * written. Does not fire under `zfb preview` either, for the same\n * reason as `preBuild`.\n * - `devMiddleware` — register HTTP handlers for ad-hoc dev-only\n * URLs. Per-request dispatch, distinct from `injectRoute` (which\n * goes through the page renderer). Fires only during `zfb dev`.\n * - `previewMiddleware` (#1542) — register HTTP handlers for ad-hoc\n * preview-only URLs. Same register-context shape as `devMiddleware`,\n * fires only during `zfb preview`. A plugin wanting coverage in both\n * modes registers the same handler under both hooks — `zfb` does\n * NOT reuse a `devMiddleware` registration for preview automatically\n * (explicit per-mode opt-in, by design).\n */\nexport type ZfbPlugin = {\n /** Plugin display name; surfaces in error / log lines. */\n name: string;\n setup?(ctx: ZfbSetupContext): Promise<void> | void;\n preBuild?(ctx: ZfbBuildHookContext): Promise<void> | void;\n postBuild?(ctx: ZfbBuildHookContext): Promise<void> | void;\n devMiddleware?(ctx: ZfbDevMiddlewareContext): Promise<void> | void;\n previewMiddleware?(ctx: ZfbPreviewMiddlewareContext): Promise<void> | void;\n};\n\n/**\n * Identity helper that types the supplied object as a [`ZfbPlugin`].\n * Use as the default export of a plugin module so editors surface\n * field-level types and typos surface at compile time.\n *\n * ```ts\n * import { definePlugin } from \"@takazudo/zfb/plugins\";\n *\n * export default definePlugin({\n * name: \"my-plugin\",\n * async preBuild({ outDir, logger }) {\n * logger.info(`generating index into ${outDir}`);\n * },\n * });\n * ```\n */\nexport function definePlugin(plugin: ZfbPlugin): ZfbPlugin {\n return plugin;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@takazudo/zfb",
|
|
3
|
-
"version": "0.1.0-next.
|
|
3
|
+
"version": "0.1.0-next.79",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Rust-built static-site engine for Astro and Next.js users — millisecond rebuilds, single binary. SDK with islands, content collections, pagination, and config helpers.",
|
|
@@ -74,11 +74,11 @@
|
|
|
74
74
|
"LICENSE"
|
|
75
75
|
],
|
|
76
76
|
"optionalDependencies": {
|
|
77
|
-
"@takazudo/zfb-darwin-arm64": "0.1.0-next.
|
|
78
|
-
"@takazudo/zfb-darwin-x64": "0.1.0-next.
|
|
79
|
-
"@takazudo/zfb-linux-arm64-gnu": "0.1.0-next.
|
|
80
|
-
"@takazudo/zfb-linux-x64-gnu": "0.1.0-next.
|
|
81
|
-
"@takazudo/zfb-win32-x64-msvc": "0.1.0-next.
|
|
77
|
+
"@takazudo/zfb-darwin-arm64": "0.1.0-next.79",
|
|
78
|
+
"@takazudo/zfb-darwin-x64": "0.1.0-next.79",
|
|
79
|
+
"@takazudo/zfb-linux-arm64-gnu": "0.1.0-next.79",
|
|
80
|
+
"@takazudo/zfb-linux-x64-gnu": "0.1.0-next.79",
|
|
81
|
+
"@takazudo/zfb-win32-x64-msvc": "0.1.0-next.79"
|
|
82
82
|
},
|
|
83
83
|
"publishConfig": {
|
|
84
84
|
"access": "public"
|