@gaganref/confect-cli 10.3.1-fork.9 → 10.3.1-fork.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Bundler.mjs +22 -1
- package/dist/Bundler.mjs.map +1 -1
- package/dist/CodegenError.mjs +16 -1
- package/dist/CodegenError.mjs.map +1 -1
- package/dist/Declaration.mjs +139 -26
- package/dist/Declaration.mjs.map +1 -1
- package/dist/EntryPoint.mjs +2 -0
- package/dist/EntryPoint.mjs.map +1 -1
- package/dist/Evaluation.mjs +39 -13
- package/dist/Evaluation.mjs.map +1 -1
- package/dist/EvaluationWorker.mjs +13 -1
- package/dist/EvaluationWorker.mjs.map +1 -1
- package/dist/FunctionModule.mjs +109 -24
- package/dist/FunctionModule.mjs.map +1 -1
- package/dist/LeafModule.mjs +56 -23
- package/dist/LeafModule.mjs.map +1 -1
- package/dist/ManifestSections.mjs +161 -0
- package/dist/ManifestSections.mjs.map +1 -0
- package/dist/SectionFiles.mjs +264 -0
- package/dist/SectionFiles.mjs.map +1 -0
- package/dist/SyncState.mjs +1 -1
- package/dist/SyncState.mjs.map +1 -1
- package/dist/TableModule.mjs +2 -1
- package/dist/TableModule.mjs.map +1 -1
- package/dist/Watcher.mjs +13 -7
- package/dist/Watcher.mjs.map +1 -1
- package/dist/confect/codegen.mjs +124 -42
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +160 -20
- package/dist/confect/declaration.mjs.map +1 -1
- package/dist/confect/dev.mjs +9 -4
- package/dist/confect/dev.mjs.map +1 -1
- package/dist/templates.mjs +74 -43
- package/dist/templates.mjs.map +1 -1
- package/dist/utils.mjs +14 -1
- package/dist/utils.mjs.map +1 -1
- package/package.json +6 -5
package/dist/Bundler.mjs
CHANGED
|
@@ -73,6 +73,27 @@ const resolveExternalEsm = Option.liftThrowable((specifier, importer, conditions
|
|
|
73
73
|
}));
|
|
74
74
|
const resolveModule = (specifier, importer) => Option.orElse(resolveEsm(specifier, importer), () => resolveCjs(specifier, importer));
|
|
75
75
|
/**
|
|
76
|
+
* The names `file` exports, read by esbuild without evaluating the module, so a
|
|
77
|
+
* test kit that only runs under Vite (`import.meta.glob`) can be checked. None
|
|
78
|
+
* when only running the module would list them: a CommonJS module assigns its
|
|
79
|
+
* exports at run time, and bare imports stay external, so `export *` from
|
|
80
|
+
* another package hides its names.
|
|
81
|
+
*/
|
|
82
|
+
const exportNames = (file) => Effect.tryPromise({
|
|
83
|
+
try: () => esbuild.build({
|
|
84
|
+
entryPoints: [file],
|
|
85
|
+
bundle: true,
|
|
86
|
+
packages: "external",
|
|
87
|
+
format: "esm",
|
|
88
|
+
platform: "node",
|
|
89
|
+
write: false,
|
|
90
|
+
metafile: true,
|
|
91
|
+
logLevel: "silent",
|
|
92
|
+
outdir: "out"
|
|
93
|
+
}),
|
|
94
|
+
catch: (cause) => new BundlerError({ cause })
|
|
95
|
+
}).pipe(Effect.map(({ metafile, outputFiles }) => Object.values(metafile.inputs).some(({ format }) => format === "cjs") || outputFiles.some(({ text }) => /^export \* from /m.test(text)) ? Option.none() : Option.some(Object.values(metafile.outputs).flatMap(({ exports }) => exports))));
|
|
96
|
+
/**
|
|
76
97
|
* Bundles first-party workspace dependencies that `bundle-require` would
|
|
77
98
|
* otherwise externalize and hand to Node's native ESM resolver. Resolves each
|
|
78
99
|
* bare specifier and, following symlinks, bundles it when its real path lives
|
|
@@ -421,6 +442,6 @@ const importersOfPackage = (bundled, packageName, where) => {
|
|
|
421
442
|
return Object.entries(bundled.metafile.inputs).filter(([absolutePath, input]) => where(absolutePath) && input.imports.some((imported) => imported.original === packageName || imported.original?.startsWith(subpathPrefix) === true)).map(([absolutePath]) => absolutePath);
|
|
422
443
|
};
|
|
423
444
|
//#endregion
|
|
424
|
-
export { bundle, bundleWorkspacePlugin, directlyImports, importersOfPackage, resolveModule, withBatch };
|
|
445
|
+
export { bundle, bundleWorkspacePlugin, directlyImports, exportNames, importersOfPackage, resolveModule, withBatch };
|
|
425
446
|
|
|
426
447
|
//# sourceMappingURL=Bundler.mjs.map
|
package/dist/Bundler.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Bundler.mjs","names":[],"sources":["../src/Bundler.ts"],"sourcesContent":["import { createRequire, isBuiltin } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport {\n bundleRequire,\n dynamicImport,\n injectFileScopePlugin,\n JS_EXT_RE,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport { resolveModulePath } from \"exsolve\";\nimport { identity, pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Chunk from \"effect/Chunk\";\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Iterable from \"effect/Iterable\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Record from \"effect/Record\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport * as esbuild from \"esbuild\";\nimport { BundlerError } from \"./BuildError.js\";\nimport { logCoalescedBuildWarnings } from \"./log.js\";\n\nexport interface Bundled {\n readonly module: any;\n readonly metafile: esbuild.Metafile;\n}\n\n/**\n * `bundle-require` sets `absWorkingDir: cwd` on the underlying esbuild build,\n * so the metafile's input keys (and each input's `imports[].path`) are stored\n * relative to that cwd. Callers reach for the metafile with absolute paths\n * (e.g. {@link directlyImports}), so we normalize every key/import path to\n * absolute up front. That way the lookup logic stays oblivious to whatever cwd\n * was used during bundling.\n *\n * `original` (the specifier as written, before resolution) is filled in from\n * `path` when esbuild omits it—esbuild only sets it when it differs from the\n * resolved path, which is exactly the externalized-bare-specifier case that\n * absolutizing `path` would otherwise mangle into `<cwd>/@confect/server`.\n * {@link importersOfPackage} relies on `original` always being the raw\n * specifier.\n */\nconst absolutizeMetafile = (\n path: Path.Path,\n metafile: esbuild.Metafile,\n cwd: string,\n): esbuild.Metafile => {\n const absolutize = (p: string) => path.resolve(cwd, p);\n const inputs = Record.mapEntries(metafile.inputs, (value, key) => [\n absolutize(key),\n {\n ...value,\n imports: Array.map(value.imports, (i) => ({\n ...i,\n path: absolutize(i.path),\n original: i.original ?? i.path,\n })),\n },\n ]);\n const outputs = Record.mapEntries(metafile.outputs, (value, key) => [\n absolutize(key),\n {\n ...value,\n ...(value.entryPoint ? { entryPoint: absolutize(value.entryPoint) } : {}),\n inputs: Record.mapKeys(value.inputs, absolutize),\n imports: Array.map(value.imports, (imported) =>\n imported.external\n ? imported\n : { ...imported, path: absolutize(imported.path) },\n ),\n },\n ]);\n return { inputs, outputs };\n};\n\nconst resolveEsm = Option.liftThrowable((specifier: string, importer: string) =>\n resolveModulePath(specifier, {\n from: importer,\n conditions: [\"node\", \"import\"],\n }),\n);\n\nconst resolveCjs = Option.liftThrowable((specifier: string, importer: string) =>\n createRequire(importer).resolve(specifier),\n);\n\nconst resolveExternalEsm = Option.liftThrowable(\n (specifier: string, importer: string, conditions: string[]) =>\n resolveModulePath(specifier, { from: importer, conditions }),\n);\n\nexport const resolveModule = (\n specifier: string,\n importer: string,\n): Option.Option<string> =>\n Option.orElse(resolveEsm(specifier, importer), () =>\n resolveCjs(specifier, importer),\n );\n\n/**\n * Bundles first-party workspace dependencies that `bundle-require` would\n * otherwise externalize and hand to Node's native ESM resolver. Resolves each\n * bare specifier and, following symlinks, bundles it when its real path lives\n * outside `node_modules`—mirroring Vite's \"linked dependencies are not\n * externalized\" heuristic. Registered ahead of `externalPlugin`, so deferring\n * (returning `undefined`) leaves third-party externalization untouched.\n * `skipPatterns` are the tsconfig `paths` regexes, which keep deferring to\n * esbuild's own `paths` resolution.\n */\nexport const bundleWorkspacePlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n): esbuild.Plugin => ({\n name: \"confect:bundle-workspace\",\n setup(build) {\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n if (isBuiltin(args.path) || path.isAbsolute(args.path)) return undefined;\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path))) {\n return undefined;\n }\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n return Option.match(resolveModule(args.path, importer), {\n onNone: () => ({\n path: args.path,\n external: true,\n warnings: [\n {\n text: `Confect could not resolve workspace dependency \"${args.path}\" (imported from ${importer}) to bundle it; leaving it external.`,\n },\n ],\n }),\n onSome: (resolved) =>\n Effect.runPromise(\n fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),\n ).then((real) =>\n pipe(real, String.split(path.sep), Array.contains(\"node_modules\"))\n ? undefined\n : { path: real },\n ),\n });\n });\n },\n});\n\ninterface CapturedBuildResult {\n readonly metafile: esbuild.Metafile | undefined;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n}\n\nconst captureBuildResultPlugin = (\n ref: Ref.Ref<CapturedBuildResult>,\n): esbuild.Plugin => ({\n name: \"confect:capture-build-result\",\n setup(build) {\n build.onEnd((result) => {\n Effect.runSync(\n Ref.set(ref, {\n metafile: result.metafile,\n warnings: result.warnings,\n }),\n );\n });\n },\n});\n\ninterface BatchCompilation {\n readonly entries: HashMap.HashMap<\n string,\n { readonly source: string; readonly output: string }\n >;\n readonly metafile: esbuild.Metafile;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n readonly cwd: string;\n}\n\nclass BatchIncompatible extends Schema.TaggedError<BatchIncompatible>()(\n \"BatchIncompatible\",\n {\n reason: Schema.Literals([\n \"RuntimeConditions\",\n \"UnsupportedEntries\",\n \"MixedTsconfigs\",\n \"UnattributedWarnings\",\n ]),\n message: Schema.String,\n },\n) {}\n\nclass Batch extends Context.Service<\n Batch,\n {\n readonly entryPoints: ReadonlyArray<string>;\n readonly compilation: Effect.Effect<\n Option.Option<BatchCompilation>,\n never,\n Path.Path | FileSystem.FileSystem\n >;\n }\n>()(\"@confect/cli/Bundler/Batch\") {}\n\ninterface ExternalImport {\n readonly path: string;\n readonly original: string;\n}\n\nconst batchResolutionPlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n conditions: string[],\n externalImports: Ref.Ref<\n HashMap.HashMap<string, ReadonlyArray<ExternalImport>>\n >,\n): esbuild.Plugin => ({\n name: \"confect:batch-resolution\",\n setup(build) {\n const external = (args: esbuild.OnResolveArgs, resolved: string) => {\n const importer = path.resolve(args.importer);\n Effect.runSync(\n Ref.update(\n externalImports,\n HashMap.modifyAt(importer, (imports) =>\n Option.some(\n Array.append(\n Option.getOrElse(imports, () => []),\n { path: resolved, original: args.path },\n ),\n ),\n ),\n ),\n );\n return { path: resolved, external: true };\n };\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === \"entry-point\") return undefined;\n if (isBuiltin(args.path)) return { path: args.path, external: true };\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path)))\n return undefined;\n if (/[\\\\/]node_modules[\\\\/]/.test(args.path)) {\n return external(\n args,\n pathToFileURL(path.resolve(args.resolveDir, args.path)).href,\n );\n }\n if (args.path.startsWith(\".\") || path.isAbsolute(args.path))\n return undefined;\n\n const resolved = resolveModule(args.path, args.importer);\n if (Option.isNone(resolved)) {\n return {\n errors: [\n { text: `Could not resolve \"${args.path}\" from ${args.importer}` },\n ],\n };\n }\n return Effect.runPromise(\n fs\n .realPath(resolved.value)\n .pipe(Effect.orElseSucceed(() => resolved.value)),\n ).then((real) => {\n if (!/[\\\\/]node_modules[\\\\/]/.test(real)) return { path: real };\n if (args.kind === \"require-call\" || args.kind === \"require-resolve\") {\n return external(\n args,\n createRequire(args.importer).resolve(args.path),\n );\n }\n return external(\n args,\n Option.match(\n resolveExternalEsm(args.path, args.importer, conditions),\n {\n onNone: () => args.path,\n onSome: (resolvedPath) => pathToFileURL(resolvedPath).href,\n },\n ),\n );\n });\n });\n },\n});\n\nconst compileBatch = Effect.fn(\"Bundler.compileBatch\")(function* (\n entryPoints: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const nodeOptions = yield* Config.String(\"NODE_OPTIONS\").pipe(\n Config.withDefault(\"\"),\n );\n if (/--conditions|-C|--(?:no-)?addons/.test(nodeOptions))\n return yield* new BatchIncompatible({\n reason: \"RuntimeConditions\",\n message:\n \"NODE_OPTIONS changes Node export conditions; individual builds preserve native resolution.\",\n });\n const runtimeOptions = yield* Effect.try({\n try: () =>\n parseArgs({\n args: process.execArgv,\n options: {\n conditions: { type: \"string\", short: \"C\", multiple: true },\n \"no-addons\": { type: \"boolean\" },\n },\n strict: false,\n allowPositionals: true,\n }).values,\n catch: (cause) => new BundlerError({ cause }),\n });\n const conditions = [\n \"node\",\n \"import\",\n ...(process.features.require_module ? [\"module-sync\"] : []),\n ...(runtimeOptions[\"no-addons\"] ? [] : [\"node-addons\"]),\n ...(runtimeOptions.conditions ?? []).filter(\n (condition) => typeof condition === \"string\",\n ),\n ];\n const entries = Array.dedupe(entryPoints.map((entry) => path.resolve(entry)));\n const first = entries[0];\n if (\n first === undefined ||\n entries.some(\n (entry) => !JS_EXT_RE.test(entry) || /[\\\\/]node_modules[\\\\/]/.test(entry),\n )\n ) {\n return yield* new BatchIncompatible({\n reason: \"UnsupportedEntries\",\n message:\n \"Shared builds require JavaScript or TypeScript entries outside node_modules.\",\n });\n }\n const configs = yield* Effect.try({\n try: () => entries.map((entry) => loadTsConfig(path.dirname(entry))),\n catch: (cause) => new BundlerError({ cause }),\n });\n const config = configs[0];\n if (configs.some((other) => other?.path !== config?.path))\n return yield* new BatchIncompatible({\n reason: \"MixedTsconfigs\",\n message: `Entries use different tsconfigs: ${Array.dedupe(configs.map((item) => item?.path ?? \"(no tsconfig)\")).join(\", \")}`,\n });\n\n const cwd = yield* fs.realPath(path.dirname(first));\n const directory = yield* fs\n .makeTempDirectoryScoped({ prefix: \"confect-batch-\" })\n .pipe(Effect.flatMap((temporary) => fs.realPath(temporary)));\n const artifacts = yield* Effect.forEach(entries, (entry, index) =>\n Effect.map(\n fs.realPath(entry),\n (source) =>\n [\n entry,\n { source, output: path.join(directory, `${index}.mjs`) },\n ] as const,\n ),\n );\n const externalImports = yield* Ref.make(\n HashMap.empty<string, ReadonlyArray<ExternalImport>>(),\n );\n const result = yield* Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: entries.map((entry, index) => ({\n in: entry,\n out: `${index}`,\n })),\n absWorkingDir: cwd,\n outdir: directory,\n outExtension: { \".js\": \".mjs\" },\n chunkNames: \"chunk-[hash]\",\n format: \"esm\",\n platform: \"node\",\n sourcemap: \"inline\",\n bundle: true,\n splitting: true,\n metafile: true,\n write: false,\n logLevel: \"silent\",\n ...(config?.path\n ? { tsconfig: config.path }\n : { tsconfigRaw: config?.data ?? {} }),\n plugins: [\n batchResolutionPlugin(\n path,\n fs,\n tsconfigPathsToRegExp(config?.data.compilerOptions?.paths ?? {}),\n conditions,\n externalImports,\n ),\n injectFileScopePlugin(),\n ],\n }),\n catch: (cause) => new BundlerError({ cause }),\n });\n const inputPaths = HashSet.fromIterable(\n Object.keys(result.metafile.inputs).map((input) =>\n path.resolve(cwd, input),\n ),\n );\n const unattributedWarnings = result.warnings.filter(\n (warning) =>\n !warning.location ||\n !HashSet.has(inputPaths, path.resolve(cwd, warning.location.file)),\n );\n if (unattributedWarnings.length > 0)\n return yield* new BatchIncompatible({\n reason: \"UnattributedWarnings\",\n message: `Cannot attribute build warnings to entries: ${unattributedWarnings.map((warning) => warning.text).join(\"; \")}`,\n });\n yield* Effect.forEach(result.outputFiles, (output) =>\n fs.writeFile(output.path, output.contents),\n );\n const capturedExternalImports = yield* Ref.get(externalImports);\n const inputs = Object.fromEntries(\n Object.entries(result.metafile.inputs).map(([input, metadata]) => {\n const originals = Option.getOrElse(\n HashMap.get(capturedExternalImports, path.resolve(cwd, input)),\n () => [],\n );\n return [\n input,\n {\n ...metadata,\n imports: metadata.imports.flatMap((imported) => {\n const matching = imported.external\n ? originals.filter((original) => original.path === imported.path)\n : [];\n return matching.length === 0\n ? [imported]\n : matching.map((original) =>\n Object.assign({}, imported, {\n original: original.original,\n }),\n );\n }),\n },\n ];\n }),\n );\n return {\n entries: HashMap.fromIterable(artifacts),\n metafile: absolutizeMetafile(path, { ...result.metafile, inputs }, cwd),\n warnings: result.warnings,\n cwd,\n } satisfies BatchCompilation;\n});\n\n/**\n * Lazily shares one compilation across ordinary bundle calls in this effect.\n * Different tsconfigs and failed compilations fall back to individual builds.\n * Runtime conditions supplied through NODE_OPTIONS also use individual builds.\n * Imports still run at each caller, and temporary chunks live until the effect\n * finishes. The disposable evaluator, not this scope, owns Node's import\n * cache.\n */\nexport const withBatch = <A, E, R>(\n entryPoints: ReadonlyArray<string>,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n Effect.scopedWith((scope) =>\n Effect.gen(function* () {\n const current = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(current) &&\n entryPoints.every((entry) => current.value.entryPoints.includes(entry))\n )\n return yield* effect;\n const compilation = yield* Effect.cached(\n compileBatch(entryPoints).pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.asSome,\n Effect.catchTag(\"BatchIncompatible\", (error) =>\n Effect.logDebug(\n \"Shared build skipped; falling back to individual builds.\",\n {\n entryPoints,\n reason: error.reason,\n detail: error.message,\n },\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n Effect.catch((error) =>\n Effect.logDebug(\n \"Shared build failed; falling back to individual builds.\",\n {\n entryPoints,\n reason: \"CompileFailure\",\n },\n Cause.fail(error),\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n ),\n );\n return yield* Effect.provideService(effect, Batch, {\n entryPoints,\n compilation,\n });\n }),\n );\n\ninterface MetafileTraversal {\n readonly pending: Chunk.Chunk<string>;\n readonly visited: HashSet.HashSet<string>;\n}\n\nconst reachableMetafileEntries = <\n Metadata extends {\n readonly imports: ReadonlyArray<{\n readonly path: string;\n readonly external?: boolean;\n }>;\n },\n>(\n entries: Readonly<Record<string, Metadata>>,\n root: string,\n resolveImport: (path: string) => string,\n): Record<string, Metadata> =>\n Object.fromEntries(\n pipe(\n Iterable.unfold<\n MetafileTraversal,\n Option.Option<readonly [string, Metadata]>\n >(\n { pending: Chunk.of(root), visited: HashSet.empty() },\n ({ pending, visited }) => {\n if (!Chunk.isNonEmpty(pending)) return Option.none();\n const key = Chunk.headNonEmpty(pending);\n const remaining = Chunk.tailNonEmpty(pending);\n const metadata = entries[key];\n if (HashSet.has(visited, key) || metadata === undefined)\n return Option.some([\n Option.none(),\n { pending: remaining, visited },\n ]);\n return Option.some([\n Option.some([key, metadata] as const),\n {\n pending: Array.reduce(\n metadata.imports,\n remaining,\n (queue, imported) =>\n imported.external\n ? queue\n : Chunk.append(queue, resolveImport(imported.path)),\n ),\n visited: HashSet.add(visited, key),\n },\n ]);\n },\n ),\n Iterable.getSomes,\n ),\n );\n\nconst entryMetafile = (\n path: Path.Path,\n compilation: BatchCompilation,\n source: string,\n output: string,\n): esbuild.Metafile => ({\n inputs: reachableMetafileEntries(\n compilation.metafile.inputs,\n source,\n identity,\n ),\n outputs: reachableMetafileEntries(\n compilation.metafile.outputs,\n output,\n (key) => path.resolve(compilation.cwd, key),\n ),\n});\n\n/**\n * Bundle a TypeScript entry point with esbuild via {@link bundleRequire} and\n * import the result. `bundle-require` writes a temp `.mjs` next to the source,\n * `import()`s it, and deletes it—so third-party `node_modules` externals\n * resolve through the user's normal `node_modules` walk, while first-party\n * workspace deps are bundled by {@link bundleWorkspacePlugin} and tsconfig\n * `paths` aliases stay inside the bundle.\n *\n * `cwd` is set to the entry's directory so `bundle-require`'s `tsconfig.json`\n * discovery (which walks upward from `cwd`) lands on the project's tsconfig\n * regardless of where `confect codegen` was invoked from, and so esbuild\n * resolves relative imports against the entry's location.\n *\n * The returned pair carries both the imported module and the esbuild metafile\n * so callers can inspect the import graph (see {@link directlyImports}); the\n * metafile is captured via a small `onEnd` plugin because `bundle-require`\n * itself only exposes a flat `dependencies: string[]`.\n *\n * `options.plugins` are registered ahead of every other plugin—including\n * `bundle-require`'s own `externalPlugin`—so a caller-supplied plugin can claim\n * resolutions (e.g. `convex.config` imports) before the workspace and\n * externalization heuristics see them.\n */\nexport const bundle = Effect.fn(\"Bundler.bundle\")(function* (\n entryPoint: string,\n options?: { readonly plugins?: ReadonlyArray<esbuild.Plugin> },\n): Effect.fn.Return<Bundled, BundlerError, Path.Path | FileSystem.FileSystem> {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n\n const batch = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(batch) &&\n !options?.plugins?.length &&\n batch.value.entryPoints.some(\n (entry) => path.resolve(entry) === path.resolve(entryPoint),\n )\n ) {\n const compilation = yield* batch.value.compilation;\n if (Option.isSome(compilation)) {\n const entry = HashMap.get(\n compilation.value.entries,\n path.resolve(entryPoint),\n );\n if (Option.isSome(entry)) {\n const metafile = entryMetafile(\n path,\n compilation.value,\n entry.value.source,\n entry.value.output,\n );\n const module = yield* Effect.tryPromise({\n try: () =>\n dynamicImport(pathToFileURL(entry.value.output).href, {\n format: \"esm\",\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n logCoalescedBuildWarnings(\n compilation.value.warnings.filter(\n (warning) =>\n warning.location &&\n metafile.inputs[\n path.resolve(compilation.value.cwd, warning.location.file)\n ],\n ),\n ),\n ),\n );\n return { module, metafile };\n }\n }\n }\n\n const buildResultRef = yield* Ref.make<CapturedBuildResult>({\n metafile: undefined,\n warnings: [],\n });\n\n const cwd = path.dirname(entryPoint);\n const skipPatterns = yield* Effect.try({\n try: () =>\n tsconfigPathsToRegExp(\n loadTsConfig(cwd)?.data.compilerOptions?.paths ?? {},\n ),\n catch: (cause) => new BundlerError({ cause }),\n });\n const result = yield* Effect.tryPromise({\n try: () =>\n bundleRequire({\n filepath: entryPoint,\n cwd,\n format: \"esm\",\n esbuildOptions: {\n plugins: [\n ...(options?.plugins ?? []),\n bundleWorkspacePlugin(path, fs, skipPatterns),\n captureBuildResultPlugin(buildResultRef),\n ],\n logLevel: \"silent\",\n },\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n Effect.andThen(Ref.get(buildResultRef), (captured) =>\n logCoalescedBuildWarnings(captured.warnings),\n ),\n ),\n );\n\n const { metafile } = yield* Ref.get(buildResultRef);\n if (!metafile) {\n return yield* Effect.die(new Error(\"esbuild metafile missing\"));\n }\n\n return {\n module: result.mod,\n metafile: absolutizeMetafile(path, metafile, cwd),\n };\n});\n\nconst findMetafileInputKey = Effect.fnUntraced(function* (\n metafile: esbuild.Metafile,\n absolutePath: string,\n) {\n const path = yield* Path.Path;\n const resolved = path.resolve(absolutePath);\n if (metafile.inputs[resolved] !== undefined) return Option.some(resolved);\n const fs = yield* FileSystem.FileSystem;\n const real = yield* fs\n .realPath(resolved)\n .pipe(Effect.orElseSucceed(() => resolved));\n return Array.findFirst(\n Object.keys(metafile.inputs),\n (key) => path.resolve(key) === real,\n );\n});\n\n/**\n * Returns `true` when the module bundled from `sourceAbsolutePath` declares a\n * direct import of `targetAbsolutePath` (according to the bundle's esbuild\n * metafile). Returns `false` if either path is missing from the metafile.\n */\nexport const directlyImports = Effect.fnUntraced(function* (\n bundled: Bundled,\n sourceAbsolutePath: string,\n targetAbsolutePath: string,\n) {\n const path = yield* Path.Path;\n const sourceKey = yield* findMetafileInputKey(\n bundled.metafile,\n sourceAbsolutePath,\n );\n const targetKey = yield* findMetafileInputKey(\n bundled.metafile,\n targetAbsolutePath,\n );\n\n return pipe(\n Option.all([sourceKey, targetKey]),\n Option.flatMap(([sourceKey_, targetKey_]) =>\n Option.fromNullishOr(bundled.metafile.inputs[sourceKey_]).pipe(\n Option.map((sourceInput) => {\n const targetResolved = path.resolve(targetKey_);\n return sourceInput.imports.some(\n (importedFile) =>\n path.resolve(importedFile.path) === targetResolved,\n );\n }),\n ),\n ),\n Option.getOrElse(() => false),\n );\n});\n\n/**\n * Returns the absolute paths of every module in the bundle that declares a\n * direct import of `packageName` (the package itself or one of its subpaths)\n * and satisfies `where`. Use `where` to restrict the search to the modules you\n * care about—the bundle's inputs include every transitive dependency.\n *\n * Matching is on the specifier as written rather than the resolved path,\n * because {@link bundleWorkspacePlugin} bundles first-party workspace\n * dependencies (so `@confect/server` resolves to a path inside the monorepo)\n * while a published install externalizes them (so it stays a bare specifier).\n * esbuild erases `import type` before it produces the metafile, so type-only\n * imports are not reported.\n */\nexport const importersOfPackage = (\n bundled: Bundled,\n packageName: string,\n where: (absolutePath: string) => boolean,\n): ReadonlyArray<string> => {\n const subpathPrefix = `${packageName}/`;\n\n return Object.entries(bundled.metafile.inputs)\n .filter(\n ([absolutePath, input]) =>\n where(absolutePath) &&\n input.imports.some(\n (imported) =>\n imported.original === packageName ||\n imported.original?.startsWith(subpathPrefix) === true,\n ),\n )\n .map(([absolutePath]) => absolutePath);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,sBACJ,MACA,UACA,QACqB;CACrB,MAAM,cAAc,MAAc,KAAK,QAAQ,KAAK,CAAC;CAyBrD,OAAO;EAAE,QAxBM,OAAO,WAAW,SAAS,SAAS,OAAO,QAAQ,CAChE,WAAW,GAAG,GACd;GACE,GAAG;GACH,SAAS,MAAM,IAAI,MAAM,UAAU,OAAO;IACxC,GAAG;IACH,MAAM,WAAW,EAAE,IAAI;IACvB,UAAU,EAAE,YAAY,EAAE;GAC5B,EAAE;EACJ,CACF,CAcc;EAAG,SAbD,OAAO,WAAW,SAAS,UAAU,OAAO,QAAQ,CAClE,WAAW,GAAG,GACd;GACE,GA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;AAOD,MAAa,kBAAkB,OAAO,WAAW,WAC/C,SACA,oBACA,oBACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,YAAY,OAAO,qBACvB,QAAQ,UACR,kBACF;CACA,MAAM,YAAY,OAAO,qBACvB,QAAQ,UACR,kBACF;CAEA,OAAO,KACL,OAAO,IAAI,CAAC,WAAW,SAAS,CAAC,GACjC,OAAO,SAAS,CAAC,YAAY,gBAC3B,OAAO,cAAc,QAAQ,SAAS,OAAO,WAAW,CAAC,CAAC,KACxD,OAAO,KAAK,gBAAgB;EAC1B,MAAM,iBAAiB,KAAK,QAAQ,UAAU;EAC9C,OAAO,YAAY,QAAQ,MACxB,iBACC,KAAK,QAAQ,aAAa,IAAI,MAAM,cACxC;CACF,CAAC,CACH,CACF,GACA,OAAO,gBAAgB,KAAK,CAC9B;AACF,CAAC;;;;;;;;;;;;;;AAeD,MAAa,sBACX,SACA,aACA,UAC0B;CAC1B,MAAM,gBAAgB,GAAG,YAAY;CAErC,OAAO,OAAO,QAAQ,QAAQ,SAAS,MAAM,CAAC,CAC3C,QACE,CAAC,cAAc,WACd,MAAM,YAAY,KAClB,MAAM,QAAQ,MACX,aACC,SAAS,aAAa,eACtB,SAAS,UAAU,WAAW,aAAa,MAAM,IACrD,CACJ,CAAC,CACA,KAAK,CAAC,kBAAkB,YAAY;AACzC"}
|
|
1
|
+
{"version":3,"file":"Bundler.mjs","names":[],"sources":["../src/Bundler.ts"],"sourcesContent":["import { createRequire, isBuiltin } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport {\n bundleRequire,\n dynamicImport,\n injectFileScopePlugin,\n JS_EXT_RE,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport { resolveModulePath } from \"exsolve\";\nimport { identity, pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Chunk from \"effect/Chunk\";\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Iterable from \"effect/Iterable\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Record from \"effect/Record\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport * as esbuild from \"esbuild\";\nimport { BundlerError } from \"./BuildError.js\";\nimport { logCoalescedBuildWarnings } from \"./log.js\";\n\nexport interface Bundled {\n readonly module: any;\n readonly metafile: esbuild.Metafile;\n}\n\n/**\n * `bundle-require` sets `absWorkingDir: cwd` on the underlying esbuild build,\n * so the metafile's input keys (and each input's `imports[].path`) are stored\n * relative to that cwd. Callers reach for the metafile with absolute paths\n * (e.g. {@link directlyImports}), so we normalize every key/import path to\n * absolute up front. That way the lookup logic stays oblivious to whatever cwd\n * was used during bundling.\n *\n * `original` (the specifier as written, before resolution) is filled in from\n * `path` when esbuild omits it—esbuild only sets it when it differs from the\n * resolved path, which is exactly the externalized-bare-specifier case that\n * absolutizing `path` would otherwise mangle into `<cwd>/@confect/server`.\n * {@link importersOfPackage} relies on `original` always being the raw\n * specifier.\n */\nconst absolutizeMetafile = (\n path: Path.Path,\n metafile: esbuild.Metafile,\n cwd: string,\n): esbuild.Metafile => {\n const absolutize = (p: string) => path.resolve(cwd, p);\n const inputs = Record.mapEntries(metafile.inputs, (value, key) => [\n absolutize(key),\n {\n ...value,\n imports: Array.map(value.imports, (i) => ({\n ...i,\n path: absolutize(i.path),\n original: i.original ?? i.path,\n })),\n },\n ]);\n const outputs = Record.mapEntries(metafile.outputs, (value, key) => [\n absolutize(key),\n {\n ...value,\n ...(value.entryPoint ? { entryPoint: absolutize(value.entryPoint) } : {}),\n inputs: Record.mapKeys(value.inputs, absolutize),\n imports: Array.map(value.imports, (imported) =>\n imported.external\n ? imported\n : { ...imported, path: absolutize(imported.path) },\n ),\n },\n ]);\n return { inputs, outputs };\n};\n\nconst resolveEsm = Option.liftThrowable((specifier: string, importer: string) =>\n resolveModulePath(specifier, {\n from: importer,\n conditions: [\"node\", \"import\"],\n }),\n);\n\nconst resolveCjs = Option.liftThrowable((specifier: string, importer: string) =>\n createRequire(importer).resolve(specifier),\n);\n\nconst resolveExternalEsm = Option.liftThrowable(\n (specifier: string, importer: string, conditions: string[]) =>\n resolveModulePath(specifier, { from: importer, conditions }),\n);\n\nexport const resolveModule = (\n specifier: string,\n importer: string,\n): Option.Option<string> =>\n Option.orElse(resolveEsm(specifier, importer), () =>\n resolveCjs(specifier, importer),\n );\n\n/**\n * The names `file` exports, read by esbuild without evaluating the module, so a\n * test kit that only runs under Vite (`import.meta.glob`) can be checked. None\n * when only running the module would list them: a CommonJS module assigns its\n * exports at run time, and bare imports stay external, so `export *` from\n * another package hides its names.\n */\nexport const exportNames = (\n file: string,\n): Effect.Effect<Option.Option<ReadonlyArray<string>>, BundlerError> =>\n Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: [file],\n bundle: true,\n packages: \"external\",\n format: \"esm\",\n platform: \"node\",\n write: false,\n metafile: true,\n logLevel: \"silent\",\n outdir: \"out\",\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.map(({ metafile, outputFiles }) =>\n Object.values(metafile.inputs).some(({ format }) => format === \"cjs\") ||\n outputFiles.some(({ text }) => /^export \\* from /m.test(text))\n ? Option.none()\n : Option.some(\n Object.values(metafile.outputs).flatMap(({ exports }) => exports),\n ),\n ),\n );\n\n/**\n * Bundles first-party workspace dependencies that `bundle-require` would\n * otherwise externalize and hand to Node's native ESM resolver. Resolves each\n * bare specifier and, following symlinks, bundles it when its real path lives\n * outside `node_modules`—mirroring Vite's \"linked dependencies are not\n * externalized\" heuristic. Registered ahead of `externalPlugin`, so deferring\n * (returning `undefined`) leaves third-party externalization untouched.\n * `skipPatterns` are the tsconfig `paths` regexes, which keep deferring to\n * esbuild's own `paths` resolution.\n */\nexport const bundleWorkspacePlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n): esbuild.Plugin => ({\n name: \"confect:bundle-workspace\",\n setup(build) {\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n if (isBuiltin(args.path) || path.isAbsolute(args.path)) return undefined;\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path))) {\n return undefined;\n }\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n return Option.match(resolveModule(args.path, importer), {\n onNone: () => ({\n path: args.path,\n external: true,\n warnings: [\n {\n text: `Confect could not resolve workspace dependency \"${args.path}\" (imported from ${importer}) to bundle it; leaving it external.`,\n },\n ],\n }),\n onSome: (resolved) =>\n Effect.runPromise(\n fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),\n ).then((real) =>\n pipe(real, String.split(path.sep), Array.contains(\"node_modules\"))\n ? undefined\n : { path: real },\n ),\n });\n });\n },\n});\n\ninterface CapturedBuildResult {\n readonly metafile: esbuild.Metafile | undefined;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n}\n\nconst captureBuildResultPlugin = (\n ref: Ref.Ref<CapturedBuildResult>,\n): esbuild.Plugin => ({\n name: \"confect:capture-build-result\",\n setup(build) {\n build.onEnd((result) => {\n Effect.runSync(\n Ref.set(ref, {\n metafile: result.metafile,\n warnings: result.warnings,\n }),\n );\n });\n },\n});\n\ninterface BatchCompilation {\n readonly entries: HashMap.HashMap<\n string,\n { readonly source: string; readonly output: string }\n >;\n readonly metafile: esbuild.Metafile;\n readonly warnings: ReadonlyArray<esbuild.Message>;\n readonly cwd: string;\n}\n\nclass BatchIncompatible extends Schema.TaggedError<BatchIncompatible>()(\n \"BatchIncompatible\",\n {\n reason: Schema.Literals([\n \"RuntimeConditions\",\n \"UnsupportedEntries\",\n \"MixedTsconfigs\",\n \"UnattributedWarnings\",\n ]),\n message: Schema.String,\n },\n) {}\n\nclass Batch extends Context.Service<\n Batch,\n {\n readonly entryPoints: ReadonlyArray<string>;\n readonly compilation: Effect.Effect<\n Option.Option<BatchCompilation>,\n never,\n Path.Path | FileSystem.FileSystem\n >;\n }\n>()(\"@confect/cli/Bundler/Batch\") {}\n\ninterface ExternalImport {\n readonly path: string;\n readonly original: string;\n}\n\nconst batchResolutionPlugin = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n skipPatterns: ReadonlyArray<RegExp>,\n conditions: string[],\n externalImports: Ref.Ref<\n HashMap.HashMap<string, ReadonlyArray<ExternalImport>>\n >,\n): esbuild.Plugin => ({\n name: \"confect:batch-resolution\",\n setup(build) {\n const external = (args: esbuild.OnResolveArgs, resolved: string) => {\n const importer = path.resolve(args.importer);\n Effect.runSync(\n Ref.update(\n externalImports,\n HashMap.modifyAt(importer, (imports) =>\n Option.some(\n Array.append(\n Option.getOrElse(imports, () => []),\n { path: resolved, original: args.path },\n ),\n ),\n ),\n ),\n );\n return { path: resolved, external: true };\n };\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === \"entry-point\") return undefined;\n if (isBuiltin(args.path)) return { path: args.path, external: true };\n if (Array.some(skipPatterns, (pattern) => pattern.test(args.path)))\n return undefined;\n if (/[\\\\/]node_modules[\\\\/]/.test(args.path)) {\n return external(\n args,\n pathToFileURL(path.resolve(args.resolveDir, args.path)).href,\n );\n }\n if (args.path.startsWith(\".\") || path.isAbsolute(args.path))\n return undefined;\n\n const resolved = resolveModule(args.path, args.importer);\n if (Option.isNone(resolved)) {\n return {\n errors: [\n { text: `Could not resolve \"${args.path}\" from ${args.importer}` },\n ],\n };\n }\n return Effect.runPromise(\n fs\n .realPath(resolved.value)\n .pipe(Effect.orElseSucceed(() => resolved.value)),\n ).then((real) => {\n if (!/[\\\\/]node_modules[\\\\/]/.test(real)) return { path: real };\n if (args.kind === \"require-call\" || args.kind === \"require-resolve\") {\n return external(\n args,\n createRequire(args.importer).resolve(args.path),\n );\n }\n return external(\n args,\n Option.match(\n resolveExternalEsm(args.path, args.importer, conditions),\n {\n onNone: () => args.path,\n onSome: (resolvedPath) => pathToFileURL(resolvedPath).href,\n },\n ),\n );\n });\n });\n },\n});\n\nconst compileBatch = Effect.fn(\"Bundler.compileBatch\")(function* (\n entryPoints: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const nodeOptions = yield* Config.String(\"NODE_OPTIONS\").pipe(\n Config.withDefault(\"\"),\n );\n if (/--conditions|-C|--(?:no-)?addons/.test(nodeOptions))\n return yield* new BatchIncompatible({\n reason: \"RuntimeConditions\",\n message:\n \"NODE_OPTIONS changes Node export conditions; individual builds preserve native resolution.\",\n });\n const runtimeOptions = yield* Effect.try({\n try: () =>\n parseArgs({\n args: process.execArgv,\n options: {\n conditions: { type: \"string\", short: \"C\", multiple: true },\n \"no-addons\": { type: \"boolean\" },\n },\n strict: false,\n allowPositionals: true,\n }).values,\n catch: (cause) => new BundlerError({ cause }),\n });\n const conditions = [\n \"node\",\n \"import\",\n ...(process.features.require_module ? [\"module-sync\"] : []),\n ...(runtimeOptions[\"no-addons\"] ? [] : [\"node-addons\"]),\n ...(runtimeOptions.conditions ?? []).filter(\n (condition) => typeof condition === \"string\",\n ),\n ];\n const entries = Array.dedupe(entryPoints.map((entry) => path.resolve(entry)));\n const first = entries[0];\n if (\n first === undefined ||\n entries.some(\n (entry) => !JS_EXT_RE.test(entry) || /[\\\\/]node_modules[\\\\/]/.test(entry),\n )\n ) {\n return yield* new BatchIncompatible({\n reason: \"UnsupportedEntries\",\n message:\n \"Shared builds require JavaScript or TypeScript entries outside node_modules.\",\n });\n }\n const configs = yield* Effect.try({\n try: () => entries.map((entry) => loadTsConfig(path.dirname(entry))),\n catch: (cause) => new BundlerError({ cause }),\n });\n const config = configs[0];\n if (configs.some((other) => other?.path !== config?.path))\n return yield* new BatchIncompatible({\n reason: \"MixedTsconfigs\",\n message: `Entries use different tsconfigs: ${Array.dedupe(configs.map((item) => item?.path ?? \"(no tsconfig)\")).join(\", \")}`,\n });\n\n const cwd = yield* fs.realPath(path.dirname(first));\n const directory = yield* fs\n .makeTempDirectoryScoped({ prefix: \"confect-batch-\" })\n .pipe(Effect.flatMap((temporary) => fs.realPath(temporary)));\n const artifacts = yield* Effect.forEach(entries, (entry, index) =>\n Effect.map(\n fs.realPath(entry),\n (source) =>\n [\n entry,\n { source, output: path.join(directory, `${index}.mjs`) },\n ] as const,\n ),\n );\n const externalImports = yield* Ref.make(\n HashMap.empty<string, ReadonlyArray<ExternalImport>>(),\n );\n const result = yield* Effect.tryPromise({\n try: () =>\n esbuild.build({\n entryPoints: entries.map((entry, index) => ({\n in: entry,\n out: `${index}`,\n })),\n absWorkingDir: cwd,\n outdir: directory,\n outExtension: { \".js\": \".mjs\" },\n chunkNames: \"chunk-[hash]\",\n format: \"esm\",\n platform: \"node\",\n sourcemap: \"inline\",\n bundle: true,\n splitting: true,\n metafile: true,\n write: false,\n logLevel: \"silent\",\n ...(config?.path\n ? { tsconfig: config.path }\n : { tsconfigRaw: config?.data ?? {} }),\n plugins: [\n batchResolutionPlugin(\n path,\n fs,\n tsconfigPathsToRegExp(config?.data.compilerOptions?.paths ?? {}),\n conditions,\n externalImports,\n ),\n injectFileScopePlugin(),\n ],\n }),\n catch: (cause) => new BundlerError({ cause }),\n });\n const inputPaths = HashSet.fromIterable(\n Object.keys(result.metafile.inputs).map((input) =>\n path.resolve(cwd, input),\n ),\n );\n const unattributedWarnings = result.warnings.filter(\n (warning) =>\n !warning.location ||\n !HashSet.has(inputPaths, path.resolve(cwd, warning.location.file)),\n );\n if (unattributedWarnings.length > 0)\n return yield* new BatchIncompatible({\n reason: \"UnattributedWarnings\",\n message: `Cannot attribute build warnings to entries: ${unattributedWarnings.map((warning) => warning.text).join(\"; \")}`,\n });\n yield* Effect.forEach(result.outputFiles, (output) =>\n fs.writeFile(output.path, output.contents),\n );\n const capturedExternalImports = yield* Ref.get(externalImports);\n const inputs = Object.fromEntries(\n Object.entries(result.metafile.inputs).map(([input, metadata]) => {\n const originals = Option.getOrElse(\n HashMap.get(capturedExternalImports, path.resolve(cwd, input)),\n () => [],\n );\n return [\n input,\n {\n ...metadata,\n imports: metadata.imports.flatMap((imported) => {\n const matching = imported.external\n ? originals.filter((original) => original.path === imported.path)\n : [];\n return matching.length === 0\n ? [imported]\n : matching.map((original) =>\n Object.assign({}, imported, {\n original: original.original,\n }),\n );\n }),\n },\n ];\n }),\n );\n return {\n entries: HashMap.fromIterable(artifacts),\n metafile: absolutizeMetafile(path, { ...result.metafile, inputs }, cwd),\n warnings: result.warnings,\n cwd,\n } satisfies BatchCompilation;\n});\n\n/**\n * Lazily shares one compilation across ordinary bundle calls in this effect.\n * Different tsconfigs and failed compilations fall back to individual builds.\n * Runtime conditions supplied through NODE_OPTIONS also use individual builds.\n * Imports still run at each caller, and temporary chunks live until the effect\n * finishes. The disposable evaluator, not this scope, owns Node's import\n * cache.\n */\nexport const withBatch = <A, E, R>(\n entryPoints: ReadonlyArray<string>,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n Effect.scopedWith((scope) =>\n Effect.gen(function* () {\n const current = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(current) &&\n entryPoints.every((entry) => current.value.entryPoints.includes(entry))\n )\n return yield* effect;\n const compilation = yield* Effect.cached(\n compileBatch(entryPoints).pipe(\n Effect.provideService(Scope.Scope, scope),\n Effect.asSome,\n Effect.catchTag(\"BatchIncompatible\", (error) =>\n Effect.logDebug(\n \"Shared build skipped; falling back to individual builds.\",\n {\n entryPoints,\n reason: error.reason,\n detail: error.message,\n },\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n Effect.catch((error) =>\n Effect.logDebug(\n \"Shared build failed; falling back to individual builds.\",\n {\n entryPoints,\n reason: \"CompileFailure\",\n },\n Cause.fail(error),\n ).pipe(Effect.as(Option.none<BatchCompilation>())),\n ),\n ),\n );\n return yield* Effect.provideService(effect, Batch, {\n entryPoints,\n compilation,\n });\n }),\n );\n\ninterface MetafileTraversal {\n readonly pending: Chunk.Chunk<string>;\n readonly visited: HashSet.HashSet<string>;\n}\n\nconst reachableMetafileEntries = <\n Metadata extends {\n readonly imports: ReadonlyArray<{\n readonly path: string;\n readonly external?: boolean;\n }>;\n },\n>(\n entries: Readonly<Record<string, Metadata>>,\n root: string,\n resolveImport: (path: string) => string,\n): Record<string, Metadata> =>\n Object.fromEntries(\n pipe(\n Iterable.unfold<\n MetafileTraversal,\n Option.Option<readonly [string, Metadata]>\n >(\n { pending: Chunk.of(root), visited: HashSet.empty() },\n ({ pending, visited }) => {\n if (!Chunk.isNonEmpty(pending)) return Option.none();\n const key = Chunk.headNonEmpty(pending);\n const remaining = Chunk.tailNonEmpty(pending);\n const metadata = entries[key];\n if (HashSet.has(visited, key) || metadata === undefined)\n return Option.some([\n Option.none(),\n { pending: remaining, visited },\n ]);\n return Option.some([\n Option.some([key, metadata] as const),\n {\n pending: Array.reduce(\n metadata.imports,\n remaining,\n (queue, imported) =>\n imported.external\n ? queue\n : Chunk.append(queue, resolveImport(imported.path)),\n ),\n visited: HashSet.add(visited, key),\n },\n ]);\n },\n ),\n Iterable.getSomes,\n ),\n );\n\nconst entryMetafile = (\n path: Path.Path,\n compilation: BatchCompilation,\n source: string,\n output: string,\n): esbuild.Metafile => ({\n inputs: reachableMetafileEntries(\n compilation.metafile.inputs,\n source,\n identity,\n ),\n outputs: reachableMetafileEntries(\n compilation.metafile.outputs,\n output,\n (key) => path.resolve(compilation.cwd, key),\n ),\n});\n\n/**\n * Bundle a TypeScript entry point with esbuild via {@link bundleRequire} and\n * import the result. `bundle-require` writes a temp `.mjs` next to the source,\n * `import()`s it, and deletes it—so third-party `node_modules` externals\n * resolve through the user's normal `node_modules` walk, while first-party\n * workspace deps are bundled by {@link bundleWorkspacePlugin} and tsconfig\n * `paths` aliases stay inside the bundle.\n *\n * `cwd` is set to the entry's directory so `bundle-require`'s `tsconfig.json`\n * discovery (which walks upward from `cwd`) lands on the project's tsconfig\n * regardless of where `confect codegen` was invoked from, and so esbuild\n * resolves relative imports against the entry's location.\n *\n * The returned pair carries both the imported module and the esbuild metafile\n * so callers can inspect the import graph (see {@link directlyImports}); the\n * metafile is captured via a small `onEnd` plugin because `bundle-require`\n * itself only exposes a flat `dependencies: string[]`.\n *\n * `options.plugins` are registered ahead of every other plugin—including\n * `bundle-require`'s own `externalPlugin`—so a caller-supplied plugin can claim\n * resolutions (e.g. `convex.config` imports) before the workspace and\n * externalization heuristics see them.\n */\nexport const bundle = Effect.fn(\"Bundler.bundle\")(function* (\n entryPoint: string,\n options?: { readonly plugins?: ReadonlyArray<esbuild.Plugin> },\n): Effect.fn.Return<Bundled, BundlerError, Path.Path | FileSystem.FileSystem> {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n\n const batch = yield* Effect.serviceOption(Batch);\n if (\n Option.isSome(batch) &&\n !options?.plugins?.length &&\n batch.value.entryPoints.some(\n (entry) => path.resolve(entry) === path.resolve(entryPoint),\n )\n ) {\n const compilation = yield* batch.value.compilation;\n if (Option.isSome(compilation)) {\n const entry = HashMap.get(\n compilation.value.entries,\n path.resolve(entryPoint),\n );\n if (Option.isSome(entry)) {\n const metafile = entryMetafile(\n path,\n compilation.value,\n entry.value.source,\n entry.value.output,\n );\n const module = yield* Effect.tryPromise({\n try: () =>\n dynamicImport(pathToFileURL(entry.value.output).href, {\n format: \"esm\",\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n logCoalescedBuildWarnings(\n compilation.value.warnings.filter(\n (warning) =>\n warning.location &&\n metafile.inputs[\n path.resolve(compilation.value.cwd, warning.location.file)\n ],\n ),\n ),\n ),\n );\n return { module, metafile };\n }\n }\n }\n\n const buildResultRef = yield* Ref.make<CapturedBuildResult>({\n metafile: undefined,\n warnings: [],\n });\n\n const cwd = path.dirname(entryPoint);\n const skipPatterns = yield* Effect.try({\n try: () =>\n tsconfigPathsToRegExp(\n loadTsConfig(cwd)?.data.compilerOptions?.paths ?? {},\n ),\n catch: (cause) => new BundlerError({ cause }),\n });\n const result = yield* Effect.tryPromise({\n try: () =>\n bundleRequire({\n filepath: entryPoint,\n cwd,\n format: \"esm\",\n esbuildOptions: {\n plugins: [\n ...(options?.plugins ?? []),\n bundleWorkspacePlugin(path, fs, skipPatterns),\n captureBuildResultPlugin(buildResultRef),\n ],\n logLevel: \"silent\",\n },\n }),\n catch: (cause) => new BundlerError({ cause }),\n }).pipe(\n Effect.ensuring(\n Effect.andThen(Ref.get(buildResultRef), (captured) =>\n logCoalescedBuildWarnings(captured.warnings),\n ),\n ),\n );\n\n const { metafile } = yield* Ref.get(buildResultRef);\n if (!metafile) {\n return yield* Effect.die(new Error(\"esbuild metafile missing\"));\n }\n\n return {\n module: result.mod,\n metafile: absolutizeMetafile(path, metafile, cwd),\n };\n});\n\nconst findMetafileInputKey = Effect.fnUntraced(function* (\n metafile: esbuild.Metafile,\n absolutePath: string,\n) {\n const path = yield* Path.Path;\n const resolved = path.resolve(absolutePath);\n if (metafile.inputs[resolved] !== undefined) return Option.some(resolved);\n const fs = yield* FileSystem.FileSystem;\n const real = yield* fs\n .realPath(resolved)\n .pipe(Effect.orElseSucceed(() => resolved));\n return Array.findFirst(\n Object.keys(metafile.inputs),\n (key) => path.resolve(key) === real,\n );\n});\n\n/**\n * Returns `true` when the module bundled from `sourceAbsolutePath` declares a\n * direct import of `targetAbsolutePath` (according to the bundle's esbuild\n * metafile). Returns `false` if either path is missing from the metafile.\n */\nexport const directlyImports = Effect.fnUntraced(function* (\n bundled: Bundled,\n sourceAbsolutePath: string,\n targetAbsolutePath: string,\n) {\n const path = yield* Path.Path;\n const sourceKey = yield* findMetafileInputKey(\n bundled.metafile,\n sourceAbsolutePath,\n );\n const targetKey = yield* findMetafileInputKey(\n bundled.metafile,\n targetAbsolutePath,\n );\n\n return pipe(\n Option.all([sourceKey, targetKey]),\n Option.flatMap(([sourceKey_, targetKey_]) =>\n Option.fromNullishOr(bundled.metafile.inputs[sourceKey_]).pipe(\n Option.map((sourceInput) => {\n const targetResolved = path.resolve(targetKey_);\n return sourceInput.imports.some(\n (importedFile) =>\n path.resolve(importedFile.path) === targetResolved,\n );\n }),\n ),\n ),\n Option.getOrElse(() => false),\n );\n});\n\n/**\n * Returns the absolute paths of every module in the bundle that declares a\n * direct import of `packageName` (the package itself or one of its subpaths)\n * and satisfies `where`. Use `where` to restrict the search to the modules you\n * care about—the bundle's inputs include every transitive dependency.\n *\n * Matching is on the specifier as written rather than the resolved path,\n * because {@link bundleWorkspacePlugin} bundles first-party workspace\n * dependencies (so `@confect/server` resolves to a path inside the monorepo)\n * while a published install externalizes them (so it stays a bare specifier).\n * esbuild erases `import type` before it produces the metafile, so type-only\n * imports are not reported.\n */\nexport const importersOfPackage = (\n bundled: Bundled,\n packageName: string,\n where: (absolutePath: string) => boolean,\n): ReadonlyArray<string> => {\n const subpathPrefix = `${packageName}/`;\n\n return Object.entries(bundled.metafile.inputs)\n .filter(\n ([absolutePath, input]) =>\n where(absolutePath) &&\n input.imports.some(\n (imported) =>\n imported.original === packageName ||\n imported.original?.startsWith(subpathPrefix) === true,\n ),\n )\n .map(([absolutePath]) => absolutePath);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAM,sBACJ,MACA,UACA,QACqB;CACrB,MAAM,cAAc,MAAc,KAAK,QAAQ,KAAK,CAAC;CAyBrD,OAAO;EAAE,QAxBM,OAAO,WAAW,SAAS,SAAS,OAAO,QAAQ,CAChE,WAAW,GAAG,GACd;GACE,GAAG;GACH,SAAS,MAAM,IAAI,MAAM,UAAU,OAAO;IACxC,GAAG;IACH,MAAM,WAAW,EAAE,IAAI;IACvB,UAAU,EAAE,YAAY,EAAE;GAC5B,EAAE;EACJ,CACF,CAcc;EAAG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OAAO,OAAO,QAAQ,QAAQ,SAAS,MAAM,CAAC,CAC3C,QACE,CAAC,cAAc,WACd,MAAM,YAAY,KAClB,MAAM,QAAQ,MACX,aACC,SAAS,aAAa,eACtB,SAAS,UAAU,WAAW,aAAa,MAAM,IACrD,CACJ,CAAC,CACA,KAAK,CAAC,kBAAkB,YAAY;AACzC"}
|
package/dist/CodegenError.mjs
CHANGED
|
@@ -52,6 +52,10 @@ var ImplMissingMiddlewareError = class extends Schema.TaggedError()("ImplMissing
|
|
|
52
52
|
groupPath: Schema.String,
|
|
53
53
|
missingMiddlewareKeys: Schema.Array(Schema.String)
|
|
54
54
|
}) {};
|
|
55
|
+
var RequiredMiddlewareError = class extends Schema.TaggedError()("RequiredMiddlewareError", { missing: Schema.Array(Schema.Struct({
|
|
56
|
+
functionName: Schema.String,
|
|
57
|
+
middlewareKey: Schema.String
|
|
58
|
+
})) }) {};
|
|
55
59
|
var ParentChildNameCollisionError = class extends Schema.TaggedError()("ParentChildNameCollisionError", {
|
|
56
60
|
parentSpecPath: Schema.String,
|
|
57
61
|
childSpecPath: Schema.String,
|
|
@@ -80,10 +84,15 @@ var InvalidDeclarationError = class extends Schema.TaggedError()("InvalidDeclara
|
|
|
80
84
|
declarationPath: Schema.String,
|
|
81
85
|
reason: Schema.String
|
|
82
86
|
}) {};
|
|
87
|
+
var InvalidManifestSectionError = class extends Schema.TaggedError()("InvalidManifestSectionError", {
|
|
88
|
+
sectionKey: Schema.String,
|
|
89
|
+
reason: Schema.String
|
|
90
|
+
}) {};
|
|
83
91
|
var HandWrittenConvexFileError = class extends Schema.TaggedError()("HandWrittenConvexFileError", {
|
|
84
92
|
convexPath: Schema.String,
|
|
85
93
|
declarationPath: Schema.String
|
|
86
94
|
}) {};
|
|
95
|
+
var UnownedConvexEntrypointError = class extends Schema.TaggedError()("UnownedConvexEntrypointError", { filePaths: Schema.Array(Schema.String) }) {};
|
|
87
96
|
var DeclarationKindMismatchError = class extends Schema.TaggedError()("DeclarationKindMismatchError", {
|
|
88
97
|
declarationPath: Schema.String,
|
|
89
98
|
declaredKind: Schema.Literals(["app", "component"]),
|
|
@@ -109,6 +118,7 @@ const CodegenError = Schema.Union([
|
|
|
109
118
|
ImplNotFinalizedError,
|
|
110
119
|
ImplMissingFunctionsError,
|
|
111
120
|
ImplMissingMiddlewareError,
|
|
121
|
+
RequiredMiddlewareError,
|
|
112
122
|
ParentChildNameCollisionError,
|
|
113
123
|
InvalidTableDefaultExportError,
|
|
114
124
|
InvalidTableFilenameError,
|
|
@@ -117,7 +127,9 @@ const CodegenError = Schema.Union([
|
|
|
117
127
|
ConflictingDocNameError,
|
|
118
128
|
InvalidConvexConfigError,
|
|
119
129
|
InvalidDeclarationError,
|
|
130
|
+
InvalidManifestSectionError,
|
|
120
131
|
HandWrittenConvexFileError,
|
|
132
|
+
UnownedConvexEntrypointError,
|
|
121
133
|
DeclarationKindMismatchError,
|
|
122
134
|
CallbackPrefixError
|
|
123
135
|
]);
|
|
@@ -175,11 +187,14 @@ const renderParentChildNameCollisionError = (error) => singleLine("Spec ", forma
|
|
|
175
187
|
const renderCodegenError = (error) => {
|
|
176
188
|
if (isBuildError(error)) return renderBuildError(error);
|
|
177
189
|
if (error._tag === "ComponentNodeGroupError") return singleLine(`Group "${error.groupPath}" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`);
|
|
190
|
+
if (error._tag === "RequiredMiddlewareError") return singleLine("Required middleware is missing:\n", error.missing.map(({ functionName, middlewareKey }) => `${functionName} requires middleware "${middlewareKey}"`).join("\n"));
|
|
178
191
|
if (error._tag === "RemoveBusyError") return singleLine("Could not remove ", formatPath(error.path), ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`);
|
|
179
192
|
if (error._tag === "InvalidDeclarationError") return singleLine("Declaration ", formatPath(error.declarationPath), ` is invalid: ${error.reason}`);
|
|
193
|
+
if (error._tag === "InvalidManifestSectionError") return singleLine(`Manifest section "${error.sectionKey}" is invalid: ${error.reason}`);
|
|
180
194
|
if (error._tag === "DeclarationKindMismatchError") return singleLine("Declaration ", formatPath(error.declarationPath), ` declares kind "${error.declaredKind}", but the target directory is kind "${error.targetKind}".`);
|
|
181
195
|
if (error._tag === "CallbackPrefixError") return singleLine("Callback contract ", `"${error.contractId}" in `, formatPath(error.declarationPath), ` must start with "${error.componentName}/" for component "${error.componentName}".`);
|
|
182
196
|
if (error._tag === "HandWrittenConvexFileError") return singleLine("Found a hand-written ", formatPath(error.convexPath), ". `confect codegen` writes it from ", formatPath(error.declarationPath), " now; move its contents there and delete the file.");
|
|
197
|
+
if (error._tag === "UnownedConvexEntrypointError") return singleLine(error.filePaths.map((file) => formatPath(file)).join(", "), error.filePaths.length === 1 ? " was" : " were", " not written by confect codegen. Generated files only re-export the registry; put authored code outside convex/. If a file is stale generated output, delete it and run codegen again.");
|
|
183
198
|
return Match.value(error).pipe(Match.tag("SnapshotError", ({ reason, relativePath, pathSegments }) => singleLine(`Invalid generation metadata (${reason})`, relativePath === "" ? "" : ` for ${relativePath}`, pathSegments.length === 0 ? "." : ` at ${pathSegments.join("/")}.`)), Match.tag("MissingImplFileError", renderMissingImplFileError), Match.tag("MissingSpecFileError", renderMissingSpecFileError), Match.tag("SpecMissingDefaultGroupSpecError", renderSpecMissingDefaultGroupSpecError), Match.tag("SpecImportsServerError", renderSpecImportsServerError), Match.tag("InvalidMiddlewareAttachmentError", (attachmentError) => singleLine("Spec ", formatPath(attachmentError.specPath), `: ${attachmentError.message}`)), Match.tag("ImplMissingSpecImportError", renderImplMissingSpecImportError), Match.tag("ImplMissingDefaultLayerError", renderImplMissingDefaultLayerError), Match.tag("ImplNotFinalizedError", renderImplNotFinalizedError), Match.tag("ImplMissingFunctionsError", renderImplMissingFunctionsError), Match.tag("ImplMissingMiddlewareError", renderImplMissingMiddlewareError), Match.tag("ParentChildNameCollisionError", renderParentChildNameCollisionError), Match.tag("InvalidTableDefaultExportError", renderInvalidTableDefaultExportError), Match.tag("InvalidTableFilenameError", renderInvalidTableFilenameError), Match.tag("DuplicateTableNameError", renderDuplicateTableNameError), Match.tag("LegacySchemaFileError", renderLegacySchemaFileError), Match.tag("ConflictingDocNameError", renderConflictingDocNameError), Match.tag("InvalidConvexConfigError", renderInvalidConvexConfigError), Match.exhaustive);
|
|
184
199
|
};
|
|
185
200
|
const logCodegenError = (error) => Console.error(renderCodegenError(error));
|
|
@@ -189,6 +204,6 @@ const logCodegenError = (error) => Console.error(renderCodegenError(error));
|
|
|
189
204
|
*/
|
|
190
205
|
const tapAndLog = (effect) => effect.pipe(Effect.tapError((error) => isCodegenError(error) ? logCodegenError(error) : Effect.void));
|
|
191
206
|
//#endregion
|
|
192
|
-
export { CallbackPrefixError, CodegenError, ComponentNodeGroupError, ConflictingDocNameError, DeclarationKindMismatchError, DuplicateTableNameError, HandWrittenConvexFileError, ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidConvexConfigError, InvalidDeclarationError, InvalidMiddlewareAttachmentError, InvalidTableDefaultExportError, InvalidTableFilenameError, LegacySchemaFileError, MissingImplFileError, MissingSpecFileError, ParentChildNameCollisionError, RemoveBusyError, SpecImportsServerError, SpecMissingDefaultGroupSpecError, isCodegenError, logCodegenError, renderCodegenError, tapAndLog };
|
|
207
|
+
export { CallbackPrefixError, CodegenError, ComponentNodeGroupError, ConflictingDocNameError, DeclarationKindMismatchError, DuplicateTableNameError, HandWrittenConvexFileError, ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidConvexConfigError, InvalidDeclarationError, InvalidManifestSectionError, InvalidMiddlewareAttachmentError, InvalidTableDefaultExportError, InvalidTableFilenameError, LegacySchemaFileError, MissingImplFileError, MissingSpecFileError, ParentChildNameCollisionError, RemoveBusyError, RequiredMiddlewareError, SpecImportsServerError, SpecMissingDefaultGroupSpecError, UnownedConvexEntrypointError, isCodegenError, logCodegenError, renderCodegenError, tapAndLog };
|
|
193
208
|
|
|
194
209
|
//# sourceMappingURL=CodegenError.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodegenError.mjs","names":["Ansi.red"],"sources":["../src/CodegenError.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport { pipe } from \"effect/Function\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { BuildError, isBuildError } from \"./BuildError.js\";\nimport { SnapshotError } from \"./SnapshotError.js\";\nimport * as Ansi from \"./Ansi.js\";\nimport { formatPath, renderBuildError } from \"./log.js\";\n\n// --- Variants ---\n\nexport class MissingImplFileError extends Schema.TaggedError<MissingImplFileError>()(\n \"MissingImplFileError\",\n {\n specPath: Schema.String,\n expectedImplPath: Schema.String,\n },\n) {}\n\nexport class MissingSpecFileError extends Schema.TaggedError<MissingSpecFileError>()(\n \"MissingSpecFileError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class SpecMissingDefaultGroupSpecError extends Schema.TaggedError<SpecMissingDefaultGroupSpecError>()(\n \"SpecMissingDefaultGroupSpecError\",\n {\n specPath: Schema.String,\n },\n) {}\n\nexport class RemoveBusyError extends Schema.TaggedError<RemoveBusyError>()(\n \"RemoveBusyError\",\n { path: Schema.String, attempts: Schema.Finite, cause: Schema.Unknown },\n) {}\n\nexport class ComponentNodeGroupError extends Schema.TaggedError<ComponentNodeGroupError>()(\n \"ComponentNodeGroupError\",\n {\n specPath: Schema.String,\n groupPath: Schema.String,\n },\n) {}\n\nexport class SpecImportsServerError extends Schema.TaggedError<SpecImportsServerError>()(\n \"SpecImportsServerError\",\n {\n specPath: Schema.String,\n importerPaths: Schema.Array(Schema.String),\n },\n) {}\n\nexport class InvalidMiddlewareAttachmentError extends Schema.TaggedError<InvalidMiddlewareAttachmentError>()(\n \"InvalidMiddlewareAttachmentError\",\n { specPath: Schema.String, message: Schema.String },\n) {}\n\nexport class ImplMissingSpecImportError extends Schema.TaggedError<ImplMissingSpecImportError>()(\n \"ImplMissingSpecImportError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingDefaultLayerError extends Schema.TaggedError<ImplMissingDefaultLayerError>()(\n \"ImplMissingDefaultLayerError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplNotFinalizedError extends Schema.TaggedError<ImplNotFinalizedError>()(\n \"ImplNotFinalizedError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingFunctionsError extends Schema.TaggedError<ImplMissingFunctionsError>()(\n \"ImplMissingFunctionsError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingFunctionNames: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ImplMissingMiddlewareError extends Schema.TaggedError<ImplMissingMiddlewareError>()(\n \"ImplMissingMiddlewareError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingMiddlewareKeys: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ParentChildNameCollisionError extends Schema.TaggedError<ParentChildNameCollisionError>()(\n \"ParentChildNameCollisionError\",\n {\n parentSpecPath: Schema.String,\n childSpecPath: Schema.String,\n collisionName: Schema.String,\n collisionKind: Schema.Literals([\"function\", \"group\"]),\n },\n) {}\n\nexport class InvalidTableDefaultExportError extends Schema.TaggedError<InvalidTableDefaultExportError>()(\n \"InvalidTableDefaultExportError\",\n {\n tablePath: Schema.String,\n },\n) {}\n\nexport class InvalidTableFilenameError extends Schema.TaggedError<InvalidTableFilenameError>()(\n \"InvalidTableFilenameError\",\n {\n tablePath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class DuplicateTableNameError extends Schema.TaggedError<DuplicateTableNameError>()(\n \"DuplicateTableNameError\",\n {\n // Every table name that more than one file resolves to, each paired with\n // the colliding file paths. All collisions are captured in a single pass\n // so the user can fix them together rather than re-running codegen once\n // per conflict.\n collisions: Schema.Array(\n Schema.Struct({\n tableName: Schema.String,\n tablePaths: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class LegacySchemaFileError extends Schema.TaggedError<LegacySchemaFileError>()(\n \"LegacySchemaFileError\",\n {\n schemaPath: Schema.String,\n },\n) {}\n\nexport class ConflictingDocNameError extends Schema.TaggedError<ConflictingDocNameError>()(\n \"ConflictingDocNameError\",\n {\n collisions: Schema.Array(\n Schema.Struct({\n docName: Schema.String,\n tableNames: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class InvalidConvexConfigError extends Schema.TaggedError<InvalidConvexConfigError>()(\n \"InvalidConvexConfigError\",\n {\n configPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class InvalidDeclarationError extends Schema.TaggedError<InvalidDeclarationError>()(\n \"InvalidDeclarationError\",\n {\n declarationPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class HandWrittenConvexFileError extends Schema.TaggedError<HandWrittenConvexFileError>()(\n \"HandWrittenConvexFileError\",\n {\n convexPath: Schema.String,\n declarationPath: Schema.String,\n },\n) {}\n\nexport class DeclarationKindMismatchError extends Schema.TaggedError<DeclarationKindMismatchError>()(\n \"DeclarationKindMismatchError\",\n {\n declarationPath: Schema.String,\n declaredKind: Schema.Literals([\"app\", \"component\"]),\n targetKind: Schema.Literals([\"app\", \"component\"]),\n },\n) {}\n\nexport class CallbackPrefixError extends Schema.TaggedError<CallbackPrefixError>()(\n \"CallbackPrefixError\",\n {\n declarationPath: Schema.String,\n contractId: Schema.String,\n componentName: Schema.String,\n },\n) {}\n\nexport const CodegenError = Schema.Union([\n SnapshotError,\n BuildError,\n MissingImplFileError,\n MissingSpecFileError,\n SpecMissingDefaultGroupSpecError,\n ComponentNodeGroupError,\n RemoveBusyError,\n SpecImportsServerError,\n InvalidMiddlewareAttachmentError,\n ImplMissingSpecImportError,\n ImplMissingDefaultLayerError,\n ImplNotFinalizedError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n ParentChildNameCollisionError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n DuplicateTableNameError,\n LegacySchemaFileError,\n ConflictingDocNameError,\n InvalidConvexConfigError,\n InvalidDeclarationError,\n HandWrittenConvexFileError,\n DeclarationKindMismatchError,\n CallbackPrefixError,\n]);\nexport type CodegenError = typeof CodegenError.Type;\n\nexport const isCodegenError = (error: unknown): error is CodegenError => {\n if (isBuildError(error)) return true;\n return Schema.is(CodegenError)(error);\n};\n\n// --- Per-variant rendering ---\n\nconst cross = Ansi.red(\"✘\");\n\nconst stemFromSpecPath = (specPath: string): string => {\n const lastSep = Math.max(\n specPath.lastIndexOf(\"/\"),\n specPath.lastIndexOf(\"\\\\\"),\n );\n const basename = lastSep < 0 ? specPath : specPath.slice(lastSep + 1);\n return basename.endsWith(\".spec.ts\")\n ? basename.slice(0, -\".spec.ts\".length)\n : basename;\n};\n\nconst singleLine = (...parts: ReadonlyArray<string>): string =>\n `${cross} ${parts.join(\"\")}`;\n\nconst renderMissingImplFileError = (error: MissingImplFileError): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" has no sibling impl; create \",\n formatPath(error.expectedImplPath),\n \" and default-export a GroupImpl layer from it.\",\n );\n\nconst renderMissingSpecFileError = (error: MissingSpecFileError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" has no sibling spec; create \",\n formatPath(error.expectedSpecPath),\n \" and default-export a GroupSpec from it, or remove the impl.\",\n );\n\nconst renderSpecMissingDefaultGroupSpecError = (\n error: SpecMissingDefaultGroupSpecError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" must default-export a GroupSpec; build it with GroupSpec.make() or GroupSpec.makeNode().\",\n );\n\nconst renderSpecImportsServerError = (\n error: SpecImportsServerError,\n): string => {\n const importers = error.importerPaths.join(\", \");\n return singleLine(\n \"Spec \",\n formatPath(error.specPath),\n ` reaches a module that imports \\`@confect/server\\`: ${importers}. Spec modules are bundled into your client, so anything they import ships to the browser—move the server logic into a \\`*.impl.ts\\` module, or use \\`import type\\` if you only need the types.`,\n );\n};\n\nconst renderImplMissingSpecImportError = (\n error: ImplMissingSpecImportError,\n): string => {\n const stem = stemFromSpecPath(error.expectedSpecPath);\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not import its sibling spec; add \\`import ${stem} from \"./${stem}.spec.js\"\\` and pass it to FunctionImpl.make/GroupImpl.make.`,\n );\n};\n\nconst renderImplMissingDefaultLayerError = (\n error: ImplMissingDefaultLayerError,\n): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.\",\n );\n\nconst renderImplNotFinalizedError = (error: ImplNotFinalizedError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).\",\n );\n\nconst renderImplMissingFunctionsError = (\n error: ImplMissingFunctionsError,\n): string => {\n const names = error.missingFunctionNames.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every function declared by group \\`${error.groupPath}\\`; missing: ${names}. Add a \\`FunctionImpl.make\\` for each missing function and provide it to the group layer.`,\n );\n};\n\nconst renderImplMissingMiddlewareError = (\n error: ImplMissingMiddlewareError,\n): string => {\n const keys = error.missingMiddlewareKeys.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every middleware attached to group \\`${error.groupPath}\\`; missing: ${keys}. Provide a \\`MiddlewareImpl.make\\` (or \\`makeByFunctionType\\`/\\`provides\\`) layer for each missing middleware to the group layer.`,\n );\n};\n\nconst renderInvalidTableDefaultExportError = (\n error: InvalidTableDefaultExportError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n \" must default-export a Table (e.g. `export default Table.make({ ... })`); convert any named export to a default export.\",\n );\n\nconst renderInvalidTableFilenameError = (\n error: InvalidTableFilenameError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n ` has an invalid filename: ${error.reason} Convex table names must start with a letter and contain only letters, numbers, and underscores; leading underscores are reserved for system tables.`,\n );\n\nconst renderDuplicateTableNameError = (\n error: DuplicateTableNameError,\n): string => {\n const conflicts = error.collisions\n .map(\n ({ tableName, tablePaths }) =>\n `\\`${tableName}\\` (${tablePaths.join(\", \")})`,\n )\n .join(\"; \");\n return singleLine(\n `Multiple files under \\`confect/tables/\\` resolve to the same table name. Table names are derived from filenames, so each must be unique across the directory (including subdirectories); rename or remove all but one. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderConflictingDocNameError = (\n error: ConflictingDocNameError,\n): string => {\n const conflicts = pipe(\n error.collisions,\n Array.map(\n ({ docName, tableNames }) =>\n `\\`${docName}\\` (${Array.join(tableNames, \", \")})`,\n ),\n Array.join(\"; \"),\n );\n return singleLine(\n `Multiple tables fold to the same generated document type name. Table names are converted to PascalCase (so \\`user_profiles\\` and \\`userProfiles\\` both become \\`UserProfilesDoc\\`); rename all but one of each colliding group. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderInvalidConvexConfigError = (\n error: InvalidConvexConfigError,\n): string =>\n singleLine(\n \"Convex config \",\n formatPath(error.configPath),\n ` could not be evaluated: ${error.reason}`,\n );\n\nconst renderLegacySchemaFileError = (error: LegacySchemaFileError): string =>\n singleLine(\n \"Found a legacy \",\n formatPath(error.schemaPath),\n \". Delete it: tables in `confect/tables/*.ts` are now the single source of truth, and the runtime schema is generated as `confect/_generated/schema.ts`.\",\n );\n\nconst renderParentChildNameCollisionError = (\n error: ParentChildNameCollisionError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.parentSpecPath),\n ` declares a ${error.collisionKind} \\`${error.collisionName}\\` whose name collides with the sibling subdirectory spec `,\n formatPath(error.childSpecPath),\n `. Rename one of them so the assembled spec has a unique key at this path.`,\n );\n\n/**\n * Render any {@link CodegenError} into a styled, ready-to-print string.\n * Single-error variants render to a one-line `✘`-prefixed message;\n * `BundleFailedError` (the only multi-error variant) renders to a header plus\n * an esbuild diagnostic block.\n */\nexport const renderCodegenError = (error: CodegenError): string => {\n if (isBuildError(error)) return renderBuildError(error);\n // The renderer pipeline below is at Effect's pipe arity limit, so the\n // fork's errors render here.\n if (error._tag === \"ComponentNodeGroupError\") {\n return singleLine(\n `Group \"${error.groupPath}\" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`,\n );\n }\n if (error._tag === \"RemoveBusyError\") {\n return singleLine(\n \"Could not remove \",\n formatPath(error.path),\n ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`,\n );\n }\n if (error._tag === \"InvalidDeclarationError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"DeclarationKindMismatchError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` declares kind \"${error.declaredKind}\", but the target directory is kind \"${error.targetKind}\".`,\n );\n }\n if (error._tag === \"CallbackPrefixError\") {\n return singleLine(\n \"Callback contract \",\n `\"${error.contractId}\" in `,\n formatPath(error.declarationPath),\n ` must start with \"${error.componentName}/\" for component \"${error.componentName}\".`,\n );\n }\n if (error._tag === \"HandWrittenConvexFileError\") {\n return singleLine(\n \"Found a hand-written \",\n formatPath(error.convexPath),\n \". `confect codegen` writes it from \",\n formatPath(error.declarationPath),\n \" now; move its contents there and delete the file.\",\n );\n }\n return Match.value(error).pipe(\n Match.tag(\"SnapshotError\", ({ reason, relativePath, pathSegments }) =>\n singleLine(\n `Invalid generation metadata (${reason})`,\n relativePath === \"\" ? \"\" : ` for ${relativePath}`,\n pathSegments.length === 0 ? \".\" : ` at ${pathSegments.join(\"/\")}.`,\n ),\n ),\n Match.tag(\"MissingImplFileError\", renderMissingImplFileError),\n Match.tag(\"MissingSpecFileError\", renderMissingSpecFileError),\n Match.tag(\n \"SpecMissingDefaultGroupSpecError\",\n renderSpecMissingDefaultGroupSpecError,\n ),\n Match.tag(\"SpecImportsServerError\", renderSpecImportsServerError),\n Match.tag(\"InvalidMiddlewareAttachmentError\", (attachmentError) =>\n singleLine(\n \"Spec \",\n formatPath(attachmentError.specPath),\n `: ${attachmentError.message}`,\n ),\n ),\n Match.tag(\"ImplMissingSpecImportError\", renderImplMissingSpecImportError),\n Match.tag(\n \"ImplMissingDefaultLayerError\",\n renderImplMissingDefaultLayerError,\n ),\n Match.tag(\"ImplNotFinalizedError\", renderImplNotFinalizedError),\n Match.tag(\"ImplMissingFunctionsError\", renderImplMissingFunctionsError),\n Match.tag(\"ImplMissingMiddlewareError\", renderImplMissingMiddlewareError),\n Match.tag(\n \"ParentChildNameCollisionError\",\n renderParentChildNameCollisionError,\n ),\n Match.tag(\n \"InvalidTableDefaultExportError\",\n renderInvalidTableDefaultExportError,\n ),\n Match.tag(\"InvalidTableFilenameError\", renderInvalidTableFilenameError),\n Match.tag(\"DuplicateTableNameError\", renderDuplicateTableNameError),\n Match.tag(\"LegacySchemaFileError\", renderLegacySchemaFileError),\n Match.tag(\"ConflictingDocNameError\", renderConflictingDocNameError),\n Match.tag(\"InvalidConvexConfigError\", renderInvalidConvexConfigError),\n Match.exhaustive,\n );\n};\n\nexport const logCodegenError = (error: CodegenError) =>\n Console.error(renderCodegenError(error));\n\n// --- Effect combinators ---\n\n/**\n * Log any {@link CodegenError} thrown by `effect` and propagate the failure\n * unchanged so the caller's error channel is preserved.\n */\nexport const tapAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n effect.pipe(\n Effect.tapError((error) =>\n isCodegenError(error) ? logCodegenError(error) : Effect.void,\n ),\n );\n\n/**\n * Catch any {@link CodegenError} thrown by `effect`, log it, and resolve to\n * `Option.none()`. Success resolves to `Option.some(value)`.\n */\n// oxlint-disable effecttsgo/unsafe-effect-type-assertion -- catchIf removes the error variant selected by this refinement.\nexport const catchAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R> =>\n Effect.catchIf(Effect.map(effect, Option.some<A>), isCodegenError, (error) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n ) as Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R>;\n// oxlint-enable effecttsgo/unsafe-effect-type-assertion\n"],"mappings":";;;;;;;;;;;;AAcA,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,mCAAb,cAAsD,OAAO,YAA8C,CAAC,CAC1G,oCACA,EACE,UAAU,OAAO,OACnB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CACxE,mBACA;CAAE,MAAM,OAAO;CAAQ,UAAU,OAAO;CAAQ,OAAO,OAAO;AAAQ,CACxE,CAAC,CAAC,CAAC;AAEH,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CACxF,2BACA;CACE,UAAU,OAAO;CACjB,WAAW,OAAO;AACpB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,UAAU,OAAO;CACjB,eAAe,OAAO,MAAM,OAAO,MAAM;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,mCAAb,cAAsD,OAAO,YAA8C,CAAC,CAC1G,oCACA;CAAE,UAAU,OAAO;CAAQ,SAAS,OAAO;AAAO,CACpD,CAAC,CAAC,CAAC;AAEH,IAAa,6BAAb,cA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AI,6BAA6B,+BAA+B,GACtE,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,yBAAyB,2BAA2B,GAC9D,MAAM,IAAI,2BAA2B,6BAA6B,GAClE,MAAM,IAAI,4BAA4B,8BAA8B,GACpE,MAAM,UACR;AACF;AAEA,MAAa,mBAAmB,UAC9B,QAAQ,MAAM,mBAAmB,KAAK,CAAC;;;;;AAQzC,MAAa,aACX,WAEA,OAAO,KACL,OAAO,UAAU,UACf,eAAe,KAAK,IAAI,gBAAgB,KAAK,IAAI,OAAO,IAC1D,CACF"}
|
|
1
|
+
{"version":3,"file":"CodegenError.mjs","names":["Ansi.red"],"sources":["../src/CodegenError.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport { pipe } from \"effect/Function\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { BuildError, isBuildError } from \"./BuildError.js\";\nimport { SnapshotError } from \"./SnapshotError.js\";\nimport * as Ansi from \"./Ansi.js\";\nimport { formatPath, renderBuildError } from \"./log.js\";\n\n// --- Variants ---\n\nexport class MissingImplFileError extends Schema.TaggedError<MissingImplFileError>()(\n \"MissingImplFileError\",\n {\n specPath: Schema.String,\n expectedImplPath: Schema.String,\n },\n) {}\n\nexport class MissingSpecFileError extends Schema.TaggedError<MissingSpecFileError>()(\n \"MissingSpecFileError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class SpecMissingDefaultGroupSpecError extends Schema.TaggedError<SpecMissingDefaultGroupSpecError>()(\n \"SpecMissingDefaultGroupSpecError\",\n {\n specPath: Schema.String,\n },\n) {}\n\nexport class RemoveBusyError extends Schema.TaggedError<RemoveBusyError>()(\n \"RemoveBusyError\",\n { path: Schema.String, attempts: Schema.Finite, cause: Schema.Unknown },\n) {}\n\nexport class ComponentNodeGroupError extends Schema.TaggedError<ComponentNodeGroupError>()(\n \"ComponentNodeGroupError\",\n {\n specPath: Schema.String,\n groupPath: Schema.String,\n },\n) {}\n\nexport class SpecImportsServerError extends Schema.TaggedError<SpecImportsServerError>()(\n \"SpecImportsServerError\",\n {\n specPath: Schema.String,\n importerPaths: Schema.Array(Schema.String),\n },\n) {}\n\nexport class InvalidMiddlewareAttachmentError extends Schema.TaggedError<InvalidMiddlewareAttachmentError>()(\n \"InvalidMiddlewareAttachmentError\",\n { specPath: Schema.String, message: Schema.String },\n) {}\n\nexport class ImplMissingSpecImportError extends Schema.TaggedError<ImplMissingSpecImportError>()(\n \"ImplMissingSpecImportError\",\n {\n implPath: Schema.String,\n expectedSpecPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingDefaultLayerError extends Schema.TaggedError<ImplMissingDefaultLayerError>()(\n \"ImplMissingDefaultLayerError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplNotFinalizedError extends Schema.TaggedError<ImplNotFinalizedError>()(\n \"ImplNotFinalizedError\",\n {\n implPath: Schema.String,\n },\n) {}\n\nexport class ImplMissingFunctionsError extends Schema.TaggedError<ImplMissingFunctionsError>()(\n \"ImplMissingFunctionsError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingFunctionNames: Schema.Array(Schema.String),\n },\n) {}\n\nexport class ImplMissingMiddlewareError extends Schema.TaggedError<ImplMissingMiddlewareError>()(\n \"ImplMissingMiddlewareError\",\n {\n implPath: Schema.String,\n groupPath: Schema.String,\n missingMiddlewareKeys: Schema.Array(Schema.String),\n },\n) {}\n\nexport class RequiredMiddlewareError extends Schema.TaggedError<RequiredMiddlewareError>()(\n \"RequiredMiddlewareError\",\n {\n missing: Schema.Array(\n Schema.Struct({\n functionName: Schema.String,\n middlewareKey: Schema.String,\n }),\n ),\n },\n) {}\n\nexport class ParentChildNameCollisionError extends Schema.TaggedError<ParentChildNameCollisionError>()(\n \"ParentChildNameCollisionError\",\n {\n parentSpecPath: Schema.String,\n childSpecPath: Schema.String,\n collisionName: Schema.String,\n collisionKind: Schema.Literals([\"function\", \"group\"]),\n },\n) {}\n\nexport class InvalidTableDefaultExportError extends Schema.TaggedError<InvalidTableDefaultExportError>()(\n \"InvalidTableDefaultExportError\",\n {\n tablePath: Schema.String,\n },\n) {}\n\nexport class InvalidTableFilenameError extends Schema.TaggedError<InvalidTableFilenameError>()(\n \"InvalidTableFilenameError\",\n {\n tablePath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class DuplicateTableNameError extends Schema.TaggedError<DuplicateTableNameError>()(\n \"DuplicateTableNameError\",\n {\n // Every table name that more than one file resolves to, each paired with\n // the colliding file paths. All collisions are captured in a single pass\n // so the user can fix them together rather than re-running codegen once\n // per conflict.\n collisions: Schema.Array(\n Schema.Struct({\n tableName: Schema.String,\n tablePaths: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class LegacySchemaFileError extends Schema.TaggedError<LegacySchemaFileError>()(\n \"LegacySchemaFileError\",\n {\n schemaPath: Schema.String,\n },\n) {}\n\nexport class ConflictingDocNameError extends Schema.TaggedError<ConflictingDocNameError>()(\n \"ConflictingDocNameError\",\n {\n collisions: Schema.Array(\n Schema.Struct({\n docName: Schema.String,\n tableNames: Schema.Array(Schema.String),\n }),\n ),\n },\n) {}\n\nexport class InvalidConvexConfigError extends Schema.TaggedError<InvalidConvexConfigError>()(\n \"InvalidConvexConfigError\",\n {\n configPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class InvalidDeclarationError extends Schema.TaggedError<InvalidDeclarationError>()(\n \"InvalidDeclarationError\",\n {\n declarationPath: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class InvalidManifestSectionError extends Schema.TaggedError<InvalidManifestSectionError>()(\n \"InvalidManifestSectionError\",\n {\n sectionKey: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport class HandWrittenConvexFileError extends Schema.TaggedError<HandWrittenConvexFileError>()(\n \"HandWrittenConvexFileError\",\n {\n convexPath: Schema.String,\n declarationPath: Schema.String,\n },\n) {}\n\nexport class UnownedConvexEntrypointError extends Schema.TaggedError<UnownedConvexEntrypointError>()(\n \"UnownedConvexEntrypointError\",\n { filePaths: Schema.Array(Schema.String) },\n) {}\n\nexport class DeclarationKindMismatchError extends Schema.TaggedError<DeclarationKindMismatchError>()(\n \"DeclarationKindMismatchError\",\n {\n declarationPath: Schema.String,\n declaredKind: Schema.Literals([\"app\", \"component\"]),\n targetKind: Schema.Literals([\"app\", \"component\"]),\n },\n) {}\n\nexport class CallbackPrefixError extends Schema.TaggedError<CallbackPrefixError>()(\n \"CallbackPrefixError\",\n {\n declarationPath: Schema.String,\n contractId: Schema.String,\n componentName: Schema.String,\n },\n) {}\n\nexport const CodegenError = Schema.Union([\n SnapshotError,\n BuildError,\n MissingImplFileError,\n MissingSpecFileError,\n SpecMissingDefaultGroupSpecError,\n ComponentNodeGroupError,\n RemoveBusyError,\n SpecImportsServerError,\n InvalidMiddlewareAttachmentError,\n ImplMissingSpecImportError,\n ImplMissingDefaultLayerError,\n ImplNotFinalizedError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n RequiredMiddlewareError,\n ParentChildNameCollisionError,\n InvalidTableDefaultExportError,\n InvalidTableFilenameError,\n DuplicateTableNameError,\n LegacySchemaFileError,\n ConflictingDocNameError,\n InvalidConvexConfigError,\n InvalidDeclarationError,\n InvalidManifestSectionError,\n HandWrittenConvexFileError,\n UnownedConvexEntrypointError,\n DeclarationKindMismatchError,\n CallbackPrefixError,\n]);\nexport type CodegenError = typeof CodegenError.Type;\n\nexport const isCodegenError = (error: unknown): error is CodegenError => {\n if (isBuildError(error)) return true;\n return Schema.is(CodegenError)(error);\n};\n\n// --- Per-variant rendering ---\n\nconst cross = Ansi.red(\"✘\");\n\nconst stemFromSpecPath = (specPath: string): string => {\n const lastSep = Math.max(\n specPath.lastIndexOf(\"/\"),\n specPath.lastIndexOf(\"\\\\\"),\n );\n const basename = lastSep < 0 ? specPath : specPath.slice(lastSep + 1);\n return basename.endsWith(\".spec.ts\")\n ? basename.slice(0, -\".spec.ts\".length)\n : basename;\n};\n\nconst singleLine = (...parts: ReadonlyArray<string>): string =>\n `${cross} ${parts.join(\"\")}`;\n\nconst renderMissingImplFileError = (error: MissingImplFileError): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" has no sibling impl; create \",\n formatPath(error.expectedImplPath),\n \" and default-export a GroupImpl layer from it.\",\n );\n\nconst renderMissingSpecFileError = (error: MissingSpecFileError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" has no sibling spec; create \",\n formatPath(error.expectedSpecPath),\n \" and default-export a GroupSpec from it, or remove the impl.\",\n );\n\nconst renderSpecMissingDefaultGroupSpecError = (\n error: SpecMissingDefaultGroupSpecError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.specPath),\n \" must default-export a GroupSpec; build it with GroupSpec.make() or GroupSpec.makeNode().\",\n );\n\nconst renderSpecImportsServerError = (\n error: SpecImportsServerError,\n): string => {\n const importers = error.importerPaths.join(\", \");\n return singleLine(\n \"Spec \",\n formatPath(error.specPath),\n ` reaches a module that imports \\`@confect/server\\`: ${importers}. Spec modules are bundled into your client, so anything they import ships to the browser—move the server logic into a \\`*.impl.ts\\` module, or use \\`import type\\` if you only need the types.`,\n );\n};\n\nconst renderImplMissingSpecImportError = (\n error: ImplMissingSpecImportError,\n): string => {\n const stem = stemFromSpecPath(error.expectedSpecPath);\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not import its sibling spec; add \\`import ${stem} from \"./${stem}.spec.js\"\\` and pass it to FunctionImpl.make/GroupImpl.make.`,\n );\n};\n\nconst renderImplMissingDefaultLayerError = (\n error: ImplMissingDefaultLayerError,\n): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" must default-export a GroupImpl layer; wrap your handlers with `GroupImpl.make(databaseSchema, groupSpec).pipe(Layer.provide(...))` and `export default` it.\",\n );\n\nconst renderImplNotFinalizedError = (error: ImplNotFinalizedError): string =>\n singleLine(\n \"Impl \",\n formatPath(error.implPath),\n \" is not finalized; append `GroupImpl.finalize` to the end of the pipeline (e.g. `GroupImpl.make(databaseSchema, group).pipe(Layer.provide(...), GroupImpl.finalize)`).\",\n );\n\nconst renderImplMissingFunctionsError = (\n error: ImplMissingFunctionsError,\n): string => {\n const names = error.missingFunctionNames.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every function declared by group \\`${error.groupPath}\\`; missing: ${names}. Add a \\`FunctionImpl.make\\` for each missing function and provide it to the group layer.`,\n );\n};\n\nconst renderImplMissingMiddlewareError = (\n error: ImplMissingMiddlewareError,\n): string => {\n const keys = error.missingMiddlewareKeys.join(\", \");\n return singleLine(\n \"Impl \",\n formatPath(error.implPath),\n ` does not implement every middleware attached to group \\`${error.groupPath}\\`; missing: ${keys}. Provide a \\`MiddlewareImpl.make\\` (or \\`makeByFunctionType\\`/\\`provides\\`) layer for each missing middleware to the group layer.`,\n );\n};\n\nconst renderInvalidTableDefaultExportError = (\n error: InvalidTableDefaultExportError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n \" must default-export a Table (e.g. `export default Table.make({ ... })`); convert any named export to a default export.\",\n );\n\nconst renderInvalidTableFilenameError = (\n error: InvalidTableFilenameError,\n): string =>\n singleLine(\n \"Table \",\n formatPath(error.tablePath),\n ` has an invalid filename: ${error.reason} Convex table names must start with a letter and contain only letters, numbers, and underscores; leading underscores are reserved for system tables.`,\n );\n\nconst renderDuplicateTableNameError = (\n error: DuplicateTableNameError,\n): string => {\n const conflicts = error.collisions\n .map(\n ({ tableName, tablePaths }) =>\n `\\`${tableName}\\` (${tablePaths.join(\", \")})`,\n )\n .join(\"; \");\n return singleLine(\n `Multiple files under \\`confect/tables/\\` resolve to the same table name. Table names are derived from filenames, so each must be unique across the directory (including subdirectories); rename or remove all but one. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderConflictingDocNameError = (\n error: ConflictingDocNameError,\n): string => {\n const conflicts = pipe(\n error.collisions,\n Array.map(\n ({ docName, tableNames }) =>\n `\\`${docName}\\` (${Array.join(tableNames, \", \")})`,\n ),\n Array.join(\"; \"),\n );\n return singleLine(\n `Multiple tables fold to the same generated document type name. Table names are converted to PascalCase (so \\`user_profiles\\` and \\`userProfiles\\` both become \\`UserProfilesDoc\\`); rename all but one of each colliding group. Conflicts: ${conflicts}.`,\n );\n};\n\nconst renderInvalidConvexConfigError = (\n error: InvalidConvexConfigError,\n): string =>\n singleLine(\n \"Convex config \",\n formatPath(error.configPath),\n ` could not be evaluated: ${error.reason}`,\n );\n\nconst renderLegacySchemaFileError = (error: LegacySchemaFileError): string =>\n singleLine(\n \"Found a legacy \",\n formatPath(error.schemaPath),\n \". Delete it: tables in `confect/tables/*.ts` are now the single source of truth, and the runtime schema is generated as `confect/_generated/schema.ts`.\",\n );\n\nconst renderParentChildNameCollisionError = (\n error: ParentChildNameCollisionError,\n): string =>\n singleLine(\n \"Spec \",\n formatPath(error.parentSpecPath),\n ` declares a ${error.collisionKind} \\`${error.collisionName}\\` whose name collides with the sibling subdirectory spec `,\n formatPath(error.childSpecPath),\n `. Rename one of them so the assembled spec has a unique key at this path.`,\n );\n\n/**\n * Render any {@link CodegenError} into a styled, ready-to-print string.\n * Single-error variants render to a one-line `✘`-prefixed message;\n * `BundleFailedError` (the only multi-error variant) renders to a header plus\n * an esbuild diagnostic block.\n */\nexport const renderCodegenError = (error: CodegenError): string => {\n if (isBuildError(error)) return renderBuildError(error);\n // The renderer pipeline below is at Effect's pipe arity limit, so the\n // fork's errors render here.\n if (error._tag === \"ComponentNodeGroupError\") {\n return singleLine(\n `Group \"${error.groupPath}\" in ${error.specPath} uses the Node runtime. Convex components do not support Node.js functions.`,\n );\n }\n if (error._tag === \"RequiredMiddlewareError\") {\n return singleLine(\n \"Required middleware is missing:\\n\",\n error.missing\n .map(\n ({ functionName, middlewareKey }) =>\n `${functionName} requires middleware \"${middlewareKey}\"`,\n )\n .join(\"\\n\"),\n );\n }\n if (error._tag === \"RemoveBusyError\") {\n return singleLine(\n \"Could not remove \",\n formatPath(error.path),\n ` after ${error.attempts} attempts because it is busy. Close other tools using it and try again.`,\n );\n }\n if (error._tag === \"InvalidDeclarationError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"InvalidManifestSectionError\") {\n return singleLine(\n `Manifest section \"${error.sectionKey}\" is invalid: ${error.reason}`,\n );\n }\n if (error._tag === \"DeclarationKindMismatchError\") {\n return singleLine(\n \"Declaration \",\n formatPath(error.declarationPath),\n ` declares kind \"${error.declaredKind}\", but the target directory is kind \"${error.targetKind}\".`,\n );\n }\n if (error._tag === \"CallbackPrefixError\") {\n return singleLine(\n \"Callback contract \",\n `\"${error.contractId}\" in `,\n formatPath(error.declarationPath),\n ` must start with \"${error.componentName}/\" for component \"${error.componentName}\".`,\n );\n }\n if (error._tag === \"HandWrittenConvexFileError\") {\n return singleLine(\n \"Found a hand-written \",\n formatPath(error.convexPath),\n \". `confect codegen` writes it from \",\n formatPath(error.declarationPath),\n \" now; move its contents there and delete the file.\",\n );\n }\n if (error._tag === \"UnownedConvexEntrypointError\") {\n return singleLine(\n error.filePaths.map((file) => formatPath(file)).join(\", \"),\n error.filePaths.length === 1 ? \" was\" : \" were\",\n \" not written by confect codegen. Generated files only re-export the registry; put authored code outside convex/. If a file is stale generated output, delete it and run codegen again.\",\n );\n }\n return Match.value(error).pipe(\n Match.tag(\"SnapshotError\", ({ reason, relativePath, pathSegments }) =>\n singleLine(\n `Invalid generation metadata (${reason})`,\n relativePath === \"\" ? \"\" : ` for ${relativePath}`,\n pathSegments.length === 0 ? \".\" : ` at ${pathSegments.join(\"/\")}.`,\n ),\n ),\n Match.tag(\"MissingImplFileError\", renderMissingImplFileError),\n Match.tag(\"MissingSpecFileError\", renderMissingSpecFileError),\n Match.tag(\n \"SpecMissingDefaultGroupSpecError\",\n renderSpecMissingDefaultGroupSpecError,\n ),\n Match.tag(\"SpecImportsServerError\", renderSpecImportsServerError),\n Match.tag(\"InvalidMiddlewareAttachmentError\", (attachmentError) =>\n singleLine(\n \"Spec \",\n formatPath(attachmentError.specPath),\n `: ${attachmentError.message}`,\n ),\n ),\n Match.tag(\"ImplMissingSpecImportError\", renderImplMissingSpecImportError),\n Match.tag(\n \"ImplMissingDefaultLayerError\",\n renderImplMissingDefaultLayerError,\n ),\n Match.tag(\"ImplNotFinalizedError\", renderImplNotFinalizedError),\n Match.tag(\"ImplMissingFunctionsError\", renderImplMissingFunctionsError),\n Match.tag(\"ImplMissingMiddlewareError\", renderImplMissingMiddlewareError),\n Match.tag(\n \"ParentChildNameCollisionError\",\n renderParentChildNameCollisionError,\n ),\n Match.tag(\n \"InvalidTableDefaultExportError\",\n renderInvalidTableDefaultExportError,\n ),\n Match.tag(\"InvalidTableFilenameError\", renderInvalidTableFilenameError),\n Match.tag(\"DuplicateTableNameError\", renderDuplicateTableNameError),\n Match.tag(\"LegacySchemaFileError\", renderLegacySchemaFileError),\n Match.tag(\"ConflictingDocNameError\", renderConflictingDocNameError),\n Match.tag(\"InvalidConvexConfigError\", renderInvalidConvexConfigError),\n Match.exhaustive,\n );\n};\n\nexport const logCodegenError = (error: CodegenError) =>\n Console.error(renderCodegenError(error));\n\n// --- Effect combinators ---\n\n/**\n * Log any {@link CodegenError} thrown by `effect` and propagate the failure\n * unchanged so the caller's error channel is preserved.\n */\nexport const tapAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n effect.pipe(\n Effect.tapError((error) =>\n isCodegenError(error) ? logCodegenError(error) : Effect.void,\n ),\n );\n\n/**\n * Catch any {@link CodegenError} thrown by `effect`, log it, and resolve to\n * `Option.none()`. Success resolves to `Option.some(value)`.\n */\n// oxlint-disable effecttsgo/unsafe-effect-type-assertion -- catchIf removes the error variant selected by this refinement.\nexport const catchAndLog = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R> =>\n Effect.catchIf(Effect.map(effect, Option.some<A>), isCodegenError, (error) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n ) as Effect.Effect<Option.Option<A>, Exclude<E, CodegenError>, R>;\n// oxlint-enable effecttsgo/unsafe-effect-type-assertion\n"],"mappings":";;;;;;;;;;;;AAcA,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,mCAAb,cAAsD,OAAO,YAA8C,CAAC,CAC1G,oCACA,EACE,UAAU,OAAO,OACnB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CACxE,mBACA;CAAE,MAAM,OAAO;CAAQ,UAAU,OAAO;CAAQ,OAAO,OAAO;AAAQ,CACxE,CAAC,CAAC,CAAC;AAEH,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CACxF,2BACA;CACE,UAAU,OAAO;CACjB,WAAW,OAAO;AACpB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,UAAU,OAAO;CACjB,eAAe,OAAO,MAAM,OAAO,MAAM;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,mCAAb,cAAsD,OAAO,YAA8C,CAAC,CAC1G,oCACA;CAAE,UAAU,OAAO;CAAQ,SAAS,OAAO;AAAO,CACpD,CAAC,CAAC,CAAC;AAEH,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA;CACE,UAAU,OAAO;CACjB,kBAAkB,OAAO;AAC3B,CACF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