@gaganref/confect-cli 10.3.1-fork.95 → 10.6.0-fork.1

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.
Files changed (98) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/Ansi.mjs +1 -2
  3. package/dist/BuildError.mjs +5 -5
  4. package/dist/BuildError.mjs.map +1 -1
  5. package/dist/Bundler.mjs +103 -76
  6. package/dist/Bundler.mjs.map +1 -1
  7. package/dist/CodeBlockWriter.mjs +1 -2
  8. package/dist/CodegenError.mjs +27 -17
  9. package/dist/CodegenError.mjs.map +1 -1
  10. package/dist/ConfectDirectory.mjs +8 -3
  11. package/dist/ConfectDirectory.mjs.map +1 -1
  12. package/dist/ConvexConfig.mjs +23 -15
  13. package/dist/ConvexConfig.mjs.map +1 -1
  14. package/dist/ConvexDirectory.mjs +6 -4
  15. package/dist/ConvexDirectory.mjs.map +1 -1
  16. package/dist/Declaration.mjs +92 -56
  17. package/dist/Declaration.mjs.map +1 -1
  18. package/dist/DirectoryOptions.mjs +13 -8
  19. package/dist/DirectoryOptions.mjs.map +1 -1
  20. package/dist/DocName.mjs +1 -2
  21. package/dist/EntryPoint.mjs +17 -15
  22. package/dist/EntryPoint.mjs.map +1 -1
  23. package/dist/Evaluation.mjs +24 -13
  24. package/dist/Evaluation.mjs.map +1 -1
  25. package/dist/EvaluationWorker.mjs +5 -6
  26. package/dist/EvaluationWorker.mjs.map +1 -1
  27. package/dist/FunctionModule.mjs +85 -47
  28. package/dist/FunctionModule.mjs.map +1 -1
  29. package/dist/FunctionPath.mjs +1 -2
  30. package/dist/FunctionPath.mjs.map +1 -1
  31. package/dist/FunctionPaths.mjs +2 -3
  32. package/dist/GenerationSnapshot.mjs +30 -22
  33. package/dist/GenerationSnapshot.mjs.map +1 -1
  34. package/dist/GroupPath.mjs +6 -3
  35. package/dist/GroupPath.mjs.map +1 -1
  36. package/dist/GroupPaths.mjs +1 -2
  37. package/dist/ImplModulePath.mjs +1 -2
  38. package/dist/Json.mjs +13 -0
  39. package/dist/Json.mjs.map +1 -0
  40. package/dist/LeafModule.mjs +121 -41
  41. package/dist/LeafModule.mjs.map +1 -1
  42. package/dist/ManifestSections.mjs +23 -19
  43. package/dist/ManifestSections.mjs.map +1 -1
  44. package/dist/PackageSelfReference.mjs +32 -0
  45. package/dist/PackageSelfReference.mjs.map +1 -0
  46. package/dist/ProjectRoot.mjs +11 -3
  47. package/dist/ProjectRoot.mjs.map +1 -1
  48. package/dist/RelativeModulePath.mjs +1 -2
  49. package/dist/Remove.mjs +2 -3
  50. package/dist/Remove.mjs.map +1 -1
  51. package/dist/RestoreWatcher.mjs +1 -2
  52. package/dist/Rollback.mjs +7 -6
  53. package/dist/Rollback.mjs.map +1 -1
  54. package/dist/SectionFiles.mjs +77 -48
  55. package/dist/SectionFiles.mjs.map +1 -1
  56. package/dist/SnapshotError.mjs +3 -3
  57. package/dist/SnapshotError.mjs.map +1 -1
  58. package/dist/SpecAssemblyNode.mjs +1 -2
  59. package/dist/SpecModulePath.mjs +4 -4
  60. package/dist/SpecModulePath.mjs.map +1 -1
  61. package/dist/SyncState.mjs +3 -4
  62. package/dist/SyncState.mjs.map +1 -1
  63. package/dist/TableModule.mjs +18 -10
  64. package/dist/TableModule.mjs.map +1 -1
  65. package/dist/TableModulePath.mjs +3 -3
  66. package/dist/TableModulePath.mjs.map +1 -1
  67. package/dist/TypeScriptConfig.mjs +135 -0
  68. package/dist/TypeScriptConfig.mjs.map +1 -0
  69. package/dist/WatchBuild.mjs +107 -32
  70. package/dist/WatchBuild.mjs.map +1 -1
  71. package/dist/WatchGraph.mjs +4 -4
  72. package/dist/WatchGraph.mjs.map +1 -1
  73. package/dist/WatchTopology.mjs +5 -4
  74. package/dist/WatchTopology.mjs.map +1 -1
  75. package/dist/Watcher.mjs +179 -108
  76. package/dist/Watcher.mjs.map +1 -1
  77. package/dist/cliApp.mjs +5 -3
  78. package/dist/cliApp.mjs.map +1 -1
  79. package/dist/confect/codegen.mjs +95 -53
  80. package/dist/confect/codegen.mjs.map +1 -1
  81. package/dist/confect/declaration.mjs +76 -42
  82. package/dist/confect/declaration.mjs.map +1 -1
  83. package/dist/confect/dev.mjs +18 -12
  84. package/dist/confect/dev.mjs.map +1 -1
  85. package/dist/confect.mjs +4 -2
  86. package/dist/confect.mjs.map +1 -1
  87. package/dist/index.mjs +1 -2
  88. package/dist/log.mjs +13 -5
  89. package/dist/log.mjs.map +1 -1
  90. package/dist/package.json.mjs +5 -0
  91. package/dist/package.json.mjs.map +1 -0
  92. package/dist/templates.mjs +34 -22
  93. package/dist/templates.mjs.map +1 -1
  94. package/dist/utils.mjs +36 -5
  95. package/dist/utils.mjs.map +1 -1
  96. package/package.json +10 -10
  97. package/dist/package.mjs +0 -6
  98. package/dist/package.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,83 @@
1
1
  # @confect/cli
2
2
 
3
+ ## 10.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - d685126: Add `GroupSpec.make({ experimental_reuseContext: true })` to opt a group's queries and mutations into Convex's experimental V8 context reuse through `confect codegen` and `confect dev`. Reuse is disabled by default, does not apply to actions or child groups, and requires auditing module-level state for safety across calls and users.
8
+ - d087214: Add `MutationAuth.signJwt()` for signing deployment JWTs in mutations and mutation-only middleware, and export `MutationAuth` from generated services. Add `TestConfect.jwks()` to verify test-issued tokens with the same test instance's public keys.
9
+
10
+ ### Patch Changes
11
+
12
+ - f8d47d9: Allow `@confect/cli` to use `bundle-require` 5.0.0 and `code-block-writer` 13.0.2 without changing its upper compatibility bounds.
13
+
14
+ ## 10.5.0
15
+
16
+ ### Minor Changes
17
+
18
+ - 3ff40bb: Fix `confect codegen` and `confect dev` failing to start with Effect 4.1, and preserve dependency tracking and build warnings on Windows. Upgrade `effect` to `~4.1.0` alongside the CLI; the CLI's Effect and `@effect/platform-node` ranges now admit only 4.1.x releases because they use APIs that may break between minor versions.
19
+
20
+ ## 10.4.1
21
+
22
+ No changes in this release.
23
+
24
+ ## 10.4.0
25
+
26
+ ### Minor Changes
27
+
28
+ - 4ac364f: Add the generated `DocumentIds` service for queries and mutations: `parse` validates a string for a specific table, and `identify` discovers its table among known application and public system tables.
29
+
30
+ Each operation returns an `Option` inside an Effect. Both accept only IDs already in their canonical format; neither fetches a document nor proves that it exists.
31
+
32
+ Import the service from your generated services module. Use `parse` when you expect the input to be an ID for a particular table:
33
+
34
+ ```ts
35
+ import * as Effect from "effect/Effect";
36
+ import { DocumentIds } from "./confect/_generated/services";
37
+
38
+ const parseNoteId = (input: string) =>
39
+ Effect.gen(function* () {
40
+ const documentIds = yield* DocumentIds;
41
+ return yield* documentIds.parse("notes", input);
42
+ });
43
+ ```
44
+
45
+ Use `identify` when you do not know the table. Match the result to handle an unrecognized ID or use the identified table and ID:
46
+
47
+ ```ts
48
+ import * as Effect from "effect/Effect";
49
+ import * as Option from "effect/Option";
50
+ import { DocumentIds } from "./confect/_generated/services";
51
+
52
+ const describeDocumentId = (input: string) =>
53
+ Effect.gen(function* () {
54
+ const documentIds = yield* DocumentIds;
55
+ const identifiedId = yield* documentIds.identify(input);
56
+
57
+ return Option.match(identifiedId, {
58
+ onNone: () => "No known table matches this ID",
59
+ onSome: (matchedId) => `${matchedId.table}: ${matchedId.id}`,
60
+ });
61
+ });
62
+ ```
63
+
64
+ ### Patch Changes
65
+
66
+ - 64c35ab: Fix the 10.3.2 code-generation performance regression affecting `confect codegen` and `confect dev`.
67
+
68
+ Restart `confect dev` manually after changing TypeScript configuration, package metadata, or installed dependencies. Ordinary source edits continue to update automatically.
69
+
70
+ Resolve `${configDir}` path aliases consistently with TypeScript when `..` follows a wildcard. For example, with `"@/*": ["${configDir}/fixtures/*/../value.ts"]`, an import of `@/a/b` resolves to `fixtures/value.ts`, not `fixtures/a/value.ts`.
71
+
72
+ ## 10.3.2
73
+
74
+ ### Patch Changes
75
+
76
+ - 99c572e: Fix repeated regeneration in `confect dev` when TypeScript files are imported through both relative paths and package self-references, and preserve self-reference `import` and `require` export conditions during code generation.
77
+ - 7df4f68: Keep module resolution and inherited TypeScript configuration consistent between `confect codegen` and `confect dev`. Restart `confect dev` automatically when configuration or dependency-resolution inputs change, while keeping ordinary source edits incremental and avoiding regeneration for unchanged inputs. Reduce entry-file resolution overhead in both commands and verification overhead for dev updates without missing dependency or configuration changes.
78
+
79
+ Fix `${configDir}` aliases with wildcard matches followed by `..` so they resolve to the matched directory's parent.
80
+
3
81
  ## 10.3.1
4
82
 
5
83
  ### Patch Changes
package/dist/Ansi.mjs CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/Ansi.ts
1
+ // src/Ansi.ts
2
2
  /**
3
3
  * Minimal ANSI styling helpers for CLI output (Effect's own ANSI helpers in
4
4
  * `effect/cli` are internal). Styles are functions from text to a styled string
@@ -12,7 +12,6 @@ const green = style(32);
12
12
  const yellow = style(33);
13
13
  const magenta = style(35);
14
14
  const blackBright = style(90);
15
- //#endregion
16
15
  export { blackBright, green, magenta, red, yellow };
17
16
 
18
17
  //# sourceMappingURL=Ansi.mjs.map
@@ -1,5 +1,6 @@
1
+ import * as Array from "effect/Array";
1
2
  import * as Schema from "effect/Schema";
2
- //#region src/BuildError.ts
3
+ // src/BuildError.ts
3
4
  var BundleFailedError = class extends Schema.TaggedError()("BundleFailedError", {
4
5
  file: Schema.String,
5
6
  errors: Schema.Array(Schema.Unknown)
@@ -16,15 +17,14 @@ const isBuildError = (error) => Schema.is(BuildError)(error);
16
17
  * render it) before reaching a user-surface boundary.
17
18
  */
18
19
  var BundlerError = class extends Schema.TaggedError()("BundlerError", { cause: Schema.Unknown }) {};
19
- const isEsbuildBuildFailure = (error) => typeof error === "object" && error !== null && "errors" in error && globalThis.Array.isArray(error.errors);
20
- const fromBundlerError = (file, error) => isEsbuildBuildFailure(error.cause) ? new BundleFailedError({
20
+ const isEsbuildBuildFailure = (error) => typeof error === "object" && error !== null && "errors" in error && Array.isArray(error.errors);
21
+ const fromBundlerError = (file, error) => isEsbuildBuildFailure(error.cause) ? BundleFailedError.make({
21
22
  file,
22
23
  errors: error.cause.errors
23
- }) : new ImportFailedError({
24
+ }) : ImportFailedError.make({
24
25
  file,
25
26
  cause: error.cause
26
27
  });
27
- //#endregion
28
28
  export { BuildError, BundleFailedError, BundlerError, ImportFailedError, fromBundlerError, isBuildError };
29
29
 
30
30
  //# sourceMappingURL=BuildError.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BuildError.mjs","names":[],"sources":["../src/BuildError.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport type * as esbuild from \"esbuild\";\n\n// --- Variants ---\n\nexport class BundleFailedError extends Schema.TaggedError<BundleFailedError>()(\n \"BundleFailedError\",\n {\n file: Schema.String,\n errors: Schema.Array(Schema.Unknown),\n },\n) {}\n\nexport class ImportFailedError extends Schema.TaggedError<ImportFailedError>()(\n \"ImportFailedError\",\n {\n file: Schema.String,\n cause: Schema.Unknown,\n },\n) {}\n\nexport const BuildError = Schema.Union([BundleFailedError, ImportFailedError]);\nexport type BuildError = typeof BuildError.Type;\n\nexport const isBuildError = (error: unknown): error is BuildError =>\n Schema.is(BuildError)(error);\n\n// --- Bundler adapter ---\n\n/**\n * Internal failure produced by the esbuild bundle/import pipeline. Always\n * remapped to a {@link BuildError} (which carries enough context for the CLI to\n * render it) before reaching a user-surface boundary.\n */\nexport class BundlerError extends Schema.TaggedError<BundlerError>()(\n \"BundlerError\",\n {\n cause: Schema.Unknown,\n },\n) {}\n\nconst isEsbuildBuildFailure = (error: unknown): error is esbuild.BuildFailure =>\n typeof error === \"object\" &&\n error !== null &&\n \"errors\" in error &&\n globalThis.Array.isArray((error as esbuild.BuildFailure).errors);\n\nexport const fromBundlerError = (\n file: string,\n error: BundlerError,\n): BuildError =>\n isEsbuildBuildFailure(error.cause)\n ? new BundleFailedError({ file, errors: error.cause.errors })\n : new ImportFailedError({ file, cause: error.cause });\n"],"mappings":";;AAKA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,MAAM,OAAO;CACb,QAAQ,OAAO,MAAM,OAAO,OAAO;AACrC,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,MAAM,OAAO;CACb,OAAO,OAAO;AAChB,CACF,CAAC,CAAC,CAAC;AAEH,MAAa,aAAa,OAAO,MAAM,CAAC,mBAAmB,iBAAiB,CAAC;AAG7E,MAAa,gBAAgB,UAC3B,OAAO,GAAG,UAAU,CAAC,CAAC,KAAK;;;;;;AAS7B,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAClE,gBACA,EACE,OAAO,OAAO,QAChB,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,yBAAyB,UAC7B,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,WAAW,MAAM,QAAS,MAA+B,MAAM;AAEjE,MAAa,oBACX,MACA,UAEA,sBAAsB,MAAM,KAAK,IAC7B,IAAI,kBAAkB;CAAE;CAAM,QAAQ,MAAM,MAAM;AAAO,CAAC,IAC1D,IAAI,kBAAkB;CAAE;CAAM,OAAO,MAAM;AAAM,CAAC"}
1
+ {"version":3,"file":"BuildError.mjs","names":[],"sources":["../src/BuildError.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Schema from \"effect/Schema\";\nimport type * as esbuild from \"esbuild\";\n\n// --- Variants ---\n\nexport class BundleFailedError extends Schema.TaggedError<\n BundleFailedError,\n { readonly brand: unique symbol }\n>()(\"BundleFailedError\", {\n file: Schema.String,\n errors: Schema.Array(Schema.Unknown),\n}) {}\n\nexport class ImportFailedError extends Schema.TaggedError<\n ImportFailedError,\n { readonly brand: unique symbol }\n>()(\"ImportFailedError\", {\n file: Schema.String,\n cause: Schema.Unknown,\n}) {}\n\nexport const BuildError = Schema.Union([BundleFailedError, ImportFailedError]);\nexport type BuildError = typeof BuildError.Type;\n\nexport const isBuildError = (error: unknown): error is BuildError =>\n Schema.is(BuildError)(error);\n\n// --- Bundler adapter ---\n\n/**\n * Internal failure produced by the esbuild bundle/import pipeline. Always\n * remapped to a {@link BuildError} (which carries enough context for the CLI to\n * render it) before reaching a user-surface boundary.\n */\nexport class BundlerError extends Schema.TaggedError<\n BundlerError,\n { readonly brand: unique symbol }\n>()(\"BundlerError\", {\n cause: Schema.Unknown,\n}) {}\n\nconst isEsbuildBuildFailure = (error: unknown): error is esbuild.BuildFailure =>\n typeof error === \"object\" &&\n error !== null &&\n \"errors\" in error &&\n Array.isArray((error as esbuild.BuildFailure).errors);\n\nexport const fromBundlerError = (\n file: string,\n error: BundlerError,\n): BuildError =>\n isEsbuildBuildFailure(error.cause)\n ? BundleFailedError.make({ file, errors: error.cause.errors })\n : ImportFailedError.make({ file, cause: error.cause });\n"],"mappings":";;;AAMA,IAAa,oBAAb,cAAuC,OAAO,YAG5C,CAAC,CAAC,qBAAqB;CACvB,MAAM,OAAO;CACb,QAAQ,OAAO,MAAM,OAAO,OAAO;AACrC,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,oBAAb,cAAuC,OAAO,YAG5C,CAAC,CAAC,qBAAqB;CACvB,MAAM,OAAO;CACb,OAAO,OAAO;AAChB,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAa,aAAa,OAAO,MAAM,CAAC,mBAAmB,iBAAiB,CAAC;AAG7E,MAAa,gBAAgB,UAC3B,OAAO,GAAG,UAAU,CAAC,CAAC,KAAK;;;;;;AAS7B,IAAa,eAAb,cAAkC,OAAO,YAGvC,CAAC,CAAC,gBAAgB,EAClB,OAAO,OAAO,QAChB,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAM,yBAAyB,UAC7B,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,MAAM,QAAS,MAA+B,MAAM;AAEtD,MAAa,oBACX,MACA,UAEA,sBAAsB,MAAM,KAAK,IAC7B,kBAAkB,KAAK;CAAE;CAAM,QAAQ,MAAM,MAAM;AAAO,CAAC,IAC3D,kBAAkB,KAAK;CAAE;CAAM,OAAO,MAAM;AAAM,CAAC"}
package/dist/Bundler.mjs CHANGED
@@ -1,17 +1,19 @@
1
1
  import { BundlerError } from "./BuildError.mjs";
2
2
  import { logCoalescedBuildWarnings } from "./log.mjs";
3
+ import { discover } from "./PackageSelfReference.mjs";
4
+ import { aliasPatterns, buildOptions, discover as discover$1 } from "./TypeScriptConfig.mjs";
3
5
  import { createRequire, isBuiltin } from "node:module";
4
6
  import * as Effect from "effect/Effect";
5
7
  import * as FileSystem from "effect/FileSystem";
6
8
  import * as Path from "effect/Path";
7
9
  import * as Array from "effect/Array";
8
- import { identity, pipe } from "effect/Function";
10
+ import { constUndefined, identity, pipe } from "effect/Function";
9
11
  import * as HashSet from "effect/HashSet";
10
12
  import * as Option from "effect/Option";
11
13
  import * as Record from "effect/Record";
12
14
  import { pathToFileURL } from "node:url";
13
15
  import { parseArgs } from "node:util";
14
- import { JS_EXT_RE, bundleRequire, dynamicImport, injectFileScopePlugin, loadTsConfig, tsconfigPathsToRegExp } from "bundle-require";
16
+ import * as BundleRequire from "bundle-require";
15
17
  import { resolveModulePath } from "exsolve";
16
18
  import * as Chunk from "effect/Chunk";
17
19
  import * as Cause from "effect/Cause";
@@ -24,7 +26,7 @@ import * as Scope from "effect/Scope";
24
26
  import * as Schema from "effect/Schema";
25
27
  import * as String from "effect/String";
26
28
  import * as esbuild from "esbuild";
27
- //#region src/Bundler.ts
29
+ // src/Bundler.ts
28
30
  /**
29
31
  * `bundle-require` sets `absWorkingDir: cwd` on the underlying esbuild build,
30
32
  * so the metafile's input keys (and each input's `imports[].path`) are stored
@@ -40,28 +42,36 @@ import * as esbuild from "esbuild";
40
42
  * {@link importersOfPackage} relies on `original` always being the raw
41
43
  * specifier.
42
44
  */
43
- const absolutizeMetafile = (path, metafile, cwd) => {
45
+ const absolutizeMetafile = (path, metafile, cwd, inputPaths) => {
44
46
  const absolutize = (p) => path.resolve(cwd, p);
47
+ const inputPath = (p) => inputPaths.get(absolutize(p)) ?? absolutize(p);
45
48
  return {
46
- inputs: Record.mapEntries(metafile.inputs, (value, key) => [absolutize(key), {
49
+ inputs: Record.mapEntries(metafile.inputs, (value, key) => [inputPath(key), {
47
50
  ...value,
48
51
  imports: Array.map(value.imports, (i) => ({
49
52
  ...i,
50
- path: absolutize(i.path),
53
+ path: inputPath(i.path),
51
54
  original: i.original ?? i.path
52
55
  }))
53
56
  }]),
54
57
  outputs: Record.mapEntries(metafile.outputs, (value, key) => [absolutize(key), {
55
58
  ...value,
56
- ...value.entryPoint ? { entryPoint: absolutize(value.entryPoint) } : {},
57
- inputs: Record.mapKeys(value.inputs, absolutize),
58
- imports: Array.map(value.imports, (imported) => imported.external ? imported : {
59
+ ...value.entryPoint !== void 0 && value.entryPoint !== "" ? { entryPoint: inputPath(value.entryPoint) } : {},
60
+ inputs: Record.mapKeys(value.inputs, inputPath),
61
+ imports: Array.map(value.imports, (imported) => imported.external === true ? imported : {
59
62
  ...imported,
60
63
  path: absolutize(imported.path)
61
64
  })
62
65
  }])
63
66
  };
64
67
  };
68
+ const canonicalInputPaths = Effect.fnUntraced(function* (path, fs, metafile, cwd) {
69
+ const inputPaths = yield* Effect.forEach(Record.keys(metafile.inputs), (input) => {
70
+ const absolute = path.resolve(cwd, input);
71
+ return fs.realPath(absolute).pipe(Effect.orElseSucceed(() => absolute), Effect.map((real) => [absolute, real]));
72
+ });
73
+ return new Map(inputPaths);
74
+ });
65
75
  const resolveEsm = Option.liftThrowable((specifier, importer) => resolveModulePath(specifier, {
66
76
  from: importer,
67
77
  conditions: ["node", "import"]
@@ -91,8 +101,8 @@ const exportNames = (file) => Effect.tryPromise({
91
101
  logLevel: "silent",
92
102
  outdir: "out"
93
103
  }),
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))));
104
+ catch: (cause) => BundlerError.make({ cause })
105
+ }).pipe(Effect.map(({ metafile, outputFiles }) => Array.some(Record.values(metafile.inputs), ({ format }) => format === "cjs") || Array.some(outputFiles, ({ text }) => /^export \* from /m.test(text)) ? Option.none() : Option.some(Array.flatMap(Record.values(metafile.outputs), ({ exports }) => exports))));
96
106
  /**
97
107
  * Bundles first-party workspace dependencies that `bundle-require` would
98
108
  * otherwise externalize and hand to Node's native ESM resolver. Resolves each
@@ -100,16 +110,19 @@ const exportNames = (file) => Effect.tryPromise({
100
110
  * outside `node_modules`—mirroring Vite's "linked dependencies are not
101
111
  * externalized" heuristic. Registered ahead of `externalPlugin`, so deferring
102
112
  * (returning `undefined`) leaves third-party externalization untouched.
103
- * `skipPatterns` are the tsconfig `paths` regexes, which keep deferring to
104
- * esbuild's own `paths` resolution.
113
+ * `skipPatterns` leave tsconfig `paths` aliases and package self-references to
114
+ * esbuild's native resolution.
115
+ *
116
+ * @internal
105
117
  */
106
118
  const bundleWorkspacePlugin = (path, fs, skipPatterns) => ({
107
119
  name: "confect:bundle-workspace",
108
120
  setup(build) {
121
+ const patterns = [...skipPatterns];
109
122
  build.onResolve({ filter: /^[^./]/ }, (args) => {
110
123
  if (args.namespace !== "file" && args.namespace !== "") return void 0;
111
124
  if (isBuiltin(args.path) || path.isAbsolute(args.path)) return void 0;
112
- if (Array.some(skipPatterns, (pattern) => pattern.test(args.path))) return;
125
+ if (BundleRequire.match(args.path, patterns)) return;
113
126
  const importer = args.importer !== "" ? args.importer : path.join(args.resolveDir, "_");
114
127
  return Option.match(resolveModule(args.path, importer), {
115
128
  onNone: () => ({
@@ -146,6 +159,7 @@ var Batch = class extends Context.Service()("@confect/cli/Bundler/Batch") {};
146
159
  const batchResolutionPlugin = (path, fs, skipPatterns, conditions, externalImports) => ({
147
160
  name: "confect:batch-resolution",
148
161
  setup(build) {
162
+ const patterns = [...skipPatterns];
149
163
  const external = (args, resolved) => {
150
164
  const importer = path.resolve(args.importer);
151
165
  Effect.runSync(Ref.update(externalImports, HashMap.modifyAt(importer, (imports) => Option.some(Array.append(Option.getOrElse(imports, () => []), {
@@ -163,9 +177,9 @@ const batchResolutionPlugin = (path, fs, skipPatterns, conditions, externalImpor
163
177
  path: args.path,
164
178
  external: true
165
179
  };
166
- if (Array.some(skipPatterns, (pattern) => pattern.test(args.path))) return void 0;
180
+ if (BundleRequire.match(args.path, patterns)) return void 0;
167
181
  if (/[\\/]node_modules[\\/]/.test(args.path)) return external(args, pathToFileURL(path.resolve(args.resolveDir, args.path)).href);
168
- if (args.path.startsWith(".") || path.isAbsolute(args.path)) return void 0;
182
+ if (String.startsWith(".")(args.path) || path.isAbsolute(args.path)) return void 0;
169
183
  const resolved = resolveModule(args.path, args.importer);
170
184
  if (Option.isNone(resolved)) return { errors: [{ text: `Could not resolve "${args.path}" from ${args.importer}` }] };
171
185
  return Effect.runPromise(fs.realPath(resolved.value).pipe(Effect.orElseSucceed(() => resolved.value))).then((real) => {
@@ -183,7 +197,7 @@ const compileBatch = Effect.fn("Bundler.compileBatch")(function* (entryPoints) {
183
197
  const path = yield* Path.Path;
184
198
  const fs = yield* FileSystem.FileSystem;
185
199
  const nodeOptions = yield* Config.String("NODE_OPTIONS").pipe(Config.withDefault(""));
186
- if (/--conditions|-C|--(?:no-)?addons/.test(nodeOptions)) return yield* new BatchIncompatible({
200
+ if (/--conditions|-C|--(?:no-)?addons/.test(nodeOptions)) return yield* BatchIncompatible.make({
187
201
  reason: "RuntimeConditions",
188
202
  message: "NODE_OPTIONS changes Node export conditions; individual builds preserve native resolution."
189
203
  });
@@ -201,29 +215,27 @@ const compileBatch = Effect.fn("Bundler.compileBatch")(function* (entryPoints) {
201
215
  strict: false,
202
216
  allowPositionals: true
203
217
  }).values,
204
- catch: (cause) => new BundlerError({ cause })
218
+ catch: (cause) => BundlerError.make({ cause })
205
219
  });
206
220
  const conditions = [
207
221
  "node",
208
222
  "import",
209
223
  ...process.features.require_module ? ["module-sync"] : [],
210
- ...runtimeOptions["no-addons"] ? [] : ["node-addons"],
211
- ...(runtimeOptions.conditions ?? []).filter((condition) => typeof condition === "string")
224
+ ...runtimeOptions["no-addons"] === true || typeof runtimeOptions["no-addons"] === "string" && runtimeOptions["no-addons"] !== "" ? [] : ["node-addons"],
225
+ ...Array.filter(runtimeOptions.conditions ?? [], (condition) => typeof condition === "string")
212
226
  ];
213
- const entries = Array.dedupe(entryPoints.map((entry) => path.resolve(entry)));
214
- const first = entries[0];
215
- if (first === void 0 || entries.some((entry) => !JS_EXT_RE.test(entry) || /[\\/]node_modules[\\/]/.test(entry))) return yield* new BatchIncompatible({
227
+ const entries = Array.dedupe(Array.map(entryPoints, (entry) => path.resolve(entry)));
228
+ if (!Array.isReadonlyArrayNonEmpty(entries) || !Array.every(entries, (entry) => BundleRequire.JS_EXT_RE.test(entry) && !/[\\/]node_modules[\\/]/.test(entry))) return yield* BatchIncompatible.make({
216
229
  reason: "UnsupportedEntries",
217
230
  message: "Shared builds require JavaScript or TypeScript entries outside node_modules."
218
231
  });
219
- const configs = yield* Effect.try({
220
- try: () => entries.map((entry) => loadTsConfig(path.dirname(entry))),
221
- catch: (cause) => new BundlerError({ cause })
222
- });
223
- const config = configs[0];
224
- if (configs.some((other) => other?.path !== config?.path)) return yield* new BatchIncompatible({
232
+ const first = Array.headNonEmpty(entries);
233
+ const configs = yield* Effect.forEach(Array.dedupe(Array.map(entries, path.dirname)), discover$1);
234
+ const config = Array.headNonEmpty(configs);
235
+ const configPath = (selected) => Option.getOrUndefined(Option.map(selected, (value) => value.path));
236
+ if (!Array.every(configs, (other) => configPath(other) === configPath(config))) return yield* BatchIncompatible.make({
225
237
  reason: "MixedTsconfigs",
226
- message: `Entries use different tsconfigs: ${Array.dedupe(configs.map((item) => item?.path ?? "(no tsconfig)")).join(", ")}`
238
+ message: `Entries use different tsconfigs: ${Array.join(Array.dedupe(Array.map(configs, (item) => configPath(item) ?? "(no tsconfig)")), ", ")}`
227
239
  });
228
240
  const cwd = yield* fs.realPath(path.dirname(first));
229
241
  const directory = yield* fs.makeTempDirectoryScoped({ prefix: "confect-batch-" }).pipe(Effect.flatMap((temporary) => fs.realPath(temporary)));
@@ -232,9 +244,11 @@ const compileBatch = Effect.fn("Bundler.compileBatch")(function* (entryPoints) {
232
244
  output: path.join(directory, `${index}.mjs`)
233
245
  }]));
234
246
  const externalImports = yield* Ref.make(HashMap.empty());
247
+ const discoveredSelfReferences = yield* Effect.forEach(Array.dedupe(Array.map(entries, path.dirname)), discover);
248
+ const selfReferences = Array.getSomes(discoveredSelfReferences);
235
249
  const result = yield* Effect.tryPromise({
236
250
  try: () => esbuild.build({
237
- entryPoints: entries.map((entry, index) => ({
251
+ entryPoints: Array.map(entries, (entry, index) => ({
238
252
  in: entry,
239
253
  out: `${index}`
240
254
  })),
@@ -250,26 +264,27 @@ const compileBatch = Effect.fn("Bundler.compileBatch")(function* (entryPoints) {
250
264
  metafile: true,
251
265
  write: false,
252
266
  logLevel: "silent",
253
- ...config?.path ? { tsconfig: config.path } : { tsconfigRaw: config?.data ?? {} },
254
- plugins: [batchResolutionPlugin(path, fs, tsconfigPathsToRegExp(config?.data.compilerOptions?.paths ?? {}), conditions, externalImports), injectFileScopePlugin()]
267
+ ...buildOptions(config),
268
+ plugins: [batchResolutionPlugin(path, fs, [...aliasPatterns(config), ...selfReferences], conditions, externalImports), BundleRequire.injectFileScopePlugin()]
255
269
  }),
256
- catch: (cause) => new BundlerError({ cause })
270
+ catch: (cause) => BundlerError.make({ cause })
257
271
  });
258
- const inputPaths = HashSet.fromIterable(Object.keys(result.metafile.inputs).map((input) => path.resolve(cwd, input)));
259
- const unattributedWarnings = result.warnings.filter((warning) => !warning.location || !HashSet.has(inputPaths, path.resolve(cwd, warning.location.file)));
260
- if (unattributedWarnings.length > 0) return yield* new BatchIncompatible({
272
+ const inputPaths = HashSet.fromIterable(Array.map(Record.keys(result.metafile.inputs), (input) => path.resolve(cwd, input)));
273
+ const unattributedWarnings = Array.filter(result.warnings, (warning) => warning.location === null || !HashSet.has(inputPaths, path.resolve(cwd, warning.location.file)));
274
+ if (unattributedWarnings.length > 0) return yield* BatchIncompatible.make({
261
275
  reason: "UnattributedWarnings",
262
- message: `Cannot attribute build warnings to entries: ${unattributedWarnings.map((warning) => warning.text).join("; ")}`
276
+ message: `Cannot attribute build warnings to entries: ${Array.join(Array.map(unattributedWarnings, (warning) => warning.text), "; ")}`
263
277
  });
264
278
  yield* Effect.forEach(result.outputFiles, (output) => fs.writeFile(output.path, output.contents));
265
279
  const capturedExternalImports = yield* Ref.get(externalImports);
266
- const inputs = Object.fromEntries(Object.entries(result.metafile.inputs).map(([input, metadata]) => {
280
+ const canonicalPaths = yield* canonicalInputPaths(path, fs, result.metafile, cwd);
281
+ const inputs = Record.fromEntries(Array.map(Record.toEntries(result.metafile.inputs), ([input, metadata]) => {
267
282
  const originals = Option.getOrElse(HashMap.get(capturedExternalImports, path.resolve(cwd, input)), () => []);
268
283
  return [input, {
269
284
  ...metadata,
270
- imports: metadata.imports.flatMap((imported) => {
271
- const matching = imported.external ? originals.filter((original) => original.path === imported.path) : [];
272
- return matching.length === 0 ? [imported] : matching.map((original) => Object.assign({}, imported, { original: original.original }));
285
+ imports: Array.flatMap(metadata.imports, (imported) => {
286
+ const matching = imported.external === true ? Array.filter(originals, (original) => original.path === imported.path) : [];
287
+ return matching.length === 0 ? [imported] : Array.map(matching, (original) => Object.assign({}, imported, { original: original.original }));
273
288
  })
274
289
  }];
275
290
  }));
@@ -278,7 +293,8 @@ const compileBatch = Effect.fn("Bundler.compileBatch")(function* (entryPoints) {
278
293
  metafile: absolutizeMetafile(path, {
279
294
  ...result.metafile,
280
295
  inputs
281
- }, cwd),
296
+ }, cwd, canonicalPaths),
297
+ inputPaths: canonicalPaths,
282
298
  warnings: result.warnings,
283
299
  cwd
284
300
  };
@@ -293,7 +309,7 @@ const compileBatch = Effect.fn("Bundler.compileBatch")(function* (entryPoints) {
293
309
  */
294
310
  const withBatch = (entryPoints, effect) => Effect.scopedWith((scope) => Effect.gen(function* () {
295
311
  const current = yield* Effect.serviceOption(Batch);
296
- if (Option.isSome(current) && entryPoints.every((entry) => current.value.entryPoints.includes(entry))) return yield* effect;
312
+ if (Option.isSome(current) && Array.every(entryPoints, (entry) => current.value.entryPoints.includes(entry))) return yield* effect;
297
313
  const compilation = yield* Effect.cached(compileBatch(entryPoints).pipe(Effect.provideService(Scope.Scope, scope), Effect.asSome, Effect.catchTag("BatchIncompatible", (error) => Effect.logDebug("Shared build skipped; falling back to individual builds.", {
298
314
  entryPoints,
299
315
  reason: error.reason,
@@ -307,7 +323,7 @@ const withBatch = (entryPoints, effect) => Effect.scopedWith((scope) => Effect.g
307
323
  compilation
308
324
  });
309
325
  }));
310
- const reachableMetafileEntries = (entries, root, resolveImport) => Object.fromEntries(pipe(Iterable.unfold({
326
+ const reachableMetafileEntries = (entries, root, resolveImport) => Record.fromEntries(pipe(Iterable.unfold({
311
327
  pending: Chunk.of(root),
312
328
  visited: HashSet.empty()
313
329
  }, ({ pending, visited }) => {
@@ -320,7 +336,7 @@ const reachableMetafileEntries = (entries, root, resolveImport) => Object.fromEn
320
336
  visited
321
337
  }]);
322
338
  return Option.some([Option.some([key, metadata]), {
323
- pending: Array.reduce(metadata.imports, remaining, (queue, imported) => imported.external ? queue : Chunk.append(queue, resolveImport(imported.path))),
339
+ pending: Array.reduce(metadata.imports, remaining, (queue, imported) => imported.external === true ? queue : Chunk.append(queue, resolveImport(imported.path))),
324
340
  visited: HashSet.add(visited, key)
325
341
  }]);
326
342
  }), Iterable.getSomes));
@@ -329,17 +345,13 @@ const entryMetafile = (path, compilation, source, output) => ({
329
345
  outputs: reachableMetafileEntries(compilation.metafile.outputs, output, (key) => path.resolve(compilation.cwd, key))
330
346
  });
331
347
  /**
332
- * Bundle a TypeScript entry point with esbuild via {@link bundleRequire} and
333
- * import the result. `bundle-require` writes a temp `.mjs` next to the source,
334
- * `import()`s it, and deletes it—so third-party `node_modules` externals
335
- * resolve through the user's normal `node_modules` walk, while first-party
336
- * workspace deps are bundled by {@link bundleWorkspacePlugin} and tsconfig
337
- * `paths` aliases stay inside the bundle.
338
- *
339
- * `cwd` is set to the entry's directory so `bundle-require`'s `tsconfig.json`
340
- * discovery (which walks upward from `cwd`) lands on the project's tsconfig
341
- * regardless of where `confect codegen` was invoked from, and so esbuild
342
- * resolves relative imports against the entry's location.
348
+ * Bundle a TypeScript entry point with esbuild via
349
+ * {@link BundleRequire.bundleRequire} and import the result. `bundle-require`
350
+ * writes a temp `.mjs` next to the source, `import()`s it, and deletes it—so
351
+ * third-party `node_modules` externals resolve through the user's normal
352
+ * `node_modules` walk, while first-party workspace deps are bundled by
353
+ * {@link bundleWorkspacePlugin} and tsconfig `paths` aliases stay inside the
354
+ * bundle.
343
355
  *
344
356
  * The returned pair carries both the imported module and the esbuild metafile
345
357
  * so callers can inspect the import graph (see {@link directlyImports}); the
@@ -351,21 +363,26 @@ const entryMetafile = (path, compilation, source, output) => ({
351
363
  * resolutions (e.g. `convex.config` imports) before the workspace and
352
364
  * externalization heuristics see them.
353
365
  */
354
- const bundle = Effect.fn("Bundler.bundle")(function* (entryPoint, options) {
366
+ const bundle = Effect.fn("Bundler.bundle")((entryPoint, options) => bundleWith(entryPoint, BundleRequire.dynamicImport, options));
367
+ const check = Effect.fn("Bundler.check")((entryPoint) => bundleWith(entryPoint).pipe(Effect.asVoid));
368
+ const bundleWith = Effect.fnUntraced(function* (entryPoint, load, options) {
355
369
  const path = yield* Path.Path;
356
370
  const fs = yield* FileSystem.FileSystem;
357
371
  const batch = yield* Effect.serviceOption(Batch);
358
- if (Option.isSome(batch) && !options?.plugins?.length && batch.value.entryPoints.some((entry) => path.resolve(entry) === path.resolve(entryPoint))) {
372
+ if (Option.isSome(batch) && (options?.plugins?.length ?? 0) === 0 && Array.some(batch.value.entryPoints, (entry) => path.resolve(entry) === path.resolve(entryPoint))) {
359
373
  const compilation = yield* batch.value.compilation;
360
374
  if (Option.isSome(compilation)) {
361
375
  const entry = HashMap.get(compilation.value.entries, path.resolve(entryPoint));
362
376
  if (Option.isSome(entry)) {
363
377
  const metafile = entryMetafile(path, compilation.value, entry.value.source, entry.value.output);
364
378
  return {
365
- module: yield* Effect.tryPromise({
366
- try: () => dynamicImport(pathToFileURL(entry.value.output).href, { format: "esm" }),
367
- catch: (cause) => new BundlerError({ cause })
368
- }).pipe(Effect.ensuring(logCoalescedBuildWarnings(compilation.value.warnings.filter((warning) => warning.location && metafile.inputs[path.resolve(compilation.value.cwd, warning.location.file)])))),
379
+ module: yield* Option.match(Option.fromUndefinedOr(load), {
380
+ onNone: () => Effect.void,
381
+ onSome: (loadModule) => Effect.tryPromise({
382
+ try: () => loadModule(pathToFileURL(entry.value.output).href, { format: "esm" }),
383
+ catch: (cause) => BundlerError.make({ cause })
384
+ })
385
+ }).pipe(Effect.ensuring(logCoalescedBuildWarnings(Array.filter(compilation.value.warnings, (warning) => warning.location !== null && metafile.inputs[compilation.value.inputPaths.get(path.resolve(compilation.value.cwd, warning.location.file)) ?? path.resolve(compilation.value.cwd, warning.location.file)] !== void 0)))),
369
386
  metafile
370
387
  };
371
388
  }
@@ -376,17 +393,27 @@ const bundle = Effect.fn("Bundler.bundle")(function* (entryPoint, options) {
376
393
  warnings: []
377
394
  });
378
395
  const cwd = path.dirname(entryPoint);
379
- const skipPatterns = yield* Effect.try({
380
- try: () => tsconfigPathsToRegExp(loadTsConfig(cwd)?.data.compilerOptions?.paths ?? {}),
381
- catch: (cause) => new BundlerError({ cause })
382
- });
396
+ const selfReference = yield* discover(cwd);
397
+ const selfReferences = Option.toArray(selfReference);
398
+ const config = yield* discover$1(cwd);
399
+ const skipPatterns = [...aliasPatterns(config), ...selfReferences];
383
400
  const result = yield* Effect.tryPromise({
384
- try: () => bundleRequire({
401
+ try: () => BundleRequire.bundleRequire({
385
402
  filepath: entryPoint,
403
+ require: load ?? constUndefined,
386
404
  cwd,
387
405
  format: "esm",
406
+ tsconfig: false,
407
+ notExternal: skipPatterns,
388
408
  esbuildOptions: {
389
409
  plugins: [
410
+ {
411
+ name: "confect:typescript-config",
412
+ setup(build) {
413
+ delete build.initialOptions.tsconfigRaw;
414
+ Object.assign(build.initialOptions, buildOptions(config));
415
+ }
416
+ },
390
417
  ...options?.plugins ?? [],
391
418
  bundleWorkspacePlugin(path, fs, skipPatterns),
392
419
  captureBuildResultPlugin(buildResultRef)
@@ -394,13 +421,14 @@ const bundle = Effect.fn("Bundler.bundle")(function* (entryPoint, options) {
394
421
  logLevel: "silent"
395
422
  }
396
423
  }),
397
- catch: (cause) => new BundlerError({ cause })
424
+ catch: (cause) => BundlerError.make({ cause })
398
425
  }).pipe(Effect.ensuring(Effect.andThen(Ref.get(buildResultRef), (captured) => logCoalescedBuildWarnings(captured.warnings))));
399
426
  const { metafile } = yield* Ref.get(buildResultRef);
400
- if (!metafile) return yield* Effect.die(/* @__PURE__ */ new Error("esbuild metafile missing"));
427
+ if (metafile === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("esbuild metafile missing"));
428
+ const inputPaths = yield* canonicalInputPaths(path, fs, metafile, cwd);
401
429
  return {
402
430
  module: result.mod,
403
- metafile: absolutizeMetafile(path, metafile, cwd)
431
+ metafile: absolutizeMetafile(path, metafile, cwd, inputPaths)
404
432
  };
405
433
  });
406
434
  const findMetafileInputKey = Effect.fnUntraced(function* (metafile, absolutePath) {
@@ -408,7 +436,7 @@ const findMetafileInputKey = Effect.fnUntraced(function* (metafile, absolutePath
408
436
  const resolved = path.resolve(absolutePath);
409
437
  if (metafile.inputs[resolved] !== void 0) return Option.some(resolved);
410
438
  const real = yield* (yield* FileSystem.FileSystem).realPath(resolved).pipe(Effect.orElseSucceed(() => resolved));
411
- return Array.findFirst(Object.keys(metafile.inputs), (key) => path.resolve(key) === real);
439
+ return Array.findFirst(Record.keys(metafile.inputs), (key) => path.resolve(key) === real);
412
440
  });
413
441
  /**
414
442
  * Returns `true` when the module bundled from `sourceAbsolutePath` declares a
@@ -421,7 +449,7 @@ const directlyImports = Effect.fnUntraced(function* (bundled, sourceAbsolutePath
421
449
  const targetKey = yield* findMetafileInputKey(bundled.metafile, targetAbsolutePath);
422
450
  return pipe(Option.all([sourceKey, targetKey]), Option.flatMap(([sourceKey_, targetKey_]) => Option.fromNullishOr(bundled.metafile.inputs[sourceKey_]).pipe(Option.map((sourceInput) => {
423
451
  const targetResolved = path.resolve(targetKey_);
424
- return sourceInput.imports.some((importedFile) => path.resolve(importedFile.path) === targetResolved);
452
+ return Array.some(sourceInput.imports, (importedFile) => path.resolve(importedFile.path) === targetResolved);
425
453
  }))), Option.getOrElse(() => false));
426
454
  });
427
455
  /**
@@ -439,9 +467,8 @@ const directlyImports = Effect.fnUntraced(function* (bundled, sourceAbsolutePath
439
467
  */
440
468
  const importersOfPackage = (bundled, packageName, where) => {
441
469
  const subpathPrefix = `${packageName}/`;
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);
470
+ return Array.map(Array.filter(Record.toEntries(bundled.metafile.inputs), ([absolutePath, input]) => where(absolutePath) && Array.some(input.imports, (imported) => imported.original === packageName || imported.original !== void 0 && String.startsWith(subpathPrefix)(imported.original))), ([absolutePath]) => absolutePath);
443
471
  };
444
- //#endregion
445
- export { bundle, bundleWorkspacePlugin, directlyImports, exportNames, importersOfPackage, resolveModule, withBatch };
472
+ export { bundle, bundleWorkspacePlugin, check, directlyImports, exportNames, importersOfPackage, resolveModule, withBatch };
446
473
 
447
474
  //# sourceMappingURL=Bundler.mjs.map