@gaganref/confect-cli 10.3.1-fork.96 → 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
@@ -13,7 +13,7 @@ import * as Schema from "effect/Schema";
13
13
  import * as String from "effect/String";
14
14
  import * as Predicate from "effect/Predicate";
15
15
  import * as Order from "effect/Order";
16
- //#region src/ConvexConfig.ts
16
+ // src/ConvexConfig.ts
17
17
  const CONVEX_CONFIG_FILENAME = "convex.config.ts";
18
18
  const COMPONENT_CONFIG_NAMESPACE = "confect-component-config";
19
19
  /**
@@ -39,15 +39,17 @@ const CONVEX_CONFIG_SUFFIX = /[/\\]convex\.config(\.[cm]?[jt]s)?$/;
39
39
  /**
40
40
  * Resolve the same config spellings that Convex accepts, for configs and test
41
41
  * kits.
42
+ *
43
+ * @internal
42
44
  */
43
45
  const resolveDefinition = (specifier, importer, path) => {
44
46
  const extension = path.extname(specifier);
45
47
  const candidates = [
46
48
  specifier,
47
- ...extension === ".js" ? [specifier.slice(0, -3) + ".ts"] : [],
49
+ ...extension === ".js" ? [pipe(specifier, String.slice(0, -3)) + ".ts"] : [],
48
50
  ...extension !== ".js" && extension !== ".ts" ? [specifier + ".js", specifier + ".ts"] : []
49
51
  ];
50
- return Option.firstSomeOf(candidates.map((candidate) => resolveModule(candidate, importer)));
52
+ return Option.firstSomeOf(Array.map(candidates, (candidate) => resolveModule(candidate, importer)));
51
53
  };
52
54
  /**
53
55
  * `convex/server`'s `app.use(definition)` rejects any definition object that
@@ -59,6 +61,8 @@ const resolveDefinition = (specifier, importer, path) => {
59
61
  * `componentPlugin`) and swaps in a virtual wrapper that re-exports the real
60
62
  * definition with `componentDefinitionPath` and `defaultName` filled in—the
61
63
  * exact shape of Convex's `ImportedComponentDefinition`.
64
+ *
65
+ * @internal
62
66
  */
63
67
  const componentConfigPlugin = (path) => ({
64
68
  name: "confect:component-config",
@@ -80,18 +84,21 @@ const componentConfigPlugin = (path) => ({
80
84
  build.onLoad({
81
85
  filter: /.*/,
82
86
  namespace: COMPONENT_CONFIG_NAMESPACE
83
- }, (args) => {
87
+ }, (args) => Effect.gen(function* () {
84
88
  const specifier = args.pluginData.specifier;
85
89
  const componentDefinitionPath = !String.startsWith(".")(specifier) && !path.isAbsolute(specifier) ? String.replace(CONVEX_CONFIG_SUFFIX, "")(specifier) : path.dirname(args.path);
90
+ const JsonString = Schema.fromJsonString(Schema.String);
91
+ const modulePath = yield* Schema.encodeEffect(JsonString)(args.path);
92
+ const definitionPath = yield* Schema.encodeEffect(JsonString)(componentDefinitionPath);
86
93
  return {
87
94
  loader: "js",
88
95
  resolveDir: path.dirname(args.path),
89
- contents: Array.join([`import real from ${JSON.stringify(args.path)};`, `export default { ...real, componentDefinitionPath: ${JSON.stringify(componentDefinitionPath)}, defaultName: real._name, [${JSON.stringify(COMPONENT_IMPORT_KEY)}]: ${JSON.stringify({
96
+ contents: Array.join([`import real from ${modulePath};`, `export default { ...real, componentDefinitionPath: ${definitionPath}, defaultName: real._name, [${JSON.stringify(COMPONENT_IMPORT_KEY)}]: ${JSON.stringify({
90
97
  specifier,
91
98
  path: args.path
92
99
  })} };`], "\n")
93
100
  };
94
- });
101
+ }).pipe(Effect.runPromise));
95
102
  }
96
103
  });
97
104
  /**
@@ -132,36 +139,36 @@ const discoverInstalledComponents = Effect.fn("ConvexConfig.discoverInstalledCom
132
139
  isRoot: false,
133
140
  constructor: "defineComponent"
134
141
  })), Match.exhaustive);
135
- if (app === null || typeof app !== "object" || app._isRoot !== definition.isRoot || typeof app.export !== "function") return yield* new InvalidConvexConfigError({
142
+ if (app === null || typeof app !== "object" || app._isRoot !== definition.isRoot || typeof app.export !== "function") return yield* InvalidConvexConfigError.make({
136
143
  configPath: displayPath,
137
144
  reason: `it must default-export the ${kind} definition created by \`${definition.constructor}()\`.`
138
145
  });
139
146
  const analysis = yield* Effect.try({
140
147
  try: () => app.export(),
141
- catch: (cause) => new InvalidConvexConfigError({
148
+ catch: (cause) => InvalidConvexConfigError.make({
142
149
  configPath: displayPath,
143
150
  reason: `exporting the app definition threw: ${globalThis.String(cause)}.`
144
151
  })
145
152
  });
146
- const decoded = yield* Schema.decodeUnknownEffect(AppDefinitionAnalysis)(analysis).pipe(Effect.mapError((cause) => new InvalidConvexConfigError({
153
+ const decoded = yield* Schema.decodeUnknownEffect(AppDefinitionAnalysis)(analysis).pipe(Effect.mapError((cause) => InvalidConvexConfigError.make({
147
154
  configPath: displayPath,
148
155
  reason: `the app definition's installed components could not be read: ${cause.message}.`
149
156
  })));
150
157
  const components = pipe(decoded.childComponents, Array.map(({ name, path: componentDefinitionPath }) => {
151
- const httpPrefix = Object.entries(decoded.httpMounts ?? {}).find(([, reference]) => reference === `_reference/childComponent/${name}`)?.[0];
158
+ const httpPrefix = Option.getOrUndefined(Array.findFirst(Record.toEntries(decoded.httpMounts ?? {}), ([, reference]) => reference === `_reference/childComponent/${name}`))?.[0];
152
159
  return {
153
160
  name,
154
161
  componentDefinitionPath,
155
- ...httpPrefix === void 0 ? {} : { httpPrefix: httpPrefix.replace(/\/$/, "") }
162
+ ...httpPrefix === void 0 ? {} : { httpPrefix: pipe(httpPrefix, String.replace(/\/$/, "")) }
156
163
  };
157
164
  }), Array.sort(byName));
158
165
  const invalidNames = pipe(components, Array.map(({ name }) => name), Array.filter((name) => Option.isNone(String.match(VALID_COMPONENT_NAME)(name))));
159
- if (Array.isArrayNonEmpty(invalidNames)) return yield* new InvalidConvexConfigError({
166
+ if (Array.isArrayNonEmpty(invalidNames)) return yield* InvalidConvexConfigError.make({
160
167
  configPath: displayPath,
161
168
  reason: `component names must be alphanumeric plus underscores, but got: ${pipe(invalidNames, Array.map((name) => `"${name}"`), Array.join(", "))}. Pass a valid \`name\` to \`app.use\`.`
162
169
  });
163
170
  const duplicateNames = pipe(components, Array.groupBy(({ name }) => name), Record.toEntries, Array.filter(([, group]) => group.length > 1), Array.map(([name]) => name));
164
- if (Array.isArrayNonEmpty(duplicateNames)) return yield* new InvalidConvexConfigError({
171
+ if (Array.isArrayNonEmpty(duplicateNames)) return yield* InvalidConvexConfigError.make({
165
172
  configPath: displayPath,
166
173
  reason: `multiple components are installed under the same name (${Array.join(duplicateNames, ", ")}); pass a unique \`name\` to \`app.use\` for each.`
167
174
  });
@@ -174,7 +181,7 @@ const componentName = Effect.fnUntraced(function* (configPath) {
174
181
  const path = yield* Path.Path;
175
182
  const { module } = yield* bundle(configPath, { plugins: [componentConfigPlugin(path)] }).pipe(Effect.mapError((error) => fromBundlerError("convex/convex.config.ts", error)));
176
183
  const definition = module.default;
177
- if (!Predicate.hasProperty(definition, "_name") || !Predicate.isString(definition._name)) return yield* new InvalidConvexConfigError({
184
+ if (!Predicate.hasProperty(definition, "_name") || !Predicate.isString(definition._name)) return yield* InvalidConvexConfigError.make({
178
185
  configPath: "convex/convex.config.ts",
179
186
  reason: "the component definition must have a string name."
180
187
  });
@@ -186,13 +193,14 @@ const componentName = Effect.fnUntraced(function* (configPath) {
186
193
  * `<definition directory>/_generated/component.js`. Bare (npm) definition
187
194
  * directories are used verbatim; locally-defined components (recorded as
188
195
  * absolute directories) become a relative path from `confect/_generated`.
196
+ *
197
+ * @internal
189
198
  */
190
199
  const typeImportPath = (path, componentDefinitionPath, confectGeneratedDirectory) => {
191
200
  if (!path.isAbsolute(componentDefinitionPath)) return componentDefinitionPath;
192
201
  const relative = toPosixPath(path, path.relative(confectGeneratedDirectory, componentDefinitionPath));
193
202
  return String.startsWith(".")(relative) ? relative : `./${relative}`;
194
203
  };
195
- //#endregion
196
204
  export { COMPONENT_IMPORT_KEY, CONVEX_CONFIG_FILENAME, componentConfigPlugin, componentImportOf, componentName, discoverInstalledComponents, resolveDefinition, typeImportPath };
197
205
 
198
206
  //# sourceMappingURL=ConvexConfig.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ConvexConfig.mjs","names":["Bundler.resolveModule","Bundler.bundle"],"sources":["../src/ConvexConfig.ts"],"sourcesContent":["import { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport type * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport { fromBundlerError, type BuildError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport { InvalidConvexConfigError } from \"./CodegenError.js\";\nimport { toPosixPath } from \"./utils.js\";\n\nexport const CONVEX_CONFIG_FILENAME = \"convex.config.ts\";\n\n/**\n * A component installed on the app via `app.use(...)` in\n * `convex/convex.config.ts`.\n */\nexport interface InstalledComponent {\n /**\n * The mount name (`app.use`'s `name` option, falling back to the name the\n * component was defined with).\n */\n readonly name: string;\n readonly httpPrefix?: string;\n /**\n * The directory the component's definition lives in, mirroring the Convex\n * runtime's convention (a `componentDefinitionPath` identifies the\n * definition's directory): the import specifier minus its trailing\n * `convex.config` segment when it was bare (e.g. `@convex-dev/workpool`), or\n * the resolved absolute directory when it was relative (a locally-defined\n * component).\n */\n readonly componentDefinitionPath: string;\n}\n\nconst COMPONENT_CONFIG_NAMESPACE = \"confect-component-config\";\n\n/**\n * Where the plugin records how a definition was imported: the specifier as\n * written and the file it resolved to. Codegen reads it to write the import of\n * each mounted component into the generated `convex.config.ts`.\n */\nexport const COMPONENT_IMPORT_KEY = \"~confect/componentImport\";\n\nexport interface ComponentImport {\n readonly specifier: string;\n readonly path: string;\n}\n\nexport const componentImportOf = (\n definition: unknown,\n): Option.Option<ComponentImport> => {\n if (!Predicate.hasProperty(definition, COMPONENT_IMPORT_KEY)) {\n return Option.none();\n }\n const recorded = definition[COMPONENT_IMPORT_KEY];\n return Predicate.hasProperty(recorded, \"specifier\") &&\n Predicate.isString(recorded.specifier) &&\n Predicate.hasProperty(recorded, \"path\") &&\n Predicate.isString(recorded.path)\n ? Option.some({ specifier: recorded.specifier, path: recorded.path })\n : Option.none();\n};\n\n/**\n * Matches the trailing `convex.config` segment of a component-definition import\n * (with or without an extension), e.g. `@convex-dev/workpool/convex.config` or\n * `./waitlist/convex.config.ts`.\n */\nconst CONVEX_CONFIG_SUFFIX = /[/\\\\]convex\\.config(\\.[cm]?[jt]s)?$/;\n\n/**\n * Resolve the same config spellings that Convex accepts, for configs and test\n * kits.\n */\nexport const resolveDefinition = (\n specifier: string,\n importer: string,\n path: Path.Path,\n): Option.Option<string> => {\n const extension = path.extname(specifier);\n const candidates = [\n specifier,\n ...(extension === \".js\" ? [specifier.slice(0, -3) + \".ts\"] : []),\n ...(extension !== \".js\" && extension !== \".ts\"\n ? [specifier + \".js\", specifier + \".ts\"]\n : []),\n ];\n return Option.firstSomeOf(\n candidates.map((candidate) => Bundler.resolveModule(candidate, importer)),\n );\n};\n\n/**\n * `convex/server`'s `app.use(definition)` rejects any definition object that\n * lacks a string `componentDefinitionPath` (\"This code only works in Convex\n * runtime\"): that property is normally stamped on by the Convex backend's\n * module system when it evaluates a definition bundle. To evaluate\n * `convex.config.ts` in plain Node, this plugin intercepts every non-entry\n * import of a `convex.config` module (mirroring the Convex CLI's own\n * `componentPlugin`) and swaps in a virtual wrapper that re-exports the real\n * definition with `componentDefinitionPath` and `defaultName` filled in—the\n * exact shape of Convex's `ImportedComponentDefinition`.\n */\nexport const componentConfigPlugin = (path: Path.Path): esbuild.Plugin => ({\n name: \"confect:component-config\",\n setup(build) {\n build.onResolve({ filter: /convex\\.config/ }, (args) => {\n // The app's own `convex.config.ts` is the entry point; only imports of\n // *component* definitions get wrapped.\n if (args.kind === \"entry-point\") return undefined;\n\n // Claim a wrapper's import of the real definition into the file\n // namespace: bundled, the definition's own nested `convex.config`\n // imports re-enter this plugin and get stamped; externalized, an npm\n // definition would be evaluated natively by Node, where its top-level\n // `component.use(...)` of unstamped nested definitions throws.\n if (args.namespace === COMPONENT_CONFIG_NAMESPACE) {\n return { path: args.path };\n }\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n // Component definitions are conventionally imported extensionless\n // (`.../convex.config`), which npm `exports` maps resolve but plain\n // file resolution may not—probe the same candidates Convex does.\n return pipe(\n resolveDefinition(args.path, importer, path),\n Option.match({\n onNone: () => undefined,\n onSome: (resolved) => ({\n path: resolved,\n namespace: COMPONENT_CONFIG_NAMESPACE,\n pluginData: { specifier: args.path },\n }),\n }),\n );\n });\n\n build.onLoad(\n { filter: /.*/, namespace: COMPONENT_CONFIG_NAMESPACE },\n (args) => {\n const specifier = (args.pluginData as { specifier: string }).specifier;\n // The injected path is the definition's *directory*, matching the\n // Convex runtime's convention—so even if a future convex version\n // stops reading `defaultName`, `app.use`'s last-resort fallback\n // (`componentDefinitionPath.split(\"/\").pop()`) still yields the\n // conventional component name rather than `convex.config`. Convex's\n // codegen doesn't trust relative specifiers as identifiers (the\n // importer's location is lost after bundling), so those are recorded\n // as the resolved absolute directory; bare specifiers keep their\n // package prefix so the generated type import stays a package\n // specifier.\n const isBareSpecifier =\n !String.startsWith(\".\")(specifier) && !path.isAbsolute(specifier);\n const componentDefinitionPath = isBareSpecifier\n ? String.replace(CONVEX_CONFIG_SUFFIX, \"\")(specifier)\n : path.dirname(args.path);\n\n // The real module is imported (not inlined) so any nested\n // `convex.config` imports resolve from the definition's own file\n // rather than from this virtual wrapper. `defaultName` comes from\n // `defineComponent(name)`'s `_name`, keeping `app.use`'s name\n // resolution identical to the Convex runtime's.\n return {\n loader: \"js\",\n resolveDir: path.dirname(args.path),\n contents: Array.join(\n [\n `import real from ${JSON.stringify(args.path)};`,\n `export default { ...real, componentDefinitionPath: ${JSON.stringify(componentDefinitionPath)}, defaultName: real._name, [${JSON.stringify(COMPONENT_IMPORT_KEY)}]: ${JSON.stringify({ specifier, path: args.path })} };`,\n ],\n \"\\n\",\n ),\n };\n },\n );\n },\n});\n\n/**\n * The subset of `app.export()` (Convex's `AppDefinitionAnalysis`) that the\n * registry needs: each installed component's mount name and the\n * `componentDefinitionPath` injected by {@link componentConfigPlugin}.\n */\nconst AppDefinitionAnalysis = Schema.Struct({\n httpMounts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n childComponents: Schema.Array(\n Schema.Struct({\n name: Schema.String,\n path: Schema.String,\n }),\n ),\n});\n\nconst byName = Order.mapInput(\n Order.String,\n (component: InstalledComponent) => component.name,\n);\n\n/**\n * Convex component names must be alphanumeric plus underscores (see\n * `defineComponent`'s docs). Beyond rejecting genuinely invalid names, this is\n * a drift tripwire: if a future convex version stopped resolving names the way\n * we rely on (e.g. `defaultName` disappearing), the fallback name would be a\n * path segment like `convex.config`—caught here as a clear error instead of\n * silently emitting a broken registry.\n */\nconst VALID_COMPONENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Bundle and evaluate `convex/convex.config.ts` and list the components\n * installed on the app, in mount-name order. `displayPath` is used in error\n * messages (mirroring how impl/spec bundling reports relative paths).\n */\nexport const discoverInstalledComponents = Effect.fn(\n \"ConvexConfig.discoverInstalledComponents\",\n)(function* (\n convexConfigPath: string,\n displayPath: string,\n kind: \"app\" | \"component\" = \"app\",\n): Effect.fn.Return<\n ReadonlyArray<InstalledComponent>,\n BuildError | InvalidConvexConfigError,\n Path.Path | FileSystem.FileSystem\n> {\n const path = yield* Path.Path;\n\n const { module } = yield* Bundler.bundle(convexConfigPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(Effect.mapError((error) => fromBundlerError(displayPath, error)));\n\n const app = module.default as\n | { _isRoot?: unknown; export?: unknown }\n | null\n | undefined;\n\n const definition = Match.value(kind).pipe(\n Match.when(\"app\", () => ({ isRoot: true, constructor: \"defineApp\" })),\n Match.when(\"component\", () => ({\n isRoot: false,\n constructor: \"defineComponent\",\n })),\n Match.exhaustive,\n );\n\n if (\n app === null ||\n typeof app !== \"object\" ||\n app._isRoot !== definition.isRoot ||\n typeof app.export !== \"function\"\n ) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `it must default-export the ${kind} definition created by \\`${definition.constructor}()\\`.`,\n });\n }\n\n const analysis = yield* Effect.try({\n try: () => (app.export as () => unknown)(),\n catch: (cause) =>\n new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `exporting the app definition threw: ${globalThis.String(cause)}.`,\n }),\n });\n\n const decoded = yield* Schema.decodeUnknownEffect(AppDefinitionAnalysis)(\n analysis,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `the app definition's installed components could not be read: ${cause.message}.`,\n }),\n ),\n );\n\n const components = pipe(\n decoded.childComponents,\n Array.map(({ name, path: componentDefinitionPath }): InstalledComponent => {\n const httpPrefix = Object.entries(decoded.httpMounts ?? {}).find(\n ([, reference]) => reference === `_reference/childComponent/${name}`,\n )?.[0];\n return {\n name,\n componentDefinitionPath,\n ...(httpPrefix === undefined\n ? {}\n : { httpPrefix: httpPrefix.replace(/\\/$/, \"\") }),\n };\n }),\n Array.sort(byName),\n );\n\n const invalidNames = pipe(\n components,\n Array.map(({ name }) => name),\n Array.filter((name) =>\n Option.isNone(String.match(VALID_COMPONENT_NAME)(name)),\n ),\n );\n if (Array.isArrayNonEmpty(invalidNames)) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `component names must be alphanumeric plus underscores, but got: ${pipe(\n invalidNames,\n Array.map((name) => `\"${name}\"`),\n Array.join(\", \"),\n )}. Pass a valid \\`name\\` to \\`app.use\\`.`,\n });\n }\n\n const duplicateNames = pipe(\n components,\n Array.groupBy(({ name }) => name),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([name]) => name),\n );\n if (Array.isArrayNonEmpty(duplicateNames)) {\n return yield* new InvalidConvexConfigError({\n configPath: displayPath,\n reason: `multiple components are installed under the same name (${Array.join(duplicateNames, \", \")}); pass a unique \\`name\\` to \\`app.use\\` for each.`,\n });\n }\n\n return components;\n});\n\n/**\n * The name passed to `defineComponent`, independent of the package's ID scope.\n */\nexport const componentName = Effect.fnUntraced(function* (configPath: string) {\n const path = yield* Path.Path;\n const { module } = yield* Bundler.bundle(configPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(\n Effect.mapError((error) =>\n fromBundlerError(\"convex/convex.config.ts\", error),\n ),\n );\n const definition: unknown = module.default;\n if (\n !Predicate.hasProperty(definition, \"_name\") ||\n !Predicate.isString(definition._name)\n ) {\n return yield* new InvalidConvexConfigError({\n configPath: \"convex/convex.config.ts\",\n reason: \"the component definition must have a string name.\",\n });\n }\n return definition._name;\n});\n\n/**\n * The module specifier the generated registry's `ComponentApi` type import\n * should use for a component, following Convex's own codegen convention:\n * `<definition directory>/_generated/component.js`. Bare (npm) definition\n * directories are used verbatim; locally-defined components (recorded as\n * absolute directories) become a relative path from `confect/_generated`.\n */\nexport const typeImportPath = (\n path: Path.Path,\n componentDefinitionPath: string,\n confectGeneratedDirectory: string,\n): string => {\n if (!path.isAbsolute(componentDefinitionPath)) {\n return componentDefinitionPath;\n }\n const relative = toPosixPath(\n path,\n path.relative(confectGeneratedDirectory, componentDefinitionPath),\n );\n return String.startsWith(\".\")(relative) ? relative : `./${relative}`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAA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AAK;AAC5D"}
1
+ {"version":3,"file":"ConvexConfig.mjs","names":["Bundler.resolveModule","Bundler.bundle"],"sources":["../src/ConvexConfig.ts"],"sourcesContent":["import { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport type * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport { fromBundlerError, type BuildError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport { InvalidConvexConfigError } from \"./CodegenError.js\";\nimport { toPosixPath } from \"./utils.js\";\n\nexport const CONVEX_CONFIG_FILENAME = \"convex.config.ts\";\n\n/**\n * A component installed on the app via `app.use(...)` in\n * `convex/convex.config.ts`.\n */\nexport interface InstalledComponent {\n /**\n * The mount name (`app.use`'s `name` option, falling back to the name the\n * component was defined with).\n */\n readonly name: string;\n readonly httpPrefix?: string;\n /**\n * The directory the component's definition lives in, mirroring the Convex\n * runtime's convention (a `componentDefinitionPath` identifies the\n * definition's directory): the import specifier minus its trailing\n * `convex.config` segment when it was bare (e.g. `@convex-dev/workpool`), or\n * the resolved absolute directory when it was relative (a locally-defined\n * component).\n */\n readonly componentDefinitionPath: string;\n}\n\nconst COMPONENT_CONFIG_NAMESPACE = \"confect-component-config\";\n\n/**\n * Where the plugin records how a definition was imported: the specifier as\n * written and the file it resolved to. Codegen reads it to write the import of\n * each mounted component into the generated `convex.config.ts`.\n */\nexport const COMPONENT_IMPORT_KEY = \"~confect/componentImport\";\n\nexport interface ComponentImport {\n readonly specifier: string;\n readonly path: string;\n}\n\nexport const componentImportOf = (\n definition: unknown,\n): Option.Option<ComponentImport> => {\n if (!Predicate.hasProperty(definition, COMPONENT_IMPORT_KEY)) {\n return Option.none();\n }\n const recorded = definition[COMPONENT_IMPORT_KEY];\n return Predicate.hasProperty(recorded, \"specifier\") &&\n Predicate.isString(recorded.specifier) &&\n Predicate.hasProperty(recorded, \"path\") &&\n Predicate.isString(recorded.path)\n ? Option.some({ specifier: recorded.specifier, path: recorded.path })\n : Option.none();\n};\n\n/**\n * Matches the trailing `convex.config` segment of a component-definition import\n * (with or without an extension), e.g. `@convex-dev/workpool/convex.config` or\n * `./waitlist/convex.config.ts`.\n */\nconst CONVEX_CONFIG_SUFFIX = /[/\\\\]convex\\.config(\\.[cm]?[jt]s)?$/;\n\n/**\n * Resolve the same config spellings that Convex accepts, for configs and test\n * kits.\n *\n * @internal\n */\nexport const resolveDefinition = (\n specifier: string,\n importer: string,\n path: Path.Path,\n): Option.Option<string> => {\n const extension = path.extname(specifier);\n const candidates = [\n specifier,\n ...(extension === \".js\"\n ? [pipe(specifier, String.slice(0, -3)) + \".ts\"]\n : []),\n ...(extension !== \".js\" && extension !== \".ts\"\n ? [specifier + \".js\", specifier + \".ts\"]\n : []),\n ];\n return Option.firstSomeOf(\n Array.map(candidates, (candidate) =>\n Bundler.resolveModule(candidate, importer),\n ),\n );\n};\n\n/**\n * `convex/server`'s `app.use(definition)` rejects any definition object that\n * lacks a string `componentDefinitionPath` (\"This code only works in Convex\n * runtime\"): that property is normally stamped on by the Convex backend's\n * module system when it evaluates a definition bundle. To evaluate\n * `convex.config.ts` in plain Node, this plugin intercepts every non-entry\n * import of a `convex.config` module (mirroring the Convex CLI's own\n * `componentPlugin`) and swaps in a virtual wrapper that re-exports the real\n * definition with `componentDefinitionPath` and `defaultName` filled in—the\n * exact shape of Convex's `ImportedComponentDefinition`.\n *\n * @internal\n */\nexport const componentConfigPlugin = (path: Path.Path): esbuild.Plugin => ({\n name: \"confect:component-config\",\n setup(build) {\n build.onResolve({ filter: /convex\\.config/ }, (args) => {\n // The app's own `convex.config.ts` is the entry point; only imports of\n // *component* definitions get wrapped.\n if (args.kind === \"entry-point\") return undefined;\n\n // Claim a wrapper's import of the real definition into the file\n // namespace: bundled, the definition's own nested `convex.config`\n // imports re-enter this plugin and get stamped; externalized, an npm\n // definition would be evaluated natively by Node, where its top-level\n // `component.use(...)` of unstamped nested definitions throws.\n if (args.namespace === COMPONENT_CONFIG_NAMESPACE) {\n return { path: args.path };\n }\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n\n const importer =\n args.importer !== \"\" ? args.importer : path.join(args.resolveDir, \"_\");\n\n // Component definitions are conventionally imported extensionless\n // (`.../convex.config`), which npm `exports` maps resolve but plain\n // file resolution may not—probe the same candidates Convex does.\n return pipe(\n resolveDefinition(args.path, importer, path),\n Option.match({\n onNone: () => undefined,\n onSome: (resolved) => ({\n path: resolved,\n namespace: COMPONENT_CONFIG_NAMESPACE,\n pluginData: { specifier: args.path },\n }),\n }),\n );\n });\n\n build.onLoad(\n { filter: /.*/, namespace: COMPONENT_CONFIG_NAMESPACE },\n (args) =>\n Effect.gen(function* () {\n const specifier = (args.pluginData as { specifier: string })\n .specifier;\n // The injected path is the definition's *directory*, matching the\n // Convex runtime's convention—so even if a future convex version\n // stops reading `defaultName`, `app.use`'s last-resort fallback\n // (`componentDefinitionPath.split(\"/\").pop()`) still yields the\n // conventional component name rather than `convex.config`. Convex's\n // codegen doesn't trust relative specifiers as identifiers (the\n // importer's location is lost after bundling), so those are recorded\n // as the resolved absolute directory; bare specifiers keep their\n // package prefix so the generated type import stays a package\n // specifier.\n const isBareSpecifier =\n !String.startsWith(\".\")(specifier) && !path.isAbsolute(specifier);\n const componentDefinitionPath = isBareSpecifier\n ? String.replace(CONVEX_CONFIG_SUFFIX, \"\")(specifier)\n : path.dirname(args.path);\n const JsonString = Schema.fromJsonString(Schema.String);\n const modulePath = yield* Schema.encodeEffect(JsonString)(args.path);\n const definitionPath = yield* Schema.encodeEffect(JsonString)(\n componentDefinitionPath,\n );\n\n // The real module is imported (not inlined) so any nested\n // `convex.config` imports resolve from the definition's own file\n // rather than from this virtual wrapper. `defaultName` comes from\n // `defineComponent(name)`'s `_name`, keeping `app.use`'s name\n // resolution identical to the Convex runtime's.\n return {\n loader: \"js\",\n resolveDir: path.dirname(args.path),\n contents: Array.join(\n [\n `import real from ${modulePath};`,\n // oxlint-disable-next-line effecttsgo/prefer-schema-over-json, effecttsgo/global-json-in-effect -- Emit an escaped JavaScript string and object literal into the virtual module, not a JSON payload.\n `export default { ...real, componentDefinitionPath: ${definitionPath}, defaultName: real._name, [${JSON.stringify(COMPONENT_IMPORT_KEY)}]: ${JSON.stringify({ specifier, path: args.path })} };`,\n ],\n \"\\n\",\n ),\n } satisfies esbuild.OnLoadResult;\n }).pipe(Effect.runPromise),\n );\n },\n});\n\n/**\n * The subset of `app.export()` (Convex's `AppDefinitionAnalysis`) that the\n * registry needs: each installed component's mount name and the\n * `componentDefinitionPath` injected by {@link componentConfigPlugin}.\n */\nconst AppDefinitionAnalysis = Schema.Struct({\n httpMounts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n childComponents: Schema.Array(\n Schema.Struct({\n name: Schema.String,\n path: Schema.String,\n }),\n ),\n});\n\nconst byName = Order.mapInput(\n Order.String,\n (component: InstalledComponent) => component.name,\n);\n\n/**\n * Convex component names must be alphanumeric plus underscores (see\n * `defineComponent`'s docs). Beyond rejecting genuinely invalid names, this is\n * a drift tripwire: if a future convex version stopped resolving names the way\n * we rely on (e.g. `defaultName` disappearing), the fallback name would be a\n * path segment like `convex.config`—caught here as a clear error instead of\n * silently emitting a broken registry.\n */\nconst VALID_COMPONENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Bundle and evaluate `convex/convex.config.ts` and list the components\n * installed on the app, in mount-name order. `displayPath` is used in error\n * messages (mirroring how impl/spec bundling reports relative paths).\n */\nexport const discoverInstalledComponents = Effect.fn(\n \"ConvexConfig.discoverInstalledComponents\",\n)(function* (\n convexConfigPath: string,\n displayPath: string,\n kind: \"app\" | \"component\" = \"app\",\n): Effect.fn.Return<\n ReadonlyArray<InstalledComponent>,\n BuildError | InvalidConvexConfigError,\n Path.Path | FileSystem.FileSystem\n> {\n const path = yield* Path.Path;\n\n const { module } = yield* Bundler.bundle(convexConfigPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(Effect.mapError((error) => fromBundlerError(displayPath, error)));\n\n const app = module.default as\n | { _isRoot?: unknown; export?: unknown }\n | null\n | undefined;\n\n const definition = Match.value(kind).pipe(\n Match.when(\"app\", () => ({ isRoot: true, constructor: \"defineApp\" })),\n Match.when(\"component\", () => ({\n isRoot: false,\n constructor: \"defineComponent\",\n })),\n Match.exhaustive,\n );\n\n if (\n app === null ||\n typeof app !== \"object\" ||\n app._isRoot !== definition.isRoot ||\n typeof app.export !== \"function\"\n ) {\n return yield* InvalidConvexConfigError.make({\n configPath: displayPath,\n reason: `it must default-export the ${kind} definition created by \\`${definition.constructor}()\\`.`,\n });\n }\n\n const analysis = yield* Effect.try({\n try: () => (app.export as () => unknown)(),\n catch: (cause) =>\n InvalidConvexConfigError.make({\n configPath: displayPath,\n reason: `exporting the app definition threw: ${globalThis.String(cause)}.`,\n }),\n });\n\n const decoded = yield* Schema.decodeUnknownEffect(AppDefinitionAnalysis)(\n analysis,\n ).pipe(\n Effect.mapError((cause) =>\n InvalidConvexConfigError.make({\n configPath: displayPath,\n reason: `the app definition's installed components could not be read: ${cause.message}.`,\n }),\n ),\n );\n\n const components = pipe(\n decoded.childComponents,\n Array.map(({ name, path: componentDefinitionPath }): InstalledComponent => {\n const httpPrefix = Option.getOrUndefined(\n Array.findFirst(\n Record.toEntries(decoded.httpMounts ?? {}),\n ([, reference]) => reference === `_reference/childComponent/${name}`,\n ),\n )?.[0];\n return {\n name,\n componentDefinitionPath,\n ...(httpPrefix === undefined\n ? {}\n : { httpPrefix: pipe(httpPrefix, String.replace(/\\/$/, \"\")) }),\n };\n }),\n Array.sort(byName),\n );\n\n const invalidNames = pipe(\n components,\n Array.map(({ name }) => name),\n Array.filter((name) =>\n Option.isNone(String.match(VALID_COMPONENT_NAME)(name)),\n ),\n );\n if (Array.isArrayNonEmpty(invalidNames)) {\n return yield* InvalidConvexConfigError.make({\n configPath: displayPath,\n reason: `component names must be alphanumeric plus underscores, but got: ${pipe(\n invalidNames,\n Array.map((name) => `\"${name}\"`),\n Array.join(\", \"),\n )}. Pass a valid \\`name\\` to \\`app.use\\`.`,\n });\n }\n\n const duplicateNames = pipe(\n components,\n Array.groupBy(({ name }) => name),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([name]) => name),\n );\n if (Array.isArrayNonEmpty(duplicateNames)) {\n return yield* InvalidConvexConfigError.make({\n configPath: displayPath,\n reason: `multiple components are installed under the same name (${Array.join(duplicateNames, \", \")}); pass a unique \\`name\\` to \\`app.use\\` for each.`,\n });\n }\n\n return components;\n});\n\n/**\n * The name passed to `defineComponent`, independent of the package's ID scope.\n */\nexport const componentName = Effect.fnUntraced(function* (configPath: string) {\n const path = yield* Path.Path;\n const { module } = yield* Bundler.bundle(configPath, {\n plugins: [componentConfigPlugin(path)],\n }).pipe(\n Effect.mapError((error) =>\n fromBundlerError(\"convex/convex.config.ts\", error),\n ),\n );\n const definition: unknown = module.default;\n if (\n !Predicate.hasProperty(definition, \"_name\") ||\n !Predicate.isString(definition._name)\n ) {\n return yield* InvalidConvexConfigError.make({\n configPath: \"convex/convex.config.ts\",\n reason: \"the component definition must have a string name.\",\n });\n }\n return definition._name;\n});\n\n/**\n * The module specifier the generated registry's `ComponentApi` type import\n * should use for a component, following Convex's own codegen convention:\n * `<definition directory>/_generated/component.js`. Bare (npm) definition\n * directories are used verbatim; locally-defined components (recorded as\n * absolute directories) become a relative path from `confect/_generated`.\n *\n * @internal\n */\nexport const typeImportPath = (\n path: Path.Path,\n componentDefinitionPath: string,\n confectGeneratedDirectory: string,\n): string => {\n if (!path.isAbsolute(componentDefinitionPath)) {\n return componentDefinitionPath;\n }\n const relative = toPosixPath(\n path,\n path.relative(confectGeneratedDirectory, componentD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UAAU,SAAS,WAAW,KAAK,GAEpC,OAAO,OAAO,yBAAyB,KAAK;EAC1C,YAAY;EACZ,QAAQ;CACV,CAAC;CAEH,OAAO,WAAW;AACpB,CAAC;;;;;;;;;;AAWD,MAAa,kBACX,MACA,yBACA,8BACW;CACX,IAAI,CAAC,KAAK,WAAW,uBAAuB,GAC1C,OAAO;CAET,MAAM,WAAW,YACf,MACA,KAAK,SAAS,2BAA2B,uBAAuB,CAClE;CACA,OAAO,OAAO,WAAW,GAAG,CAAC,CAAC,QAAQ,IAAI,WAAW,KAAK;AAC5D"}
@@ -9,7 +9,7 @@ import * as Schema from "effect/Schema";
9
9
  import * as Predicate from "effect/Predicate";
10
10
  import * as Layer from "effect/Layer";
11
11
  import * as IdScope from "@confect/core/IdScope";
12
- //#region src/ConvexDirectory.ts
12
+ // src/ConvexDirectory.ts
13
13
  var ConvexDirectory = class ConvexDirectory extends Context.Service()("@confect/cli/ConvexDirectory") {
14
14
  static get = ConvexDirectory.use((service) => service.get);
15
15
  static target = ConvexDirectory.use((service) => Effect.succeed(service.target ?? {
@@ -39,16 +39,18 @@ const findConvexDirectory = Effect.gen(function* () {
39
39
  const projectRoot = yield* ProjectRoot.get;
40
40
  const defaultPath = path.join(projectRoot, "convex");
41
41
  const convexJsonPath = path.join(projectRoot, "convex.json");
42
- const convexDirectory = (yield* fs.exists(convexJsonPath)) ? yield* fs.readFileString(convexJsonPath).pipe(Effect.flatMap((json) => Schema.decodeEffect(ConvexJsonConfig)(json).pipe(Effect.mapError((cause) => new InvalidConvexJsonError({ cause })))), Effect.map((config) => Option.fromNullishOr(config.functions).pipe(Option.map((functionsDir) => path.join(projectRoot, functionsDir)), Option.getOrElse(() => defaultPath)))) : defaultPath;
42
+ const convexDirectory = (yield* fs.exists(convexJsonPath)) ? yield* fs.readFileString(convexJsonPath).pipe(Effect.flatMap((json) => Schema.decodeEffect(ConvexJsonConfig)(json).pipe(Effect.mapError((cause) => InvalidConvexJsonError.make({ cause })))), Effect.map((config) => Option.fromNullishOr(config.functions).pipe(Option.map((functionsDir) => path.join(projectRoot, functionsDir)), Option.getOrElse(() => defaultPath)))) : defaultPath;
43
43
  if (yield* fs.exists(convexDirectory)) return convexDirectory;
44
- else return yield* new ConvexDirectoryNotFoundError();
44
+ else return yield* ConvexDirectoryNotFoundError.make();
45
45
  });
46
+ /**
47
+ * @internal
48
+ */
46
49
  const layer = Layer.effect(ConvexDirectory, Effect.gen(function* () {
47
50
  const convexDirectory = yield* findConvexDirectory;
48
51
  const ref = yield* Ref.make(convexDirectory);
49
52
  return { get: Ref.get(ref) };
50
53
  })).pipe(Layer.provide(layer$1));
51
- //#endregion
52
54
  export { ConvexDirectory, ConvexDirectoryNotFoundError, InvalidConvexJsonError, layer };
53
55
 
54
56
  //# sourceMappingURL=ConvexDirectory.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ConvexDirectory.mjs","names":["ProjectRoot.layer"],"sources":["../src/ConvexDirectory.ts"],"sourcesContent":["import * as IdScope from \"@confect/core/IdScope\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ProjectRoot from \"./ProjectRoot.js\";\nimport type * as DatabaseSchema from \"@confect/server/DatabaseSchema\";\n\nexport class ConvexDirectory extends Context.Service<\n ConvexDirectory,\n {\n readonly get: Effect.Effect<string>;\n readonly target?:\n | DatabaseSchema.AppTarget\n | DatabaseSchema.ComponentTarget<IdScope.Component<string>>;\n }\n>()(\"@confect/cli/ConvexDirectory\") {\n static readonly get = ConvexDirectory.use((service) => service.get);\n static readonly target = ConvexDirectory.use((service) =>\n Effect.succeed(\n service.target ?? { kind: \"app\" as const, scope: IdScope.app },\n ),\n );\n}\n\nexport class ConvexDirectoryNotFoundError extends Schema.TaggedError<ConvexDirectoryNotFoundError>()(\n \"ConvexDirectoryNotFoundError\",\n {},\n) {\n override get message(): string {\n return \"Could not find Convex directory\";\n }\n}\n\n/**\n * Schema for `convex.json` configuration file.\n *\n * @see https://docs.convex.dev/production/project-configuration\n */\nconst ConvexJsonConfig = Schema.fromJsonString(\n Schema.Struct({\n functions: Schema.optional(Schema.String),\n }),\n);\n\nexport class InvalidConvexJsonError extends Schema.TaggedError<InvalidConvexJsonError>()(\n \"InvalidConvexJsonError\",\n {\n cause: Schema.Unknown,\n },\n) {\n override get message(): string {\n const detail = Predicate.isError(this.cause)\n ? `: ${this.cause.message}`\n : \"\";\n return `Failed to parse convex.json${detail}`;\n }\n}\n\nconst findConvexDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const projectRoot = yield* ProjectRoot.ProjectRoot.get;\n\n const defaultPath = path.join(projectRoot, \"convex\");\n\n const convexJsonPath = path.join(projectRoot, \"convex.json\");\n\n const convexDirectory = (yield* fs.exists(convexJsonPath))\n ? yield* fs.readFileString(convexJsonPath).pipe(\n Effect.flatMap((json) =>\n Schema.decodeEffect(ConvexJsonConfig)(json).pipe(\n Effect.mapError((cause) => new InvalidConvexJsonError({ cause })),\n ),\n ),\n Effect.map((config) =>\n Option.fromNullishOr(config.functions).pipe(\n Option.map((functionsDir) => path.join(projectRoot, functionsDir)),\n Option.getOrElse(() => defaultPath),\n ),\n ),\n )\n : defaultPath;\n\n if (yield* fs.exists(convexDirectory)) {\n return convexDirectory;\n } else {\n return yield* new ConvexDirectoryNotFoundError();\n }\n});\n\nexport const layer = Layer.effect(\n ConvexDirectory,\n Effect.gen(function* () {\n const convexDirectory = yield* findConvexDirectory;\n\n const ref = yield* Ref.make<string>(convexDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n).pipe(Layer.provide(ProjectRoot.layer));\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,kBAAb,MAAa,wBAA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E,OAAO,gBAAgB,WAAW,CACpC,CACF,CACF,IACA;CAEJ,IAAI,OAAO,GAAG,OAAO,eAAe,GAClC,OAAO;MAEP,OAAO,OAAO,IAAI,6BAA6B;AAEnD,CAAC;AAED,MAAa,QAAQ,MAAM,OACzB,iBACA,OAAO,IAAI,aAAa;CACtB,MAAM,kBAAkB,OAAO;CAE/B,MAAM,MAAM,OAAO,IAAI,KAAa,eAAe;CAEnD,OAAO,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAC7B,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQA,OAAiB,CAAC"}
1
+ {"version":3,"file":"ConvexDirectory.mjs","names":["ProjectRoot.layer"],"sources":["../src/ConvexDirectory.ts"],"sourcesContent":["import * as IdScope from \"@confect/core/IdScope\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as ProjectRoot from \"./ProjectRoot.js\";\nimport type * as DatabaseSchema from \"@confect/server/DatabaseSchema\";\n\nexport class ConvexDirectory extends Context.Service<\n ConvexDirectory,\n {\n readonly get: Effect.Effect<string>;\n readonly target?:\n | DatabaseSchema.AppTarget\n | DatabaseSchema.ComponentTarget<IdScope.Component<string>>;\n }\n>()(\"@confect/cli/ConvexDirectory\") {\n static readonly get = ConvexDirectory.use((service) => service.get);\n static readonly target = ConvexDirectory.use((service) =>\n Effect.succeed(\n service.target ?? { kind: \"app\" as const, scope: IdScope.app },\n ),\n );\n}\n\nexport class ConvexDirectoryNotFoundError extends Schema.TaggedError<\n ConvexDirectoryNotFoundError,\n { readonly brand: unique symbol }\n>()(\"ConvexDirectoryNotFoundError\", {}) {\n override get message(): string {\n return \"Could not find Convex directory\";\n }\n}\n\n/**\n * Schema for `convex.json` configuration file.\n *\n * @see https://docs.convex.dev/production/project-configuration\n */\nconst ConvexJsonConfig = Schema.fromJsonString(\n Schema.Struct({\n functions: Schema.optional(Schema.String),\n }),\n);\n\nexport class InvalidConvexJsonError extends Schema.TaggedError<\n InvalidConvexJsonError,\n { readonly brand: unique symbol }\n>()(\"InvalidConvexJsonError\", {\n cause: Schema.Unknown,\n}) {\n override get message(): string {\n const detail = Predicate.isError(this.cause)\n ? `: ${this.cause.message}`\n : \"\";\n return `Failed to parse convex.json${detail}`;\n }\n}\n\nconst findConvexDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const projectRoot = yield* ProjectRoot.ProjectRoot.get;\n\n const defaultPath = path.join(projectRoot, \"convex\");\n\n const convexJsonPath = path.join(projectRoot, \"convex.json\");\n\n const convexDirectory = (yield* fs.exists(convexJsonPath))\n ? yield* fs.readFileString(convexJsonPath).pipe(\n Effect.flatMap((json) =>\n Schema.decodeEffect(ConvexJsonConfig)(json).pipe(\n Effect.mapError((cause) => InvalidConvexJsonError.make({ cause })),\n ),\n ),\n Effect.map((config) =>\n Option.fromNullishOr(config.functions).pipe(\n Option.map((functionsDir) => path.join(projectRoot, functionsDir)),\n Option.getOrElse(() => defaultPath),\n ),\n ),\n )\n : defaultPath;\n\n if (yield* fs.exists(convexDirectory)) {\n return convexDirectory;\n } else {\n return yield* ConvexDirectoryNotFoundError.make();\n }\n});\n\n/**\n * @internal\n */\nexport const layer = Layer.effect(\n ConvexDirectory,\n Effect.gen(function* () {\n const convexDirectory = yield* findConvexDirectory;\n\n const ref = yield* Ref.make<string>(convexDirectory);\n\n return { get: Ref.get(ref) } as const;\n }),\n).pipe(Layer.provide(ProjectRoot.layer));\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAQ3C,CAAC,CAAC,8BAA8B,CAAC,CAAC;CAClC,OAAgB,MAAM,gBAAgB,KAAK,YAAY,Q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