@anvil-di/anvil-unplugin 0.0.2

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/src/index.ts ADDED
@@ -0,0 +1,468 @@
1
+ /**
2
+ * `@anvil-di/anvil-unplugin` — runs anvil's Rust codegen as part of any bundler's
3
+ * pipeline. One adapter; every bundler (Vite, Rollup, Webpack, Rspack,
4
+ * esbuild) via [unplugin](https://github.com/unjs/unplugin).
5
+ *
6
+ * The plugin invokes the `anvil` CLI binary on:
7
+ * - `buildStart` (once at the beginning of every build)
8
+ * - `watchChange` (debounced, when any source `.ts` is edited in dev)
9
+ *
10
+ * It emits the generated `*.anvil.ts` files alongside their source
11
+ * components — same shape as running `anvil build` manually. The
12
+ * bundler's normal TS pipeline picks them up.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * // vite.config.ts
17
+ * import anvil from "@anvil-di/anvil-unplugin/vite";
18
+ *
19
+ * export default defineConfig({
20
+ * plugins: [anvil()],
21
+ * });
22
+ * ```
23
+ */
24
+
25
+ import { execFile } from "node:child_process";
26
+ import { promisify } from "node:util";
27
+ import path from "node:path";
28
+ import {
29
+ readdirSync,
30
+ readFileSync,
31
+ statSync,
32
+ writeFileSync,
33
+ existsSync,
34
+ mkdirSync,
35
+ } from "node:fs";
36
+ import { createUnplugin, type UnpluginInstance } from "unplugin";
37
+ import { resolveBinaryPath, unresolvableBinaryError } from "@anvil-di/anvil-cli";
38
+ import { compile as wasmCompile } from "@anvil-di/anvil-codegen-wasm";
39
+
40
+ const execFileAsync = promisify(execFile);
41
+
42
+ /**
43
+ * A hook that runs before `anvil build` in the plugin lifecycle.
44
+ *
45
+ * Implement this to perform custom codegen (e.g. `bellowsCodegen()`) before
46
+ * the main anvil compilation step. Returned by factory functions such as
47
+ * `bellowsCodegen` in `@anvil-di/bellows`.
48
+ */
49
+ export interface PreBuildHook {
50
+ /** Stable identifier, shown in diagnostics. */
51
+ name: string;
52
+ /** Glob patterns whose changes should trigger a re-run in watch mode. */
53
+ watchPatterns: string[];
54
+ /** Return `true` if the hook should re-run given the set of changed files. */
55
+ shouldRerun(changedFiles: string[]): boolean;
56
+ /** Execute the hook; throw to signal failure. */
57
+ run(): Promise<void>;
58
+ }
59
+
60
+ /**
61
+ * A hook that runs after `anvil build` in the plugin lifecycle.
62
+ * Same shape as `PreBuildHook`; separated by name so callers can keep
63
+ * their intent explicit in the plugin options.
64
+ */
65
+ export interface PostBuildHook {
66
+ /** Stable identifier, shown in diagnostics. */
67
+ name: string;
68
+ /** Glob patterns whose changes should trigger a re-run in watch mode. */
69
+ watchPatterns: string[];
70
+ /** Return `true` if the hook should re-run given the set of changed files. */
71
+ shouldRerun(changedFiles: string[]): boolean;
72
+ /** Execute the hook; throw to signal failure. */
73
+ run(): Promise<void>;
74
+ }
75
+
76
+ /** Plugin options. Every field is optional; sensible defaults match the CLI. */
77
+ export interface AnvilPluginOptions {
78
+ /**
79
+ * Component entry files to (re)generate. Each path is passed to
80
+ * `anvil build --entry <path>`. Defaults to whatever `anvil.config.json`
81
+ * (auto-discovered from the project root) declares — the same logic
82
+ * `anvil build` uses without arguments.
83
+ */
84
+ entries?: string[];
85
+ /**
86
+ * Path to a `tsconfig.json`. Forwarded to the CLI as `--tsconfig`.
87
+ * Lets the resolver honor `paths` / `baseUrl` aliases.
88
+ */
89
+ tsconfig?: string;
90
+ /**
91
+ * Path to the `anvil` binary. When unset, the plugin resolves the
92
+ * native binary via the `@anvil-di/anvil-cli` npm launcher — which in turn
93
+ * picks the right per-platform package (`@anvil-di/anvil-cli-linux-x64`,
94
+ * `@anvil-di/anvil-cli-darwin-arm64`, etc.) installed alongside it.
95
+ *
96
+ * Override only when you need to point at a custom build (e.g. a
97
+ * `cargo build`-produced binary outside `node_modules`).
98
+ */
99
+ cli?: string;
100
+ /**
101
+ * Debounce window (ms) for re-running codegen after a file change in
102
+ * watch mode. Default: 100 — same value `anvil watch` uses for its
103
+ * own filesystem-event debouncing.
104
+ */
105
+ debounceMs?: number;
106
+ /**
107
+ * Glob patterns the plugin will watch in dev mode. Editing any
108
+ * matching file triggers a debounced rebuild. Defaults to `**\/*.ts`
109
+ * — the codegen's M2 resolver is the layer that decides which files
110
+ * actually feed into a particular component, so over-watching is
111
+ * harmless (extra files just get filtered out by the resolver).
112
+ */
113
+ include?: string[];
114
+ /**
115
+ * Which codegen backend to use (M13).
116
+ *
117
+ * - `"native"` (default): spawn the `anvil` Rust binary via
118
+ * `@anvil-di/anvil-cli`. Lower steady-state codegen latency, requires the
119
+ * per-platform binary to be installed.
120
+ * - `"wasm"`: run the entire pipeline in-process through
121
+ * `@anvil-di/anvil-codegen-wasm`. No `spawnSync` cost in the bundler hot
122
+ * path, works anywhere V8 runs (Bun, Cloudflare Workers,
123
+ * StackBlitz, etc.). The WASM compile + instantiate happens once
124
+ * on first build (~80-150ms); subsequent builds are direct
125
+ * function calls.
126
+ *
127
+ * The two paths produce byte-identical output for the same input
128
+ * — same parser, same graph builder, same emitter, just sourced
129
+ * from a process spawn vs an in-memory file map.
130
+ */
131
+ mode?: "native" | "wasm";
132
+ /**
133
+ * For `mode: "wasm"`, the directory whose `.ts` / `.tsx` files
134
+ * should be loaded into the in-memory file map. Defaults to the
135
+ * directory containing the first `entries[0]`'s parent folder.
136
+ * The WASM resolver walks transitively from each entry — extra
137
+ * files in the map are harmless, missing files surface as a
138
+ * diagnostic. Set this when your sources live somewhere other
139
+ * than the entry's own subtree.
140
+ */
141
+ rootDir?: string;
142
+ /**
143
+ * Hooks that run **before** `anvil build` on every `buildStart`.
144
+ *
145
+ * In watch mode a hook re-runs when `hook.shouldRerun(changedFiles)`
146
+ * returns `true`. If any pre-build hook re-runs, `anvil build` and
147
+ * all post-build hooks are also re-run.
148
+ *
149
+ * Hooks run in array order; the first failure aborts the build.
150
+ */
151
+ preBuild?: PreBuildHook[];
152
+ /**
153
+ * Hooks that run **after** `anvil build` on every `buildStart`.
154
+ *
155
+ * In watch mode a post-build hook re-runs when any pre-build hook
156
+ * re-ran (because the build output may have changed), or when
157
+ * `hook.shouldRerun(changedFiles)` returns `true` and no pre-build
158
+ * hook ran.
159
+ *
160
+ * Hooks run in array order; the first failure aborts the post-build
161
+ * phase.
162
+ */
163
+ postBuild?: PostBuildHook[];
164
+ }
165
+
166
+ /**
167
+ * The unplugin factory. Each per-bundler entry point (`/vite`,
168
+ * `/rollup`, etc.) just calls `anvilUnplugin.<name>(options)` to get a
169
+ * bundler-specific plugin object.
170
+ */
171
+ export const anvilUnplugin: UnpluginInstance<AnvilPluginOptions | undefined, false> =
172
+ createUnplugin<AnvilPluginOptions | undefined>((rawOptions) => {
173
+ // Default `cli` to whatever `@anvil-di/anvil-cli` resolves at runtime (the
174
+ // matching `@anvil-di/anvil-cli-<platform>-<arch>` package, or the
175
+ // `ANVIL_CLI_BIN` env override). This is the recommended path for
176
+ // npm-distributed users; explicit `cli:` overrides take priority
177
+ // for monorepo dev where the binary lives in `target/release`.
178
+ const resolvedCli = rawOptions?.cli ?? resolveBinaryPath();
179
+ const mode: "native" | "wasm" = rawOptions?.mode ?? "native";
180
+ const options: Required<
181
+ Omit<AnvilPluginOptions, "entries" | "tsconfig" | "cli" | "rootDir" | "preBuild" | "postBuild">
182
+ > &
183
+ Pick<AnvilPluginOptions, "entries" | "tsconfig" | "rootDir" | "preBuild" | "postBuild"> & {
184
+ cli: string | null;
185
+ } = {
186
+ cli: resolvedCli,
187
+ debounceMs: rawOptions?.debounceMs ?? 100,
188
+ include: rawOptions?.include ?? ["**/*.ts"],
189
+ mode,
190
+ entries: rawOptions?.entries,
191
+ tsconfig: rawOptions?.tsconfig,
192
+ rootDir: rawOptions?.rootDir,
193
+ preBuild: rawOptions?.preBuild,
194
+ postBuild: rawOptions?.postBuild,
195
+ };
196
+
197
+ let pending: NodeJS.Timeout | undefined;
198
+ let inFlight: Promise<void> | undefined;
199
+ // Files that changed during the current debounce window.
200
+ let pendingChanges: Set<string> = new Set();
201
+
202
+ async function runCodegenOnce(): Promise<void> {
203
+ // Coalesce concurrent invocations: the second caller awaits the
204
+ // first's in-flight Promise rather than spawning a duplicate
205
+ // `anvil build`.
206
+ if (inFlight !== undefined) {
207
+ return inFlight;
208
+ }
209
+ inFlight = (async () => {
210
+ try {
211
+ if (options.mode === "wasm") {
212
+ await runWasmBuild(options);
213
+ } else {
214
+ await invokeBuild(options);
215
+ }
216
+ } finally {
217
+ inFlight = undefined;
218
+ }
219
+ })();
220
+ return inFlight;
221
+ }
222
+
223
+ // Run hooks triggered by a set of changed files.
224
+ // Pre-build hooks run first; if any ran, anvil build + all post-build
225
+ // hooks follow. If none ran, only the post-build hooks that opt-in run.
226
+ async function runHooksForChanges(changedFiles: string[]): Promise<void> {
227
+ const preBuildHooks = options.preBuild ?? [];
228
+ const postBuildHooks = options.postBuild ?? [];
229
+
230
+ const preBuildToRun = preBuildHooks.filter((h) =>
231
+ h.shouldRerun(changedFiles),
232
+ );
233
+
234
+ for (const hook of preBuildToRun) {
235
+ await hook.run();
236
+ }
237
+
238
+ if (preBuildToRun.length > 0) {
239
+ await runCodegenOnce();
240
+ for (const hook of postBuildHooks) {
241
+ await hook.run();
242
+ }
243
+ } else {
244
+ for (const hook of postBuildHooks.filter((h) =>
245
+ h.shouldRerun(changedFiles),
246
+ )) {
247
+ await hook.run();
248
+ }
249
+ }
250
+ }
251
+
252
+ function scheduleRebuild(changedFile: string): void {
253
+ pendingChanges.add(changedFile);
254
+ if (pending !== undefined) {
255
+ clearTimeout(pending);
256
+ }
257
+ pending = setTimeout(() => {
258
+ pending = undefined;
259
+ const files = [...pendingChanges];
260
+ pendingChanges = new Set();
261
+ // Errors in watch mode are reported to stderr; we don't crash
262
+ // the dev server.
263
+ void runHooksForChanges(files).catch(() => {});
264
+ }, options.debounceMs);
265
+ }
266
+
267
+ return {
268
+ name: "anvil-unplugin",
269
+ // unplugin's universal hooks. Each bundler maps these onto its
270
+ // own lifecycle (Vite's `buildStart`, Webpack's tap, etc.).
271
+ async buildStart() {
272
+ // Execution order: preBuild hooks → anvil build → postBuild hooks.
273
+ // Fail fast on the first error so the bundler surfaces the diagnostic.
274
+ for (const hook of options.preBuild ?? []) {
275
+ await hook.run();
276
+ }
277
+ await runCodegenOnce();
278
+ for (const hook of options.postBuild ?? []) {
279
+ await hook.run();
280
+ }
281
+ },
282
+ watchChange(id: string) {
283
+ // Skip our own output so we don't infinite-loop.
284
+ if (id.endsWith(".anvil.ts")) {
285
+ return;
286
+ }
287
+ if (!id.endsWith(".ts") && !id.endsWith(".tsx")) {
288
+ return;
289
+ }
290
+ scheduleRebuild(id);
291
+ },
292
+ };
293
+ });
294
+
295
+ async function invokeBuild(options: {
296
+ cli: string | null;
297
+ entries?: string[];
298
+ tsconfig?: string;
299
+ }): Promise<void> {
300
+ if (options.cli === null) {
301
+ throw new Error(unresolvableBinaryError());
302
+ }
303
+ const cli: string = options.cli;
304
+ // The CLI accepts a single --entry per invocation. When the user
305
+ // supplies multiple, we spawn once per entry — concurrency is fine
306
+ // because each entry's output file is co-located with that entry,
307
+ // so writes don't race.
308
+ const tsconfigArgs = options.tsconfig === undefined ? [] : ["--tsconfig", options.tsconfig];
309
+ if (options.entries === undefined || options.entries.length === 0) {
310
+ // Let the CLI auto-discover from `anvil.config.json` /
311
+ // `package.json#anvil`.
312
+ await execFileAsync(cli, ["build", ...tsconfigArgs]);
313
+ return;
314
+ }
315
+ await Promise.all(
316
+ options.entries.map((entry) =>
317
+ execFileAsync(cli, [
318
+ "build",
319
+ "--entry",
320
+ path.resolve(entry),
321
+ ...tsconfigArgs,
322
+ ]),
323
+ ),
324
+ );
325
+ }
326
+
327
+ /**
328
+ * M13: in-process codegen via `@anvil-di/anvil-codegen-wasm`.
329
+ *
330
+ * Reads every `.ts` / `.tsx` file under `rootDir` (defaulting to the
331
+ * first entry's parent dir) into an in-memory file map, hands it to
332
+ * the WASM compile function, and writes the emitted dagger files
333
+ * back to disk co-located with their components — same layout the
334
+ * native CLI produces, just without the `spawnSync` round-trip.
335
+ *
336
+ * Diagnostics are written to stderr in the same format as `anvil
337
+ * check`. Future revisions of this hook will route them through the
338
+ * unplugin context's `this.error` / `this.warn` for inline overlay
339
+ * support, but those APIs differ across bundlers and stderr is the
340
+ * lowest-common-denominator surface that works everywhere today.
341
+ */
342
+ async function runWasmBuild(options: {
343
+ entries?: string[];
344
+ tsconfig?: string;
345
+ rootDir?: string;
346
+ }): Promise<void> {
347
+ if (options.entries === undefined || options.entries.length === 0) {
348
+ throw new Error(
349
+ "@anvil-di/anvil-unplugin: `mode: \"wasm\"` requires explicit `entries:` paths " +
350
+ "(auto-discovery from anvil.config.json isn't wired through the WASM " +
351
+ "build yet). Specify `entries: ['src/**/*-component.ts']` or similar.",
352
+ );
353
+ }
354
+ const root =
355
+ options.rootDir ?? path.dirname(path.resolve(options.entries[0]!));
356
+ const files = collectSourceFiles(root);
357
+
358
+ // Also pull in the `@anvil-di/anvil` runtime so bare-specifier imports
359
+ // resolve. Locate via require.resolve so we don't hardcode the path.
360
+ try {
361
+ const anvilPkg = require.resolve("@anvil-di/anvil/package.json");
362
+ const anvilDir = path.dirname(anvilPkg);
363
+ addRecursive(anvilDir, files);
364
+ } catch {
365
+ // The `@anvil-di/anvil` runtime isn't installed — caller probably stubbed it
366
+ // themselves under a different name; the WASM resolver will
367
+ // surface a `BareNotFound` if anything's actually missing.
368
+ }
369
+
370
+ const aliases = options.tsconfig === undefined ? [] : tsconfigPathsFrom(options.tsconfig);
371
+
372
+ for (const entry of options.entries) {
373
+ const entryAbs = path.resolve(entry);
374
+ const result = wasmCompile({
375
+ entryPath: entryAbs,
376
+ files,
377
+ aliases,
378
+ version: "0.0.1-wasm",
379
+ });
380
+ for (const diag of result.diagnostics) {
381
+ process.stderr.write(`anvil: ${diag.code}: ${diag.summary}\n`);
382
+ process.stderr.write(` at ${diag.primary.path}:${diag.primary.start}\n`);
383
+ }
384
+ for (const emitted of result.emittedFiles) {
385
+ const dir = path.dirname(emitted.path);
386
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
387
+ writeFileSync(emitted.path, emitted.contents, "utf8");
388
+ }
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Read every `.ts` / `.tsx` file under `root` into a map keyed by
394
+ * absolute path. Skips `node_modules` (those entries are added
395
+ * separately when the host's `@anvil-di/anvil` runtime is located).
396
+ */
397
+ function collectSourceFiles(root: string): Record<string, string> {
398
+ const out: Record<string, string> = {};
399
+ addRecursive(root, out);
400
+ return out;
401
+ }
402
+
403
+ function addRecursive(dir: string, out: Record<string, string>): void {
404
+ let entries;
405
+ try {
406
+ entries = readdirSync(dir, { withFileTypes: true });
407
+ } catch {
408
+ return;
409
+ }
410
+ for (const entry of entries) {
411
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
412
+ const abs = path.join(dir, entry.name);
413
+ if (entry.isDirectory()) {
414
+ addRecursive(abs, out);
415
+ continue;
416
+ }
417
+ if (
418
+ entry.isFile() &&
419
+ (abs.endsWith(".ts") || abs.endsWith(".tsx") || abs.endsWith(".d.ts"))
420
+ ) {
421
+ try {
422
+ out[abs] = readFileSync(abs, "utf8");
423
+ } catch {
424
+ // Skip unreadable files; the resolver will surface them if they
425
+ // were actually needed.
426
+ }
427
+ }
428
+ }
429
+ // Avoid lint-warn for unused statSync; the import is documented as
430
+ // available for future host-specific filesystem probes.
431
+ void statSync;
432
+ }
433
+
434
+ /**
435
+ * Pull `compilerOptions.paths` aliases out of a tsconfig.json on
436
+ * disk. Best-effort — bad JSON or missing paths field returns an
437
+ * empty list rather than throwing.
438
+ */
439
+ function tsconfigPathsFrom(tsconfigPath: string): {
440
+ pattern: string;
441
+ target: string;
442
+ baseDir: string;
443
+ }[] {
444
+ try {
445
+ const raw = readFileSync(tsconfigPath, "utf8");
446
+ // Strip simple block comments — tsconfig.json technically
447
+ // permits them. Not a full JSONC parser; covers the 99% case.
448
+ const cleaned = raw.replace(/\/\*[\s\S]*?\*\//g, "");
449
+ const cfg = JSON.parse(cleaned) as {
450
+ compilerOptions?: {
451
+ baseUrl?: string;
452
+ paths?: Record<string, string[]>;
453
+ };
454
+ };
455
+ const baseUrl = cfg.compilerOptions?.baseUrl ?? ".";
456
+ const baseDir = path.resolve(path.dirname(tsconfigPath), baseUrl);
457
+ const paths = cfg.compilerOptions?.paths ?? {};
458
+ return Object.entries(paths).flatMap(([pattern, targets]) =>
459
+ targets.length === 0
460
+ ? []
461
+ : [{ pattern, target: targets[0]!, baseDir }],
462
+ );
463
+ } catch {
464
+ return [];
465
+ }
466
+ }
467
+
468
+ export default anvilUnplugin;
package/src/rollup.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { anvilUnplugin, type AnvilPluginOptions } from "./index.js";
2
+
3
+ /** Rollup plugin form of `@anvil-di/anvil-unplugin`. See the package README. */
4
+ const rollupPlugin = anvilUnplugin.rollup as (options?: AnvilPluginOptions) => unknown;
5
+ export default rollupPlugin;
package/src/rspack.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { anvilUnplugin, type AnvilPluginOptions } from "./index.js";
2
+
3
+ /** Rspack plugin form of `@anvil-di/anvil-unplugin`. See the package README. */
4
+ const rspackPlugin = anvilUnplugin.rspack as (options?: AnvilPluginOptions) => unknown;
5
+ export default rspackPlugin;
package/src/vite.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { anvilUnplugin, type AnvilPluginOptions } from "./index.js";
2
+
3
+ /**
4
+ * Vite plugin that runs anvil codegen at build start and on file
5
+ * changes in dev. Equivalent to `anvil build` integrated into the
6
+ * normal Vite pipeline.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import anvil from "@anvil-di/anvil-unplugin/vite";
11
+ *
12
+ * export default defineConfig({
13
+ * plugins: [anvil({ tsconfig: "./tsconfig.json" })],
14
+ * });
15
+ * ```
16
+ */
17
+ const vitePlugin = anvilUnplugin.vite as (options?: AnvilPluginOptions) => unknown;
18
+ export default vitePlugin;
package/src/webpack.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { anvilUnplugin, type AnvilPluginOptions } from "./index.js";
2
+
3
+ /** Webpack plugin form of `@anvil-di/anvil-unplugin`. See the package README. */
4
+ const webpackPlugin = anvilUnplugin.webpack as (options?: AnvilPluginOptions) => unknown;
5
+ export default webpackPlugin;