@gaganref/confect-cli 10.3.1-fork.8 → 10.3.1-fork.81

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.
@@ -1,6 +1,6 @@
1
1
  import { fromBundlerError } from "./BuildError.mjs";
2
2
  import { bundle, directlyImports, importersOfPackage, withBatch } from "./Bundler.mjs";
3
- import { ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidMiddlewareAttachmentError, MissingImplFileError, MissingSpecFileError, SpecImportsServerError, SpecMissingDefaultGroupSpecError } from "./CodegenError.mjs";
3
+ import { ImplMissingDefaultLayerError, ImplMissingFunctionsError, ImplMissingMiddlewareError, ImplMissingSpecImportError, ImplNotFinalizedError, InvalidDeclarationError, InvalidMiddlewareAttachmentError, MissingImplFileError, MissingSpecFileError, RequiredMiddlewareError, SpecImportsServerError, SpecMissingDefaultGroupSpecError } from "./CodegenError.mjs";
4
4
  import { ConfectDirectory } from "./ConfectDirectory.mjs";
5
5
  import { removePathExtension, toPosixPath } from "./utils.mjs";
6
6
  import { ImplModulePath } from "./ImplModulePath.mjs";
@@ -16,7 +16,7 @@ import * as Schema from "effect/Schema";
16
16
  import * as String from "effect/String";
17
17
  import * as Layer from "effect/Layer";
18
18
  import * as Brand from "effect/Brand";
19
- import { Registry } from "@confect/server";
19
+ import { Registry, RegistryItems } from "@confect/server";
20
20
  import * as GroupImpl from "@confect/server/GroupImpl";
21
21
  //#region src/LeafModule.ts
22
22
  const LoadedLeafModule = Brand.nominal();
@@ -126,6 +126,17 @@ const validateClientSafety = Effect.fnUntraced(function* (leaf, bundled) {
126
126
  importerPaths: Array.map(importers, (absolutePath) => toPosixPath(path, path.relative(confectDirectory, absolutePath)))
127
127
  });
128
128
  });
129
+ const validateReservedArguments = Effect.fnUntraced(function* (group, specPath, groupPath) {
130
+ for (const spec of Object.values(group.functions)) {
131
+ const name = spec.reservedArgument;
132
+ const provenance = spec.functionProvenance;
133
+ if (name !== void 0 && provenance._tag === "Confect" && Object.hasOwn(provenance.args.fields, name)) return yield* new InvalidDeclarationError({
134
+ declarationPath: `confect/${specPath}`,
135
+ reason: `${groupPath}:${spec.name} declares the argument "${name}", which its profile reserves. Rename the argument.`
136
+ });
137
+ }
138
+ for (const [name, child] of Object.entries(group.groups)) yield* validateReservedArguments(child, specPath, `${groupPath}/${name}`);
139
+ });
129
140
  /**
130
141
  * Validate that the leaf's spec file default-exports a `GroupSpec`, and that
131
142
  * nothing it reaches drags server code into the client (see
@@ -139,6 +150,7 @@ const loadSpec = Effect.fn("LeafModule.loadSpec")(function* (leaf) {
139
150
  const groupSpec = bundled.module.default;
140
151
  if (!GroupSpec.isGroupSpec(groupSpec)) return yield* new SpecMissingDefaultGroupSpecError({ specPath: leaf.relativePath });
141
152
  yield* validateClientSafety(leaf, bundled);
153
+ yield* validateReservedArguments(groupSpec, leaf.relativePath, leaf.pathSegments.join("/"));
142
154
  yield* Effect.fromResult(GroupSpec.validateMiddleware(groupSpec)).pipe(Effect.mapError((error) => new InvalidMiddlewareAttachmentError({
143
155
  specPath: leaf.relativePath,
144
156
  message: MiddlewareAttachment.formatValidationError(error)
@@ -156,22 +168,23 @@ const loadSpec = Effect.fn("LeafModule.loadSpec")(function* (leaf) {
156
168
  const findFinalizedGroupImpl = (context) => Array.findFirst(context.mapUnsafe.values(), GroupImpl.isFinalizedGroupImpl);
157
169
  /**
158
170
  * Build the impl layer with a fresh `Registry` so each validation is isolated
159
- * from prior validations' `FunctionImpl.make` writes. The CLI no longer reads
160
- * the registry directly—`GroupImpl.finalize` snapshots the registered function
161
- * names onto the produced `Finalized` `GroupImpl` service value—but a fresh
162
- * `Ref` is still required because the default `Context.Reference` is cached
163
- * globally and would otherwise accumulate items across impls.
171
+ * from prior validations' `FunctionImpl.make` writes. Retain its items to check
172
+ * required middleware against actual function attachments.
164
173
  */
165
174
  const buildImplLayer = Effect.fnUntraced(function* (implLayer) {
166
175
  const registry = Ref.makeUnsafe({});
167
- return yield* Layer.build(implLayer).pipe(Effect.provideService(Registry.Registry, registry));
176
+ return {
177
+ context: yield* Layer.build(implLayer).pipe(Effect.provideService(Registry.Registry, registry)),
178
+ items: yield* Ref.get(registry)
179
+ };
168
180
  }, Effect.scoped);
169
181
  /**
170
182
  * Validate that the leaf's sibling impl file imports the spec, default-exports
171
183
  * a finalized `GroupImpl` layer, and provides a `FunctionImpl` for every
172
- * function declared by the spec.
184
+ * function declared by the spec. Return uncovered middleware requirements for
185
+ * the caller to report across groups.
173
186
  */
174
- const validateImpl = Effect.fn("LeafModule.validateImpl")(function* (leaf) {
187
+ const validateImpl = Effect.fn("LeafModule.validateImpl")(function* (leaf, required = []) {
175
188
  const implRelativePath = yield* implPathForSpec(leaf.relativePath);
176
189
  const implAbsolutePath = yield* absoluteModulePath(implRelativePath);
177
190
  const specAbsolutePath = yield* absoluteModulePath(leaf.relativePath);
@@ -183,7 +196,7 @@ const validateImpl = Effect.fn("LeafModule.validateImpl")(function* (leaf) {
183
196
  if (!Layer.isLayer(bundled.module.default)) return yield* new ImplMissingDefaultLayerError({ implPath: implRelativePath });
184
197
  const groupSpec = leaf.spec;
185
198
  const expectedFunctionNames = Object.keys(groupSpec.functions);
186
- const context = yield* buildImplLayer(bundled.module.default);
199
+ const { context, items } = yield* buildImplLayer(bundled.module.default);
187
200
  const finalizedGroupImpl = yield* Option.match(findFinalizedGroupImpl(context), {
188
201
  onNone: () => new ImplNotFinalizedError({ implPath: implRelativePath }),
189
202
  onSome: Effect.succeed
@@ -203,6 +216,7 @@ const validateImpl = Effect.fn("LeafModule.validateImpl")(function* (leaf) {
203
216
  groupPath: leaf.groupPathDot,
204
217
  missingMiddlewareKeys: missingMiddleware
205
218
  });
219
+ return RegistryItems.missingRequired(items, required, leaf.groupPathDot);
206
220
  });
207
221
  const withImplFiles = Effect.fnUntraced(function* (relativePaths, use) {
208
222
  const fs = yield* FileSystem.FileSystem;
@@ -227,14 +241,12 @@ const withImplFiles = Effect.fnUntraced(function* (relativePaths, use) {
227
241
  }));
228
242
  });
229
243
  const validateImplFiles = Effect.fn("LeafModule.validateImplFiles")((relativePaths) => withImplFiles(relativePaths, validateAllImpls));
230
- const validateAllImpls = Effect.fnUntraced(function* (leaves) {
244
+ const validateAllImpls = Effect.fnUntraced(function* (leaves, required = []) {
231
245
  const path = yield* Path.Path;
232
246
  const confectDirectory = yield* ConfectDirectory.get;
233
247
  const implementationPaths = yield* Effect.forEach(leaves, ({ relativePath }) => implPathForSpec(relativePath).pipe(Effect.map((implPath) => path.resolve(confectDirectory, implPath))));
234
- yield* withBatch(implementationPaths, Effect.forEach(leaves, validateImpl, {
235
- concurrency: VALIDATION_CONCURRENCY,
236
- discard: true
237
- }));
248
+ const missing = (yield* withBatch(implementationPaths, Effect.forEach(leaves, (leaf) => validateImpl(leaf, required), { concurrency: VALIDATION_CONCURRENCY }))).flat().sort((left, right) => left.functionName.localeCompare(right.functionName));
249
+ if (missing.length > 0) return yield* new RequiredMiddlewareError({ missing });
238
250
  });
239
251
  const loadAll = Effect.gen(function* () {
240
252
  const fs = yield* FileSystem.FileSystem;
@@ -1 +1 @@
1
- {"version":3,"file":"LeafModule.mjs","names":["Bundler.importersOfPackage","Bundler.bundle","Bundler.directlyImports","Bundler.withBatch"],"sources":["../src/LeafModule.ts"],"sourcesContent":["import { GroupSpec, MiddlewareAttachment } from \"@confect/core\";\nimport { Registry, type RegistryItems } from \"@confect/server\";\nimport * as GroupImpl from \"@confect/server/GroupImpl\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport type { Context } from \"effect\";\nimport * as Array from \"effect/Array\";\nimport * as Brand from \"effect/Brand\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n MissingImplFileError,\n MissingSpecFileError,\n ImplMissingDefaultLayerError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n ImplMissingSpecImportError,\n ImplNotFinalizedError,\n InvalidMiddlewareAttachmentError,\n SpecImportsServerError,\n SpecMissingDefaultGroupSpecError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ImplModulePath } from \"./ImplModulePath.js\";\nimport { removePathExtension, toPosixPath } from \"./utils.js\";\n\nexport interface LeafModule {\n readonly relativePath: string;\n readonly pathSegments: readonly [string, ...string[]];\n readonly groupPathDot: string;\n readonly exportName: string;\n readonly specImportPath: string;\n}\n\nexport type LoadedLeafModule = LeafModule & {\n readonly spec: GroupSpec.AnyWithProps;\n} & Brand.Brand<\"@confect/cli/LoadedLeafModule\">;\n\nconst LoadedLeafModule = Brand.nominal<LoadedLeafModule>();\n\nconst VALIDATION_CONCURRENCY = 4;\n\nexport const SPEC_SUFFIX = \".spec.ts\";\nexport const IMPL_SUFFIX = \".impl.ts\";\n\nconst swapModuleSuffix = Effect.fnUntraced(function* (\n relativePath: string,\n fromSuffix: string,\n toSuffix: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n if (ext !== \".ts\" || !name.endsWith(fromSuffix.slice(0, -\".ts\".length))) {\n return relativePath;\n }\n\n const stem = name.slice(0, -fromSuffix.slice(0, -\".ts\".length).length);\n const nextName = `${stem}${toSuffix.slice(0, -\".ts\".length)}`;\n return dir.length > 0\n ? path.join(dir, `${nextName}${ext}`)\n : `${nextName}${ext}`;\n});\n\nexport const isLeafSpecPath = (relativePath: string) =>\n relativePath.endsWith(SPEC_SUFFIX);\n\nexport const exportNameFromModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name, ext } = path.parse(relativePath);\n if (ext !== \".ts\") {\n return name;\n }\n return name.endsWith(\".spec\") ? name.slice(0, -\".spec\".length) : name;\n});\n\nexport const groupPathFromRelativeModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n const stem =\n ext === \".ts\" && name.endsWith(\".spec\")\n ? name.slice(0, -\".spec\".length)\n : name;\n const dirSegments = Array.filter(\n String.split(dir, path.sep),\n String.isNonEmpty,\n );\n const pathSegments = Array.append(dirSegments, stem) as [string, ...string[]];\n return {\n pathSegments,\n groupPathDot: Array.join(pathSegments, \".\"),\n };\n});\n\nexport const specImportPathFromGenerated = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const path = yield* Path.Path;\n const withoutExt = toPosixPath(\n path,\n yield* removePathExtension(specRelativePath),\n );\n return `../${withoutExt}.js`;\n});\n\nexport const specPathForImpl = (implRelativePath: string) =>\n swapModuleSuffix(implRelativePath, IMPL_SUFFIX, SPEC_SUFFIX);\n\nexport const implPathForSpec = (specRelativePath: string) =>\n swapModuleSuffix(specRelativePath, SPEC_SUFFIX, IMPL_SUFFIX);\n\nexport const registeredFunctionsRelativePath = Effect.fnUntraced(function* (\n leaf: LeafModule,\n) {\n const path = yield* Path.Path;\n return path.join(\"registeredFunctions\", ...leaf.pathSegments) + \".ts\";\n});\n\nexport const discoverLeafSpecFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n const excludedFiles = HashSet.make(\"nodeSpec.ts\", \"spec.ts\");\n\n const allPaths = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n\n return Array.filter(allPaths, (relativePath) => {\n if (!isLeafSpecPath(relativePath)) {\n return false;\n }\n\n if (HashSet.has(excludedFiles, relativePath)) {\n return false;\n }\n\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n });\n});\n\nexport const discoverLeafImplFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n\n const allPaths = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n\n return Array.filter(\n Array.filterMap(allPaths, (relativePath) =>\n Schema.decodeResult(ImplModulePath)(relativePath),\n ),\n (relativePath) => {\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n },\n );\n});\n\nexport const toLeafModule = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const exportName = yield* exportNameFromModulePath(specRelativePath);\n const { pathSegments, groupPathDot } =\n yield* groupPathFromRelativeModulePath(specRelativePath);\n const specImportPath = yield* specImportPathFromGenerated(specRelativePath);\n\n return {\n relativePath: specRelativePath,\n pathSegments,\n groupPathDot,\n exportName,\n specImportPath,\n } satisfies LeafModule;\n});\n\nconst absoluteModulePath = Effect.fnUntraced(function* (relativePath: string) {\n const confectDirectory = yield* ConfectDirectory.get;\n const path = yield* Path.Path;\n return path.resolve(confectDirectory, relativePath);\n});\n\n/**\n * Every `*.spec.ts` is reachable from `_generated/spec.ts`, which the client\n * imports through `_generated/refs.ts`—so a spec's whole import graph is\n * bundled into the browser whether or not the client calls those functions.\n * Server logic co-located with a declaration therefore ships to users,\n * silently.\n *\n * `@confect/server` is a sound proxy for \"server logic lives here\": an\n * implementation can't be written without `FunctionImpl`/`MiddlewareImpl`, both\n * of which live there. Table `Doc`/`Fields` schemas live in `@confect/core`, so\n * the documented `notes.Doc` pattern in a spec must not reach `@confect/server`\n * even through `tables/` or `_generated/`. The check runs over the spec\n * bundle's transitive inputs rather than the spec module alone, so it also\n * covers middleware declarations under `confect/middleware/` (which codegen\n * otherwise never visits) and any shared helper a spec pulls in—while only ever\n * flagging modules that genuinely reach the client.\n */\nconst validateClientSafety = Effect.fnUntraced(function* (\n leaf: LeafModule,\n bundled: Bundler.Bundled,\n) {\n const path = yield* Path.Path;\n const confectDirectory = path.resolve(yield* ConfectDirectory.get);\n\n const isCheckedUserModule = (absolutePath: string) => {\n const relative = path.relative(confectDirectory, absolutePath);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n };\n\n const importers = Bundler.importersOfPackage(\n bundled,\n \"@confect/server\",\n isCheckedUserModule,\n );\n\n if (importers.length > 0) {\n return yield* new SpecImportsServerError({\n specPath: leaf.relativePath,\n importerPaths: Array.map(importers, (absolutePath) =>\n toPosixPath(path, path.relative(confectDirectory, absolutePath)),\n ),\n });\n }\n});\n\n/**\n * Validate that the leaf's spec file default-exports a `GroupSpec`, and that\n * nothing it reaches drags server code into the client (see\n * {@link validateClientSafety}). Returns the leaf paired with its validated\n * spec, so subsequent operations reuse that association without re-bundling.\n * The runtime is declared by the spec, not its file location.\n */\nexport const loadSpec = Effect.fn(\"LeafModule.loadSpec\")(function* (\n leaf: LeafModule,\n) {\n const absolutePath = yield* absoluteModulePath(leaf.relativePath);\n const bundled = yield* Bundler.bundle(absolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(leaf.relativePath, error)),\n );\n\n const groupSpec = bundled.module.default;\n\n if (!GroupSpec.isGroupSpec(groupSpec)) {\n return yield* new SpecMissingDefaultGroupSpecError({\n specPath: leaf.relativePath,\n });\n }\n\n yield* validateClientSafety(leaf, bundled);\n\n yield* Effect.fromResult(GroupSpec.validateMiddleware(groupSpec)).pipe(\n Effect.mapError(\n (error) =>\n new InvalidMiddlewareAttachmentError({\n specPath: leaf.relativePath,\n message: MiddlewareAttachment.formatValidationError(error),\n }),\n ),\n );\n\n return LoadedLeafModule({\n ...leaf,\n spec: groupSpec,\n });\n});\n\n/**\n * Walk the built `Context` for a `Finalized` `GroupImpl` service value. The\n * lookup is value-shaped (via `GroupImpl.isFinalizedGroupImpl`) so we don't\n * need to know the group's path up front to construct a typed tag for it.\n */\nconst findFinalizedGroupImpl = <S>(\n context: Context.Context<S>,\n): Option.Option<GroupImpl.AnyFinalized> =>\n Array.findFirst(context.mapUnsafe.values(), GroupImpl.isFinalizedGroupImpl);\n\n/**\n * Build the impl layer with a fresh `Registry` so each validation is isolated\n * from prior validations' `FunctionImpl.make` writes. The CLI no longer reads\n * the registry directly—`GroupImpl.finalize` snapshots the registered function\n * names onto the produced `Finalized` `GroupImpl` service value—but a fresh\n * `Ref` is still required because the default `Context.Reference` is cached\n * globally and would otherwise accumulate items across impls.\n */\nconst buildImplLayer = Effect.fnUntraced(function* (\n implLayer: Layer.Layer<unknown>,\n) {\n const registry = Ref.makeUnsafe<RegistryItems.RegistryItems>({});\n return yield* Layer.build(\n implLayer as Layer.Layer<unknown, never, never>,\n ).pipe(Effect.provideService(Registry.Registry, registry));\n}, Effect.scoped);\n\n/**\n * Validate that the leaf's sibling impl file imports the spec, default-exports\n * a finalized `GroupImpl` layer, and provides a `FunctionImpl` for every\n * function declared by the spec.\n */\nexport const validateImpl = Effect.fn(\"LeafModule.validateImpl\")(function* (\n leaf: LoadedLeafModule,\n) {\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const implAbsolutePath = yield* absoluteModulePath(implRelativePath);\n const specAbsolutePath = yield* absoluteModulePath(leaf.relativePath);\n\n const bundled = yield* Bundler.bundle(implAbsolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(implRelativePath, error)),\n );\n\n if (\n !(yield* Bundler.directlyImports(\n bundled,\n implAbsolutePath,\n specAbsolutePath,\n ))\n ) {\n return yield* new ImplMissingSpecImportError({\n implPath: implRelativePath,\n expectedSpecPath: leaf.relativePath,\n });\n }\n\n if (!Layer.isLayer(bundled.module.default)) {\n return yield* new ImplMissingDefaultLayerError({\n implPath: implRelativePath,\n });\n }\n\n const groupSpec = leaf.spec;\n const expectedFunctionNames = Object.keys(groupSpec.functions);\n\n const context = yield* buildImplLayer(\n bundled.module.default as Layer.Layer<unknown>,\n );\n const finalizedGroupImpl = yield* Option.match(\n findFinalizedGroupImpl(context),\n {\n onNone: () => new ImplNotFinalizedError({ implPath: implRelativePath }),\n onSome: Effect.succeed,\n },\n );\n\n const registeredSet = HashSet.fromIterable(\n finalizedGroupImpl.registeredFunctionNames,\n );\n const missing = expectedFunctionNames.filter(\n (name) => !HashSet.has(registeredSet, name),\n );\n\n if (missing.length > 0) {\n return yield* new ImplMissingFunctionsError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingFunctionNames: missing,\n });\n }\n\n const expectedMiddlewareKeys = Array.dedupe([\n ...(groupSpec.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ...Object.values(groupSpec.functions).flatMap((function_) =>\n (function_.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ),\n ]);\n const registeredMiddlewareKeys = HashSet.fromIterable(\n finalizedGroupImpl.registeredMiddlewareKeys ?? [],\n );\n const missingMiddleware = Array.filter(\n expectedMiddlewareKeys,\n (key) => !HashSet.has(registeredMiddlewareKeys, key),\n );\n\n if (missingMiddleware.length > 0) {\n return yield* new ImplMissingMiddlewareError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingMiddlewareKeys: missingMiddleware,\n });\n }\n});\n\nexport const withImplFiles = Effect.fnUntraced(function* <A, E, R>(\n relativePaths: ReadonlyArray<ImplModulePath>,\n use: (leaves: ReadonlyArray<LoadedLeafModule>) => Effect.Effect<A, E, R>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const pairs = yield* Effect.forEach(relativePaths, (implRelativePath) =>\n specPathForImpl(implRelativePath).pipe(\n Effect.map((specRelativePath) => ({\n implRelativePath,\n specRelativePath,\n })),\n ),\n );\n\n return yield* Bundler.withBatch(\n pairs.flatMap(({ implRelativePath, specRelativePath }) => [\n path.resolve(confectDirectory, implRelativePath),\n path.resolve(confectDirectory, specRelativePath),\n ]),\n Effect.gen(function* () {\n const leaves = yield* Effect.forEach(\n pairs,\n Effect.fnUntraced(function* ({ implRelativePath, specRelativePath }) {\n if (\n !(yield* fs.exists(path.join(confectDirectory, specRelativePath)))\n ) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n if (\n !(yield* fs.exists(path.join(confectDirectory, implRelativePath)))\n ) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n const leaf = yield* loadSpec(yield* toLeafModule(specRelativePath));\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n );\n return yield* use(leaves);\n }),\n );\n});\n\nexport const validateImplFiles = Effect.fn(\"LeafModule.validateImplFiles\")(\n (relativePaths: ReadonlyArray<ImplModulePath>) =>\n withImplFiles(relativePaths, validateAllImpls),\n);\n\nexport const validateAllImpls = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implementationPaths = yield* Effect.forEach(\n leaves,\n ({ relativePath }) =>\n implPathForSpec(relativePath).pipe(\n Effect.map((implPath) => path.resolve(confectDirectory, implPath)),\n ),\n );\n yield* Bundler.withBatch(\n implementationPaths,\n Effect.forEach(leaves, validateImpl, {\n concurrency: VALIDATION_CONCURRENCY,\n discard: true,\n }),\n );\n});\n\nexport const loadAll = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const specFiles = yield* discoverLeafSpecFiles;\n\n const results = yield* Bundler.withBatch(\n specFiles.map((relativePath) =>\n path.resolve(confectDirectory, relativePath),\n ),\n Effect.forEach(\n specFiles,\n Effect.fnUntraced(function* (specRelativePath: string) {\n const discovered = yield* toLeafModule(specRelativePath);\n const leaf = yield* loadSpec(discovered);\n\n const implRelativePath = yield* implPathForSpec(specRelativePath);\n const implAbsolutePath = path.join(confectDirectory, implRelativePath);\n if (!(yield* fs.exists(implAbsolutePath))) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n ),\n );\n\n yield* validateOrphanImpls(specFiles);\n\n return results;\n});\n\n/**\n * Walk leaf ancestors and fail with a {@link ParentChildNameCollisionError} when\n * a parent leaf declares a function or subgroup whose name matches a sibling\n * subdirectory spec's segment. Without this check the colliding descendant\n * would overwrite the parent's entry in the assembled `GroupSpec.groups` map at\n * runtime, surfacing as a confusing `Refs.make` error rather than a\n * codegen-time diagnostic.\n */\nconst validateOrphanImpls = Effect.fnUntraced(function* (\n specFiles: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implFiles = yield* discoverLeafImplFiles;\n const specPaths = HashSet.fromIterable(specFiles);\n\n yield* Effect.forEach(\n implFiles,\n Effect.fnUntraced(function* (implRelativePath: string) {\n const specRelativePath = yield* specPathForImpl(implRelativePath);\n if (HashSet.has(specPaths, specRelativePath)) {\n return;\n }\n\n const specAbsolutePath = path.join(confectDirectory, specRelativePath);\n if (!(yield* fs.exists(specAbsolutePath))) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,mBAAmB,MAAM,QAA0B;AAEzD,MAAM,yBAAyB;AAE/B,MAAa,cAAc;AAC3B,MAAa,cAAc;AAE3B,MAAM,mBAAmB,OAAO,WAAW,WACzC,cACA,YACA,UACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,EAAE,KAAK,MAAM,QAAQ,KAAK,MAAM,YAAY;CAClD,IAAI,QAAQ,SAAS,CAAC,KAAK,SAAS,WAAW,MAAM,GAAG,EAAa,CAAC,GACpE,OAAO;CAIT,MAAM,WAAW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,QACL,WACA,OAAO,WAAW,WAAW,kBAA0B;EACrD,MAAM,aAAa,OAAO,aAAa,gBAAgB;EACvD,MAAM,OAAO,OAAO,SAAS,UAAU;EAEvC,MAAM,mBAAmB,OAAO,gBAAgB,gBAAgB;EAChE,MAAM,mBAAmB,KAAK,KAAK,kBAAkB,gBAAgB;EACrE,IAAI,EAAE,OAAO,GAAG,OAAO,gBAAgB,IACrC,OAAO,OAAO,IAAI,qBAAqB;GACrC,UAAU;GACV,kBAAkB;EACpB,CAAC;EAGH,OAAO;CACT,CAAC,GACD,EAAE,aAAa,uBAAuB,CACxC,CACF;CAEA,OAAO,oBAAoB,SAAS;CAEpC,OAAO;AACT,CAAC;;;;;;;;;AAUD,MAAM,sBAAsB,OAAO,WAAW,WAC5C,WACA;CACA,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,mBAAmB,OAAO,iBAAiB;CACjD,MAAM,YAAY,OAAO;CACzB,MAAM,YAAY,QAAQ,aAAa,SAAS;CAEhD,OAAO,OAAO,QACZ,WACA,OAAO,WAAW,WAAW,kBAA0B;EACrD,MAAM,mBAAmB,OAAO,gBAAgB,gBAAgB;EAChE,IAAI,QAAQ,IAAI,WAAW,gBAAgB,GACzC;EAGF,MAAM,mBAAmB,KAAK,KAAK,kBAAkB,gBAAgB;EACrE,IAAI,EAAE,OAAO,GAAG,OAAO,gBAAgB,IACrC,OAAO,OAAO,IAAI,qBAAqB;GACrC,UAAU;GACV,kBAAkB;EACpB,CAAC;CAEL,CAAC,CACH;AACF,CAAC"}
1
+ {"version":3,"file":"LeafModule.mjs","names":["Bundler.importersOfPackage","Bundler.bundle","Bundler.directlyImports","Bundler.withBatch"],"sources":["../src/LeafModule.ts"],"sourcesContent":["import { GroupSpec, MiddlewareAttachment } from \"@confect/core\";\nimport { Registry, RegistryItems } from \"@confect/server\";\nimport * as GroupImpl from \"@confect/server/GroupImpl\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport type { Context } from \"effect\";\nimport * as Array from \"effect/Array\";\nimport * as Brand from \"effect/Brand\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as String from \"effect/String\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidDeclarationError,\n MissingImplFileError,\n MissingSpecFileError,\n ImplMissingDefaultLayerError,\n ImplMissingFunctionsError,\n ImplMissingMiddlewareError,\n RequiredMiddlewareError,\n ImplMissingSpecImportError,\n ImplNotFinalizedError,\n InvalidMiddlewareAttachmentError,\n SpecImportsServerError,\n SpecMissingDefaultGroupSpecError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ImplModulePath } from \"./ImplModulePath.js\";\nimport { removePathExtension, toPosixPath } from \"./utils.js\";\n\nexport interface LeafModule {\n readonly relativePath: string;\n readonly pathSegments: readonly [string, ...string[]];\n readonly groupPathDot: string;\n readonly exportName: string;\n readonly specImportPath: string;\n}\n\nexport type LoadedLeafModule = LeafModule & {\n readonly spec: GroupSpec.AnyWithProps;\n} & Brand.Brand<\"@confect/cli/LoadedLeafModule\">;\n\nconst LoadedLeafModule = Brand.nominal<LoadedLeafModule>();\n\nconst VALIDATION_CONCURRENCY = 4;\n\nexport const SPEC_SUFFIX = \".spec.ts\";\nexport const IMPL_SUFFIX = \".impl.ts\";\n\nconst swapModuleSuffix = Effect.fnUntraced(function* (\n relativePath: string,\n fromSuffix: string,\n toSuffix: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n if (ext !== \".ts\" || !name.endsWith(fromSuffix.slice(0, -\".ts\".length))) {\n return relativePath;\n }\n\n const stem = name.slice(0, -fromSuffix.slice(0, -\".ts\".length).length);\n const nextName = `${stem}${toSuffix.slice(0, -\".ts\".length)}`;\n return dir.length > 0\n ? path.join(dir, `${nextName}${ext}`)\n : `${nextName}${ext}`;\n});\n\nexport const isLeafSpecPath = (relativePath: string) =>\n relativePath.endsWith(SPEC_SUFFIX);\n\nexport const exportNameFromModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { name, ext } = path.parse(relativePath);\n if (ext !== \".ts\") {\n return name;\n }\n return name.endsWith(\".spec\") ? name.slice(0, -\".spec\".length) : name;\n});\n\nexport const groupPathFromRelativeModulePath = Effect.fnUntraced(function* (\n relativePath: string,\n) {\n const path = yield* Path.Path;\n const { dir, name, ext } = path.parse(relativePath);\n const stem =\n ext === \".ts\" && name.endsWith(\".spec\")\n ? name.slice(0, -\".spec\".length)\n : name;\n const dirSegments = Array.filter(\n String.split(dir, path.sep),\n String.isNonEmpty,\n );\n const pathSegments = Array.append(dirSegments, stem) as [string, ...string[]];\n return {\n pathSegments,\n groupPathDot: Array.join(pathSegments, \".\"),\n };\n});\n\nexport const specImportPathFromGenerated = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const path = yield* Path.Path;\n const withoutExt = toPosixPath(\n path,\n yield* removePathExtension(specRelativePath),\n );\n return `../${withoutExt}.js`;\n});\n\nexport const specPathForImpl = (implRelativePath: string) =>\n swapModuleSuffix(implRelativePath, IMPL_SUFFIX, SPEC_SUFFIX);\n\nexport const implPathForSpec = (specRelativePath: string) =>\n swapModuleSuffix(specRelativePath, SPEC_SUFFIX, IMPL_SUFFIX);\n\nexport const registeredFunctionsRelativePath = Effect.fnUntraced(function* (\n leaf: LeafModule,\n) {\n const path = yield* Path.Path;\n return path.join(\"registeredFunctions\", ...leaf.pathSegments) + \".ts\";\n});\n\nexport const discoverLeafSpecFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n const excludedFiles = HashSet.make(\"nodeSpec.ts\", \"spec.ts\");\n\n const allPaths = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n\n return Array.filter(allPaths, (relativePath) => {\n if (!isLeafSpecPath(relativePath)) {\n return false;\n }\n\n if (HashSet.has(excludedFiles, relativePath)) {\n return false;\n }\n\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n });\n});\n\nexport const discoverLeafImplFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const excludedDirs = HashSet.make(\"_generated\", \"tables\", \"middleware\");\n\n const allPaths = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n\n return Array.filter(\n Array.filterMap(allPaths, (relativePath) =>\n Schema.decodeResult(ImplModulePath)(relativePath),\n ),\n (relativePath) => {\n const segments = String.split(relativePath, path.sep);\n return !Array.some(segments, (segment) =>\n HashSet.has(excludedDirs, segment),\n );\n },\n );\n});\n\nexport const toLeafModule = Effect.fnUntraced(function* (\n specRelativePath: string,\n) {\n const exportName = yield* exportNameFromModulePath(specRelativePath);\n const { pathSegments, groupPathDot } =\n yield* groupPathFromRelativeModulePath(specRelativePath);\n const specImportPath = yield* specImportPathFromGenerated(specRelativePath);\n\n return {\n relativePath: specRelativePath,\n pathSegments,\n groupPathDot,\n exportName,\n specImportPath,\n } satisfies LeafModule;\n});\n\nconst absoluteModulePath = Effect.fnUntraced(function* (relativePath: string) {\n const confectDirectory = yield* ConfectDirectory.get;\n const path = yield* Path.Path;\n return path.resolve(confectDirectory, relativePath);\n});\n\n/**\n * Every `*.spec.ts` is reachable from `_generated/spec.ts`, which the client\n * imports through `_generated/refs.ts`—so a spec's whole import graph is\n * bundled into the browser whether or not the client calls those functions.\n * Server logic co-located with a declaration therefore ships to users,\n * silently.\n *\n * `@confect/server` is a sound proxy for \"server logic lives here\": an\n * implementation can't be written without `FunctionImpl`/`MiddlewareImpl`, both\n * of which live there. Table `Doc`/`Fields` schemas live in `@confect/core`, so\n * the documented `notes.Doc` pattern in a spec must not reach `@confect/server`\n * even through `tables/` or `_generated/`. The check runs over the spec\n * bundle's transitive inputs rather than the spec module alone, so it also\n * covers middleware declarations under `confect/middleware/` (which codegen\n * otherwise never visits) and any shared helper a spec pulls in—while only ever\n * flagging modules that genuinely reach the client.\n */\nconst validateClientSafety = Effect.fnUntraced(function* (\n leaf: LeafModule,\n bundled: Bundler.Bundled,\n) {\n const path = yield* Path.Path;\n const confectDirectory = path.resolve(yield* ConfectDirectory.get);\n\n const isCheckedUserModule = (absolutePath: string) => {\n const relative = path.relative(confectDirectory, absolutePath);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n };\n\n const importers = Bundler.importersOfPackage(\n bundled,\n \"@confect/server\",\n isCheckedUserModule,\n );\n\n if (importers.length > 0) {\n return yield* new SpecImportsServerError({\n specPath: leaf.relativePath,\n importerPaths: Array.map(importers, (absolutePath) =>\n toPosixPath(path, path.relative(confectDirectory, absolutePath)),\n ),\n });\n }\n});\n\nconst validateReservedArguments = Effect.fnUntraced(function* (\n group: GroupSpec.AnyWithProps,\n specPath: string,\n groupPath: string,\n): Effect.fn.Return<void, InvalidDeclarationError> {\n for (const spec of Object.values(group.functions)) {\n const name = spec.reservedArgument;\n const provenance = spec.functionProvenance;\n if (\n name !== undefined &&\n provenance._tag === \"Confect\" &&\n Object.hasOwn(provenance.args.fields, name)\n ) {\n return yield* new InvalidDeclarationError({\n declarationPath: `confect/${specPath}`,\n reason: `${groupPath}:${spec.name} declares the argument \"${name}\", which its profile reserves. Rename the argument.`,\n });\n }\n }\n for (const [name, child] of Object.entries(group.groups)) {\n yield* validateReservedArguments(child, specPath, `${groupPath}/${name}`);\n }\n});\n\n/**\n * Validate that the leaf's spec file default-exports a `GroupSpec`, and that\n * nothing it reaches drags server code into the client (see\n * {@link validateClientSafety}). Returns the leaf paired with its validated\n * spec, so subsequent operations reuse that association without re-bundling.\n * The runtime is declared by the spec, not its file location.\n */\nexport const loadSpec = Effect.fn(\"LeafModule.loadSpec\")(function* (\n leaf: LeafModule,\n) {\n const absolutePath = yield* absoluteModulePath(leaf.relativePath);\n const bundled = yield* Bundler.bundle(absolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(leaf.relativePath, error)),\n );\n\n const groupSpec = bundled.module.default;\n\n if (!GroupSpec.isGroupSpec(groupSpec)) {\n return yield* new SpecMissingDefaultGroupSpecError({\n specPath: leaf.relativePath,\n });\n }\n\n yield* validateClientSafety(leaf, bundled);\n yield* validateReservedArguments(\n groupSpec,\n leaf.relativePath,\n leaf.pathSegments.join(\"/\"),\n );\n\n yield* Effect.fromResult(GroupSpec.validateMiddleware(groupSpec)).pipe(\n Effect.mapError(\n (error) =>\n new InvalidMiddlewareAttachmentError({\n specPath: leaf.relativePath,\n message: MiddlewareAttachment.formatValidationError(error),\n }),\n ),\n );\n\n return LoadedLeafModule({\n ...leaf,\n spec: groupSpec,\n });\n});\n\n/**\n * Walk the built `Context` for a `Finalized` `GroupImpl` service value. The\n * lookup is value-shaped (via `GroupImpl.isFinalizedGroupImpl`) so we don't\n * need to know the group's path up front to construct a typed tag for it.\n */\nconst findFinalizedGroupImpl = <S>(\n context: Context.Context<S>,\n): Option.Option<GroupImpl.AnyFinalized> =>\n Array.findFirst(context.mapUnsafe.values(), GroupImpl.isFinalizedGroupImpl);\n\n/**\n * Build the impl layer with a fresh `Registry` so each validation is isolated\n * from prior validations' `FunctionImpl.make` writes. Retain its items to check\n * required middleware against actual function attachments.\n */\nconst buildImplLayer = Effect.fnUntraced(function* (\n implLayer: Layer.Layer<unknown>,\n) {\n const registry = Ref.makeUnsafe<RegistryItems.RegistryItems>({});\n const context = yield* Layer.build(\n implLayer as Layer.Layer<unknown, never, never>,\n ).pipe(Effect.provideService(Registry.Registry, registry));\n return { context, items: yield* Ref.get(registry) };\n}, Effect.scoped);\n\n/**\n * Validate that the leaf's sibling impl file imports the spec, default-exports\n * a finalized `GroupImpl` layer, and provides a `FunctionImpl` for every\n * function declared by the spec. Return uncovered middleware requirements for\n * the caller to report across groups.\n */\nexport const validateImpl = Effect.fn(\"LeafModule.validateImpl\")(function* (\n leaf: LoadedLeafModule,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const implAbsolutePath = yield* absoluteModulePath(implRelativePath);\n const specAbsolutePath = yield* absoluteModulePath(leaf.relativePath);\n\n const bundled = yield* Bundler.bundle(implAbsolutePath).pipe(\n Effect.mapError((error) => fromBundlerError(implRelativePath, error)),\n );\n\n if (\n !(yield* Bundler.directlyImports(\n bundled,\n implAbsolutePath,\n specAbsolutePath,\n ))\n ) {\n return yield* new ImplMissingSpecImportError({\n implPath: implRelativePath,\n expectedSpecPath: leaf.relativePath,\n });\n }\n\n if (!Layer.isLayer(bundled.module.default)) {\n return yield* new ImplMissingDefaultLayerError({\n implPath: implRelativePath,\n });\n }\n\n const groupSpec = leaf.spec;\n const expectedFunctionNames = Object.keys(groupSpec.functions);\n\n const { context, items } = yield* buildImplLayer(\n bundled.module.default as Layer.Layer<unknown>,\n );\n const finalizedGroupImpl = yield* Option.match(\n findFinalizedGroupImpl(context),\n {\n onNone: () => new ImplNotFinalizedError({ implPath: implRelativePath }),\n onSome: Effect.succeed,\n },\n );\n\n const registeredSet = HashSet.fromIterable(\n finalizedGroupImpl.registeredFunctionNames,\n );\n const missing = expectedFunctionNames.filter(\n (name) => !HashSet.has(registeredSet, name),\n );\n\n if (missing.length > 0) {\n return yield* new ImplMissingFunctionsError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingFunctionNames: missing,\n });\n }\n\n const expectedMiddlewareKeys = Array.dedupe([\n ...(groupSpec.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ...Object.values(groupSpec.functions).flatMap((function_) =>\n (function_.middlewareSpecs ?? []).map(\n (middlewareSpec) => middlewareSpec.key,\n ),\n ),\n ]);\n const registeredMiddlewareKeys = HashSet.fromIterable(\n finalizedGroupImpl.registeredMiddlewareKeys ?? [],\n );\n const missingMiddleware = Array.filter(\n expectedMiddlewareKeys,\n (key) => !HashSet.has(registeredMiddlewareKeys, key),\n );\n\n if (missingMiddleware.length > 0) {\n return yield* new ImplMissingMiddlewareError({\n implPath: implRelativePath,\n groupPath: leaf.groupPathDot,\n missingMiddlewareKeys: missingMiddleware,\n });\n }\n\n return RegistryItems.missingRequired(items, required, leaf.groupPathDot);\n});\n\nexport const withImplFiles = Effect.fnUntraced(function* <A, E, R>(\n relativePaths: ReadonlyArray<ImplModulePath>,\n use: (leaves: ReadonlyArray<LoadedLeafModule>) => Effect.Effect<A, E, R>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const pairs = yield* Effect.forEach(relativePaths, (implRelativePath) =>\n specPathForImpl(implRelativePath).pipe(\n Effect.map((specRelativePath) => ({\n implRelativePath,\n specRelativePath,\n })),\n ),\n );\n\n return yield* Bundler.withBatch(\n pairs.flatMap(({ implRelativePath, specRelativePath }) => [\n path.resolve(confectDirectory, implRelativePath),\n path.resolve(confectDirectory, specRelativePath),\n ]),\n Effect.gen(function* () {\n const leaves = yield* Effect.forEach(\n pairs,\n Effect.fnUntraced(function* ({ implRelativePath, specRelativePath }) {\n if (\n !(yield* fs.exists(path.join(confectDirectory, specRelativePath)))\n ) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n if (\n !(yield* fs.exists(path.join(confectDirectory, implRelativePath)))\n ) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n const leaf = yield* loadSpec(yield* toLeafModule(specRelativePath));\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n );\n return yield* use(leaves);\n }),\n );\n});\n\nexport const validateImplFiles = Effect.fn(\"LeafModule.validateImplFiles\")(\n (relativePaths: ReadonlyArray<ImplModulePath>) =>\n withImplFiles(relativePaths, validateAllImpls),\n);\n\nexport const validateAllImpls = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implementationPaths = yield* Effect.forEach(\n leaves,\n ({ relativePath }) =>\n implPathForSpec(relativePath).pipe(\n Effect.map((implPath) => path.resolve(confectDirectory, implPath)),\n ),\n );\n const missing = (yield* Bundler.withBatch(\n implementationPaths,\n Effect.forEach(leaves, (leaf) => validateImpl(leaf, required), {\n concurrency: VALIDATION_CONCURRENCY,\n }),\n ))\n .flat()\n .sort((left, right) => left.functionName.localeCompare(right.functionName));\n if (missing.length > 0) {\n return yield* new RequiredMiddlewareError({ missing });\n }\n});\n\nexport const loadAll = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const specFiles = yield* discoverLeafSpecFiles;\n\n const results = yield* Bundler.withBatch(\n specFiles.map((relativePath) =>\n path.resolve(confectDirectory, relativePath),\n ),\n Effect.forEach(\n specFiles,\n Effect.fnUntraced(function* (specRelativePath: string) {\n const discovered = yield* toLeafModule(specRelativePath);\n const leaf = yield* loadSpec(discovered);\n\n const implRelativePath = yield* implPathForSpec(specRelativePath);\n const implAbsolutePath = path.join(confectDirectory, implRelativePath);\n if (!(yield* fs.exists(implAbsolutePath))) {\n return yield* new MissingImplFileError({\n specPath: specRelativePath,\n expectedImplPath: implRelativePath,\n });\n }\n\n return leaf;\n }),\n { concurrency: VALIDATION_CONCURRENCY },\n ),\n );\n\n yield* validateOrphanImpls(specFiles);\n\n return results;\n});\n\n/**\n * Walk leaf ancestors and fail with a {@link ParentChildNameCollisionError} when\n * a parent leaf declares a function or subgroup whose name matches a sibling\n * subdirectory spec's segment. Without this check the colliding descendant\n * would overwrite the parent's entry in the assembled `GroupSpec.groups` map at\n * runtime, surfacing as a confusing `Refs.make` error rather than a\n * codegen-time diagnostic.\n */\nconst validateOrphanImpls = Effect.fnUntraced(function* (\n specFiles: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const implFiles = yield* discoverLeafImplFiles;\n const specPaths = HashSet.fromIterable(specFiles);\n\n yield* Effect.forEach(\n implFiles,\n Effect.fnUntraced(function* (implRelativePath: string) {\n const specRelativePath = yield* specPathForImpl(implRelativePath);\n if (HashSet.has(specPaths, specRelativePath)) {\n return;\n }\n\n const specAbsolutePath = path.join(confectDirectory, specRelativePath);\n if (!(yield* fs.exists(specAbsolutePath))) {\n return yield* new MissingSpecFileError({\n implPath: implRelativePath,\n expectedSpecPath: specRelativePath,\n });\n }\n }),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,mBAAmB,MAAM,QAA0B;AAEzD,MAAM,yBAAyB;AAE/B,MAAa,cAAc;AAC3B,MAAa,cAAc;AAE3B,MAAM,mBAAmB,OAAO,WAAW,WACzC,cACA,YACA,UACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,EAAE,KAAK,MAAM,QAAQ,KAAK,MAAM,YAAY;CAClD,IAAI,QAAQ,SAAS,CAAC,KAAK,SAAS,WAAW,MAAM,GAAG,EAAa,CAAC,GACpE,OAAO;CAIT,MAAM,WAAW,GADJ,KAAK,MAAM,GAAG,CAAC,WAAW,MAAM,GAAG,EAAa,CAAC,CAAC,MACxC,IAAI,SAAS,MAAM,GAAG,EAAa;CAC1D,OAAO,IAAI,SAAS,IAChB,KAAK,KAAK,KAAK,GAAG,WAAW,KAAK,IAClC,GAAG,WAAW;AACpB,CAAC;AAED,MAAa,kBAAkB,iBAC7B,aAAa,SAAS,WAAW;AAEnC,MAAa,2BAA2B,OAAO,WAAW,WACxD,cACA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M,YAAY,QAAQ,aAAa,SAAS;CAEhD,OAAO,OAAO,QACZ,WACA,OAAO,WAAW,WAAW,kBAA0B;EACrD,MAAM,mBAAmB,OAAO,gBAAgB,gBAAgB;EAChE,IAAI,QAAQ,IAAI,WAAW,gBAAgB,GACzC;EAGF,MAAM,mBAAmB,KAAK,KAAK,kBAAkB,gBAAgB;EACrE,IAAI,EAAE,OAAO,GAAG,OAAO,gBAAgB,IACrC,OAAO,OAAO,IAAI,qBAAqB;GACrC,UAAU;GACV,kBAAkB;EACpB,CAAC;CAEL,CAAC,CACH;AACF,CAAC"}
@@ -0,0 +1,125 @@
1
+ import { InvalidDeclarationError, InvalidManifestSectionError } from "./CodegenError.mjs";
2
+ import * as Result from "effect/Result";
3
+ import * as Schema from "effect/Schema";
4
+ import * as Predicate from "effect/Predicate";
5
+ //#region src/ManifestSections.ts
6
+ const reserved = new Set("name env http digest __proto__ constructor prototype".split(" "));
7
+ const sections = (manifest) => Object.fromEntries(Object.entries(manifest).filter(([key]) => !reserved.has(key)));
8
+ const nonJsonPath = (value, path = "$", ancestors = []) => {
9
+ if (value === null || ["string", "boolean"].includes(typeof value)) return void 0;
10
+ if (typeof value === "number") return Number.isFinite(value) ? void 0 : path;
11
+ if (typeof value !== "object" || ancestors.includes(value)) return path;
12
+ const isArray = Array.isArray(value);
13
+ if (!(isArray ? [Array.prototype] : [Object.prototype, null]).includes(Object.getPrototypeOf(value))) return path;
14
+ const keys = isArray ? Array.from({ length: Object.getOwnPropertyDescriptor(value, "length")?.value }, (_, index) => String(index)) : Reflect.ownKeys(value);
15
+ for (const key of keys) {
16
+ if (typeof key === "symbol") return path;
17
+ const at = `${path}[${JSON.stringify(key)}]`;
18
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
19
+ if (key === "__proto__" || !descriptor?.enumerable || !("value" in descriptor)) return at;
20
+ const found = nonJsonPath(descriptor.value, at, [...ancestors, value]);
21
+ if (found !== void 0) return found;
22
+ }
23
+ return isArray && Reflect.ownKeys(value).length !== keys.length + 1 ? path : void 0;
24
+ };
25
+ const json = (value) => {
26
+ const path = nonJsonPath(value);
27
+ return path === void 0 ? Result.succeed(JSON.parse(JSON.stringify(value))) : Result.fail(`Expected JSON data at ${path}`);
28
+ };
29
+ const hasFormat = (format) => Schema.is(Schema.Struct({ format: Schema.Literal(format) }));
30
+ const collect = (leaves) => Result.gen(function* () {
31
+ const registry = /* @__PURE__ */ new Map();
32
+ const visit = (group, path, source) => Result.gen(function* () {
33
+ for (const spec of Object.values(group.functions)) {
34
+ const functionPath = `${path}:${spec.name}`;
35
+ for (const { key, section } of spec.manifestSections ?? []) {
36
+ const invalid = (reason) => new InvalidDeclarationError({
37
+ declarationPath: `confect/${source}`,
38
+ reason: `Manifest section "${key}" (${functionPath}): ${reason}`
39
+ });
40
+ if (reserved.has(key)) return yield* Result.fail(invalid("shadows a built-in key."));
41
+ const existing = registry.get(key);
42
+ if (existing !== void 0 && (existing.section.owner !== section.owner || existing.section.format !== section.format)) return yield* Result.fail(invalid(`conflicts between ${existing.section.owner} (format ${existing.section.format}) and ${section.owner} (format ${section.format}).`));
43
+ const entry = existing ?? {
44
+ section,
45
+ data: {
46
+ format: section.format,
47
+ functions: Object.create(null)
48
+ },
49
+ sources: Object.create(null)
50
+ };
51
+ registry.set(key, entry);
52
+ const description = yield* Result.try({
53
+ try: () => section.describe({
54
+ path: functionPath,
55
+ spec,
56
+ middleware: [...group.middlewareSpecs, ...spec.middlewareSpecs]
57
+ }),
58
+ catch: (cause) => invalid(String(cause))
59
+ });
60
+ entry.data.functions[functionPath] = yield* Result.mapError(json(description), (reason) => invalid(`could not describe as JSON: ${reason}`));
61
+ entry.sources[functionPath] = source;
62
+ }
63
+ }
64
+ for (const [name, child] of Object.entries(group.groups)) yield* visit(child, `${path}/${name}`, source);
65
+ });
66
+ for (const leaf of leaves) yield* visit(leaf.spec, leaf.pathSegments.join("/"), leaf.relativePath);
67
+ return registry;
68
+ });
69
+ /**
70
+ * Replace the data of each section that has `summarize` with what it returns
71
+ * from its matched modules, its functions' descriptions and their spec files.
72
+ */
73
+ const summarize = (registry, modules) => Result.gen(function* () {
74
+ const summarized = new Map(registry);
75
+ for (const [key, { section, data, sources }] of registry) {
76
+ if (section.summarize === void 0) continue;
77
+ const input = {
78
+ modules: modules.get(key) ?? [],
79
+ functions: data.functions,
80
+ sources
81
+ };
82
+ const invalid = (reason) => new InvalidManifestSectionError({
83
+ sectionKey: key,
84
+ reason
85
+ });
86
+ const summary = yield* Result.try({
87
+ try: () => section.summarize?.(input),
88
+ catch: (cause) => invalid(`summarize failed: ${String(cause)}`)
89
+ });
90
+ const parsed = yield* Result.mapError(json(summary), (reason) => invalid(`could not summarize as JSON: ${reason}`));
91
+ if (!hasFormat(section.format)(parsed)) return yield* Result.fail(invalid(`summarize must return data with format ${section.format}.`));
92
+ summarized.set(key, {
93
+ section,
94
+ data: parsed
95
+ });
96
+ }
97
+ return summarized;
98
+ });
99
+ const check = (registry, previous) => {
100
+ const errors = [];
101
+ const notes = [];
102
+ for (const [key, { section, data }] of registry) try {
103
+ const checked = section.check?.(data, previous[key]);
104
+ if (checked === void 0) continue;
105
+ notes.push(...checked.notes);
106
+ if (checked.errors.length > 0) errors.push(new InvalidManifestSectionError({
107
+ sectionKey: key,
108
+ reason: [...new Set(checked.errors)].join("\n")
109
+ }));
110
+ } catch (cause) {
111
+ errors.push(new InvalidManifestSectionError({
112
+ sectionKey: key,
113
+ reason: `check failed: ${String(cause)}`
114
+ }));
115
+ }
116
+ for (const [key, value] of Object.entries(previous)) if (!reserved.has(key) && !registry.has(key) && Predicate.isObjectOrArray(value) && "functions" in value && Predicate.isObjectOrArray(value.functions)) notes.push(`Manifest section "${key}" no longer has participants. Previous functions: ${Object.keys(value.functions).join(", ")}.`);
117
+ return {
118
+ errors,
119
+ notes
120
+ };
121
+ };
122
+ //#endregion
123
+ export { check, collect, sections, summarize };
124
+
125
+ //# sourceMappingURL=ManifestSections.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ManifestSections.mjs","names":[],"sources":["../src/ManifestSections.ts"],"sourcesContent":["import type { GroupSpec, ManifestSection } from \"@confect/core\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport {\n InvalidDeclarationError,\n InvalidManifestSectionError,\n} from \"./CodegenError.js\";\n\nconst reserved = new Set(\n \"name env http digest __proto__ constructor prototype\".split(\" \"),\n);\nexport const sections = (manifest: Readonly<Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(manifest).filter(([key]) => !reserved.has(key)),\n );\n// Read only property descriptors, through static functions, so no getter,\n// `toJSON` or other method of the input runs before the check and nothing\n// `JSON.stringify` would call, skip or convert passes.\nconst nonJsonPath = (\n value: unknown,\n path = \"$\",\n ancestors: ReadonlyArray<object> = [],\n): string | undefined => {\n if (value === null || [\"string\", \"boolean\"].includes(typeof value))\n return undefined;\n if (typeof value === \"number\")\n return Number.isFinite(value) ? undefined : path;\n if (typeof value !== \"object\" || ancestors.includes(value)) return path;\n const isArray = Array.isArray(value);\n const prototypes = isArray ? [Array.prototype] : [Object.prototype, null];\n if (!prototypes.includes(Object.getPrototypeOf(value))) return path;\n const keys = isArray\n ? Array.from(\n { length: Object.getOwnPropertyDescriptor(value, \"length\")?.value },\n (_, index) => String(index),\n )\n : Reflect.ownKeys(value);\n for (const key of keys) {\n if (typeof key === \"symbol\") return path;\n const at = `${path}[${JSON.stringify(key)}]`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n key === \"__proto__\" ||\n !descriptor?.enumerable ||\n !(\"value\" in descriptor)\n )\n return at;\n const found = nonJsonPath(descriptor.value, at, [...ancestors, value]);\n if (found !== undefined) return found;\n }\n // Every index is an own data property by now, so any other key than `length`\n // is one `JSON.stringify` would drop or call.\n return isArray && Reflect.ownKeys(value).length !== keys.length + 1\n ? path\n : undefined;\n};\nconst json = (value: unknown): Result.Result<unknown, string> => {\n const path = nonJsonPath(value);\n return path === undefined\n ? Result.succeed(JSON.parse(JSON.stringify(value)))\n : Result.fail(`Expected JSON data at ${path}`);\n};\nexport type Registry = Map<\n string,\n {\n section: ManifestSection.Any;\n data: { format: number; functions: Record<string, unknown> };\n sources: Record<string, string>;\n }\n>;\nconst hasFormat = (format: number) =>\n Schema.is(Schema.Struct({ format: Schema.Literal(format) }));\ntype Summarized = {\n readonly section: ManifestSection.Any;\n readonly data: { readonly format: number };\n};\n\nexport const collect = (\n leaves: ReadonlyArray<\n Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">\n >,\n) =>\n Result.gen(function* () {\n const registry: Registry = new Map();\n const visit = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ): Result.Result<void, InvalidDeclarationError> =>\n Result.gen(function* () {\n for (const spec of Object.values(group.functions)) {\n const functionPath = `${path}:${spec.name}`;\n for (const { key, section } of spec.manifestSections ?? []) {\n const invalid = (reason: string) =>\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `Manifest section \"${key}\" (${functionPath}): ${reason}`,\n });\n if (reserved.has(key))\n return yield* Result.fail(invalid(\"shadows a built-in key.\"));\n const existing = registry.get(key);\n if (\n existing !== undefined &&\n (existing.section.owner !== section.owner ||\n existing.section.format !== section.format)\n )\n return yield* Result.fail(\n invalid(\n `conflicts between ${existing.section.owner} (format ${existing.section.format}) and ${section.owner} (format ${section.format}).`,\n ),\n );\n const entry = existing ?? {\n section,\n data: {\n format: section.format,\n functions: Object.create(null) as Record<string, unknown>,\n },\n sources: Object.create(null) as Record<string, string>,\n };\n registry.set(key, entry);\n const description = yield* Result.try({\n try: () =>\n section.describe({\n path: functionPath,\n spec,\n middleware: [\n ...group.middlewareSpecs,\n ...spec.middlewareSpecs,\n ],\n }),\n catch: (cause) => invalid(String(cause)),\n });\n entry.data.functions[functionPath] = yield* Result.mapError(\n json(description),\n (reason) => invalid(`could not describe as JSON: ${reason}`),\n );\n entry.sources[functionPath] = source;\n }\n }\n for (const [name, child] of Object.entries(group.groups))\n yield* visit(child, `${path}/${name}`, source);\n });\n for (const leaf of leaves)\n yield* visit(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n return registry;\n });\n\n/**\n * Replace the data of each section that has `summarize` with what it returns\n * from its matched modules, its functions' descriptions and their spec files.\n */\nexport const summarize = (\n registry: Registry,\n modules: ReadonlyMap<string, ManifestSection.GenerateInput[\"modules\"]>,\n) =>\n Result.gen(function* () {\n const summarized = new Map<string, Summarized>(registry);\n for (const [key, { section, data, sources }] of registry) {\n if (section.summarize === undefined) continue;\n const input = {\n modules: modules.get(key) ?? [],\n functions: data.functions,\n sources,\n };\n const invalid = (reason: string) =>\n new InvalidManifestSectionError({ sectionKey: key, reason });\n const summary = yield* Result.try({\n try: () => section.summarize?.(input),\n catch: (cause) => invalid(`summarize failed: ${String(cause)}`),\n });\n const parsed = yield* Result.mapError(json(summary), (reason) =>\n invalid(`could not summarize as JSON: ${reason}`),\n );\n if (!hasFormat(section.format)(parsed))\n return yield* Result.fail(\n invalid(`summarize must return data with format ${section.format}.`),\n );\n summarized.set(key, { section, data: parsed });\n }\n return summarized;\n });\n\nexport const check = (\n registry: ReadonlyMap<string, Summarized>,\n previous: Readonly<Record<string, unknown>>,\n) => {\n const errors: InvalidManifestSectionError[] = [];\n const notes: string[] = [];\n for (const [key, { section, data }] of registry) {\n try {\n const checked = section.check?.(data, previous[key]);\n if (checked === undefined) continue;\n notes.push(...checked.notes);\n if (checked.errors.length > 0)\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: [...new Set(checked.errors)].join(\"\\n\"),\n }),\n );\n } catch (cause) {\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `check failed: ${String(cause)}`,\n }),\n );\n }\n }\n for (const [key, value] of Object.entries(previous)) {\n if (\n !reserved.has(key) &&\n !registry.has(key) &&\n Predicate.isObjectOrArray(value) &&\n \"functions\" in value &&\n Predicate.isObjectOrArray(value.functions)\n )\n notes.push(\n `Manifest section \"${key}\" no longer has participants. Previous functions: ${Object.keys(value.functions).join(\", \")}.`,\n );\n }\n return { errors, notes };\n};\n"],"mappings":";;;;;AAUA,MAAM,WAAW,IAAI,IACnB,uDAAuD,MAAM,GAAG,CAClE;AACA,MAAa,YAAY,aACvB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,IAAI,GAAG,CAAC,CAC/D;AAIF,MAAM,eACJ,OACA,OAAO,KACP,YAAmC,CAAC,MACb;CACvB,IAAI,UAAU,QAAQ,CAAC,UAAU,SAAS,CAAC,CAAC,SAAS,OAAO,KAAK,GAC/D,OAAO,KAAA;CACT,IAAI,OAAO,UAAU,UACnB,OAAO,OAAO,SAAS,KAAK,IAAI,KAAA,IAAY;CAC9C,IAAI,OAAO,UAAU,YAAY,UAAU,SAAS,KAAK,GAAG,OAAO;CACnE,MAAM,UAAU,MAAM,QAAQ,KAAK;CAEnC,IAAI,EADe,UAAU,CAAC,MAAM,SAAS,IAAI,CAAC,OAAO,WAAW,IAAI,EAAA,CACxD,SAAS,OAAO,eAAe,KAAK,CAAC,GAAG,OAAO;CAC/D,MAAM,OAAO,UACT,MAAM,KACJ,EAAE,QAAQ,OAAO,yBAAyB,OAAO,QAAQ,CAAC,EAAE,MAAM,IACjE,GAAG,UAAU,OAAO,KAAK,CAC5B,IACA,QAAQ,QAAQ,KAAK;CACzB,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,QAAQ,UAAU,OAAO;EACpC,MAAM,KAAK,GAAG,KAAK,GAAG,KAAK,UAAU,GAAG,EAAE;EAC1C,MAAM,aAAa,OAAO,yBAAyB,OAAO,GAAG;EAC7D,IACE,QAAQ,eACR,CAAC,YAAY,cACb,EAAE,WAAW,aAEb,OAAO;EACT,MAAM,QAAQ,YAAY,WAAW,OAAO,IAAI,CAAC,GAAG,WAAW,KAAK,CAAC;EACrE,IAAI,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A,IAAI,CAAC,UAAU,QAAQ,MAAM,CAAC,CAAC,MAAM,GACnC,OAAO,OAAO,OAAO,KACnB,QAAQ,0CAA0C,QAAQ,OAAO,EAAE,CACrE;EACF,WAAW,IAAI,KAAK;GAAE;GAAS,MAAM;EAAO,CAAC;CAC/C;CACA,OAAO;AACT,CAAC;AAEH,MAAa,SACX,UACA,aACG;CACH,MAAM,SAAwC,CAAC;CAC/C,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,KAAK,EAAE,SAAS,WAAW,UACrC,IAAI;EACF,MAAM,UAAU,QAAQ,QAAQ,MAAM,SAAS,IAAI;EACnD,IAAI,YAAY,KAAA,GAAW;EAC3B,MAAM,KAAK,GAAG,QAAQ,KAAK;EAC3B,IAAI,QAAQ,OAAO,SAAS,GAC1B,OAAO,KACL,IAAI,4BAA4B;GAC9B,YAAY;GACZ,QAAQ,CAAC,GAAG,IAAI,IAAI,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI;EAChD,CAAC,CACH;CACJ,SAAS,OAAO;EACd,OAAO,KACL,IAAI,4BAA4B;GAC9B,YAAY;GACZ,QAAQ,iBAAiB,OAAO,KAAK;EACvC,CAAC,CACH;CACF;CAEF,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IACE,CAAC,SAAS,IAAI,GAAG,KACjB,CAAC,SAAS,IAAI,GAAG,KACjB,UAAU,gBAAgB,KAAK,KAC/B,eAAe,SACf,UAAU,gBAAgB,MAAM,SAAS,GAEzC,MAAM,KACJ,qBAAqB,IAAI,oDAAoD,OAAO,KAAK,MAAM,SAAS,CAAC,CAAC,KAAK,IAAI,EAAE,EACvH;CAEJ,OAAO;EAAE;EAAQ;CAAM;AACzB"}
@@ -0,0 +1,192 @@
1
+ import { fromBundlerError } from "./BuildError.mjs";
2
+ import { logFileRemoved } from "./log.mjs";
3
+ import { bundle } from "./Bundler.mjs";
4
+ import { InvalidManifestSectionError, logCodegenError } from "./CodegenError.mjs";
5
+ import { ConfectDirectory } from "./ConfectDirectory.mjs";
6
+ import { removePathIfExists, toPosixPath, writeFileStringAndLog } from "./utils.mjs";
7
+ import * as Effect from "effect/Effect";
8
+ import * as FileSystem from "effect/FileSystem";
9
+ import * as Path from "effect/Path";
10
+ import * as Result from "effect/Result";
11
+ import * as Option from "effect/Option";
12
+ import * as Schema from "effect/Schema";
13
+ //#region src/SectionFiles.ts
14
+ /**
15
+ * The files codegen writes directly in `confect/_generated`, current and
16
+ * legacy, which no section may claim.
17
+ */
18
+ const builtIn = new Set(`spec schema convexSchema id components component refs docs services manifest
19
+ auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions
20
+ nodeRegisteredFunctions`.split(/\s+/).map((name) => `${name}.ts`));
21
+ const PREFIX = "// Generated by `confect codegen` from the manifest section ";
22
+ const header = (key) => `${PREFIX}${JSON.stringify(key)}. Do not edit.`;
23
+ const Sources = Schema.fromJsonString(Schema.Array(Schema.String));
24
+ const encodeSources = Schema.encodeSync(Sources);
25
+ const decodeSources = Schema.decodeUnknownOption(Sources);
26
+ const INPUTS = "sectionInputs.json";
27
+ const visit = (leaves, each) => {
28
+ const walk = (group, path, source) => {
29
+ for (const spec of Object.values(group.functions)) each(spec, `${path}:${spec.name}`, source);
30
+ for (const [name, child] of Object.entries(group.groups)) walk(child, `${path}/${name}`, source);
31
+ };
32
+ for (const leaf of leaves) walk(leaf.spec, leaf.pathSegments.join("/"), leaf.relativePath);
33
+ };
34
+ /**
35
+ * One claim per section key that generates a file, ordered by file. A name that
36
+ * is built in, not a `.ts` file directly in `_generated`, or claimed by two
37
+ * keys is refused.
38
+ */
39
+ const claims = (leaves) => Result.gen(function* () {
40
+ const byKey = /* @__PURE__ */ new Map();
41
+ visit(leaves, (spec) => {
42
+ for (const { key, section } of spec.manifestSections ?? []) if (section.generate !== void 0 && !byKey.has(key)) byKey.set(key, section.generate);
43
+ });
44
+ const byFile = /* @__PURE__ */ new Map();
45
+ for (const [key, { file }] of byKey) {
46
+ const other = byFile.get(file);
47
+ const refusal = builtIn.has(file) ? `claims confect/_generated/${file}, which codegen writes itself.` : !/^[\w-]+\.ts$/.test(file) ? `claims ${JSON.stringify(file)}; name a .ts file directly inside confect/_generated.` : other !== void 0 ? `claims confect/_generated/${file}, which the manifest section ${JSON.stringify(other)} also claims.` : void 0;
48
+ if (refusal !== void 0) return yield* Result.fail(new InvalidManifestSectionError({
49
+ sectionKey: key,
50
+ reason: refusal
51
+ }));
52
+ byFile.set(file, key);
53
+ }
54
+ return [...byKey].map(([key, generate]) => ({
55
+ key,
56
+ generate
57
+ })).sort((a, b) => a.generate.file.localeCompare(b.generate.file));
58
+ });
59
+ const sourceFiles = Effect.gen(function* () {
60
+ const fs = yield* FileSystem.FileSystem;
61
+ const path = yield* Path.Path;
62
+ const confectDirectory = yield* ConfectDirectory.get;
63
+ return (yield* fs.readDirectory(confectDirectory, { recursive: true })).map((file) => toPosixPath(path, file)).filter((file) => file.endsWith(".ts") && !file.endsWith(".d.ts") && !file.split("/").includes("_generated")).sort();
64
+ });
65
+ const render = Effect.fnUntraced(function* ({ key, generate }, input, watched) {
66
+ const path = yield* Path.Path;
67
+ const confectDirectory = yield* ConfectDirectory.get;
68
+ const failed = (cause) => new InvalidManifestSectionError({
69
+ sectionKey: key,
70
+ reason: `generate failed: ${String(cause)}`
71
+ });
72
+ const matched = yield* Effect.try({
73
+ try: () => input.files.filter((file) => generate.match(file)),
74
+ catch: failed
75
+ });
76
+ for (const file of matched) watched.add(file);
77
+ const modules = yield* Effect.forEach(matched, (relativePath) => {
78
+ const entry = path.join(confectDirectory, relativePath);
79
+ return bundle(entry, { plugins: [{
80
+ name: "confect:section-inputs",
81
+ setup: (build) => build.onEnd(({ metafile }) => {
82
+ for (const loaded of Object.keys(metafile?.inputs ?? {})) {
83
+ const file = toPosixPath(path, path.relative(confectDirectory, path.resolve(path.dirname(entry), loaded)));
84
+ if (!file.startsWith("../") && !file.startsWith("_generated/")) watched.add(file);
85
+ }
86
+ })
87
+ }] }).pipe(Effect.map(({ module }) => ({
88
+ relativePath,
89
+ exports: module
90
+ })), Effect.mapError((error) => fromBundlerError(`confect/${relativePath}`, error)));
91
+ });
92
+ const { contents, errors } = yield* Effect.try({
93
+ try: () => generate.render({
94
+ ...input,
95
+ modules
96
+ }),
97
+ catch: failed
98
+ });
99
+ const [error, ...more] = errors.map((reason) => new InvalidManifestSectionError({
100
+ sectionKey: key,
101
+ reason
102
+ }));
103
+ for (const other of more) yield* logCodegenError(other);
104
+ if (error !== void 0) return yield* error;
105
+ return {
106
+ modules,
107
+ contents: [
108
+ header(key),
109
+ `// Sources: ${encodeSources(matched)}`,
110
+ contents
111
+ ].join("\n")
112
+ };
113
+ });
114
+ /**
115
+ * The files in `confect/_generated` a section wrote, which carry its header.
116
+ */
117
+ const written = Effect.gen(function* () {
118
+ const fs = yield* FileSystem.FileSystem;
119
+ const path = yield* Path.Path;
120
+ const generated = path.join(yield* ConfectDirectory.get, "_generated");
121
+ if (!(yield* fs.exists(generated))) return [];
122
+ return yield* Effect.filter((yield* fs.readDirectory(generated)).filter((file) => file.endsWith(".ts")), (file) => fs.readFileString(path.join(generated, file)).pipe(Effect.map((contents) => contents.startsWith(PREFIX))));
123
+ });
124
+ /**
125
+ * The `confect/` files the generating sections matched and the `confect/` files
126
+ * those import, as recorded by the last codegen run that loaded them.
127
+ */
128
+ const inputs = Effect.gen(function* () {
129
+ const fs = yield* FileSystem.FileSystem;
130
+ const record = (yield* Path.Path).join(yield* ConfectDirectory.get, "_generated", INPUTS);
131
+ const none = [];
132
+ if (!(yield* fs.exists(record))) return none;
133
+ return Option.getOrElse(decodeSources(yield* fs.readFileString(record)), () => none);
134
+ });
135
+ /**
136
+ * Write each claimed file into `confect/_generated` once every section has
137
+ * rendered. Every section renders before codegen fails with the first error
138
+ * after logging the rest. The record of section inputs is written either way,
139
+ * keeping the previous inputs after a failure, so `confect dev` sees the fix.
140
+ * Returns the claimed file names, whether they differ from the section files
141
+ * that existed before, and the modules each section key matched.
142
+ */
143
+ const sync = Effect.fnUntraced(function* (leaves, mounts) {
144
+ const path = yield* Path.Path;
145
+ const generated = path.join(yield* ConfectDirectory.get, "_generated");
146
+ const claimed = yield* Effect.fromResult(claims(leaves));
147
+ const functions = [];
148
+ visit(leaves, (_, functionPath, source) => functions.push({
149
+ path: functionPath,
150
+ source
151
+ }));
152
+ const files = claimed.length === 0 ? [] : yield* sourceFiles;
153
+ const watched = /* @__PURE__ */ new Set();
154
+ const [rendered, failures] = yield* Effect.partition(claimed, (claim) => render(claim, {
155
+ functions,
156
+ mounts,
157
+ files
158
+ }, watched).pipe(Effect.map((output) => ({
159
+ ...claim,
160
+ ...output
161
+ }))));
162
+ if (failures.length > 0) for (const file of yield* inputs) watched.add(file);
163
+ yield* claimed.length === 0 ? removePathIfExists(path.join(generated, INPUTS)) : writeFileStringAndLog(path.join(generated, INPUTS), encodeSources([...watched].sort()));
164
+ const [error, ...more] = failures;
165
+ for (const other of more) yield* logCodegenError(other);
166
+ if (error !== void 0) return yield* error;
167
+ const existing = yield* written;
168
+ for (const { generate, contents } of rendered) yield* writeFileStringAndLog(path.join(generated, generate.file), contents);
169
+ const names = rendered.map(({ generate }) => generate.file);
170
+ return {
171
+ modules: new Map(rendered.map(({ key, modules }) => [key, modules])),
172
+ files: names,
173
+ changed: names.length !== existing.length || names.some((file) => !existing.includes(file))
174
+ };
175
+ });
176
+ /**
177
+ * Remove each file a section wrote that is not in `files`. Codegen runs this
178
+ * after it rewrites the registration files and the HTTP router, so a run that
179
+ * fails earlier leaves no import of a removed file.
180
+ */
181
+ const removeUnclaimed = Effect.fnUntraced(function* (files) {
182
+ const path = yield* Path.Path;
183
+ const generated = path.join(yield* ConfectDirectory.get, "_generated");
184
+ for (const file of yield* written) if (!files.includes(file)) {
185
+ yield* removePathIfExists(path.join(generated, file));
186
+ yield* logFileRemoved(path.join(generated, file));
187
+ }
188
+ });
189
+ //#endregion
190
+ export { builtIn, claims, inputs, removeUnclaimed, sync, written };
191
+
192
+ //# sourceMappingURL=SectionFiles.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SectionFiles.mjs","names":["Bundler.bundle"],"sources":["../src/SectionFiles.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport type * as esbuild from \"esbuild\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidManifestSectionError,\n logCodegenError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport { logFileRemoved } from \"./log.js\";\nimport {\n removePathIfExists,\n toPosixPath,\n writeFileStringAndLog,\n} from \"./utils.js\";\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\n/**\n * The files codegen writes directly in `confect/_generated`, current and\n * legacy, which no section may claim.\n */\nexport const builtIn: ReadonlySet<string> = new Set(\n `spec schema convexSchema id components component refs docs services manifest\n auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions\n nodeRegisteredFunctions`\n .split(/\\s+/)\n .map((name) => `${name}.ts`),\n);\n\nconst PREFIX = \"// Generated by `confect codegen` from the manifest section \";\nconst header = (key: string) => `${PREFIX}${JSON.stringify(key)}. Do not edit.`;\nconst Sources = Schema.fromJsonString(Schema.Array(Schema.String));\nconst encodeSources = Schema.encodeSync(Sources);\nconst decodeSources = Schema.decodeUnknownOption(Sources);\nconst INPUTS = \"sectionInputs.json\";\n\ninterface Claim {\n readonly key: string;\n readonly generate: ManifestSection.Generate;\n}\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (spec: FunctionSpec.AnyWithProps, path: string, source: string) => void,\n) => {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => {\n for (const spec of Object.values(group.functions))\n each(spec, `${path}:${spec.name}`, source);\n for (const [name, child] of Object.entries(group.groups))\n walk(child, `${path}/${name}`, source);\n };\n for (const leaf of leaves)\n walk(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n};\n\n/**\n * One claim per section key that generates a file, ordered by file. A name that\n * is built in, not a `.ts` file directly in `_generated`, or claimed by two\n * keys is refused.\n */\nexport const claims = (leaves: ReadonlyArray<Leaf>) =>\n Result.gen(function* () {\n const byKey = new Map<string, ManifestSection.Generate>();\n visit(leaves, (spec) => {\n for (const { key, section } of spec.manifestSections ?? [])\n if (section.generate !== undefined && !byKey.has(key))\n byKey.set(key, section.generate);\n });\n const byFile = new Map<string, string>();\n for (const [key, { file }] of byKey) {\n const other = byFile.get(file);\n const refusal = builtIn.has(file)\n ? `claims confect/_generated/${file}, which codegen writes itself.`\n : !/^[\\w-]+\\.ts$/.test(file)\n ? `claims ${JSON.stringify(file)}; name a .ts file directly inside confect/_generated.`\n : other !== undefined\n ? `claims confect/_generated/${file}, which the manifest section ${JSON.stringify(other)} also claims.`\n : undefined;\n if (refusal !== undefined)\n return yield* Result.fail(\n new InvalidManifestSectionError({ sectionKey: key, reason: refusal }),\n );\n byFile.set(file, key);\n }\n return [...byKey]\n .map(([key, generate]) => ({ key, generate }))\n .sort((a, b) => a.generate.file.localeCompare(b.generate.file));\n });\n\nconst sourceFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n return (yield* fs.readDirectory(confectDirectory, { recursive: true }))\n .map((file) => toPosixPath(path, file))\n .filter(\n (file) =>\n file.endsWith(\".ts\") &&\n !file.endsWith(\".d.ts\") &&\n !file.split(\"/\").includes(\"_generated\"),\n )\n .sort();\n});\n\nconst render = Effect.fnUntraced(function* (\n { key, generate }: Claim,\n input: Omit<ManifestSection.GenerateInput, \"modules\">,\n watched: Set<string>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const failed = (cause: unknown) =>\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `generate failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => input.files.filter((file) => generate.match(file)),\n catch: failed,\n });\n for (const file of matched) watched.add(file);\n const modules = yield* Effect.forEach(matched, (relativePath) => {\n const entry = path.join(confectDirectory, relativePath);\n // Inputs are recorded once esbuild finishes, before the module runs, so a\n // module that throws on load still has its imports watched. `confect dev`\n // sees changes only under `confect/`, and every run rewrites `_generated`,\n // so watching it would loop.\n const recordInputs: esbuild.Plugin = {\n name: \"confect:section-inputs\",\n setup: (build) =>\n build.onEnd(({ metafile }) => {\n for (const loaded of Object.keys(metafile?.inputs ?? {})) {\n const file = toPosixPath(\n path,\n path.relative(\n confectDirectory,\n path.resolve(path.dirname(entry), loaded),\n ),\n );\n if (!file.startsWith(\"../\") && !file.startsWith(\"_generated/\"))\n watched.add(file);\n }\n }),\n };\n return Bundler.bundle(entry, { plugins: [recordInputs] }).pipe(\n Effect.map(({ module }) => ({ relativePath, exports: module })),\n Effect.mapError((error) =>\n fromBundlerError(`confect/${relativePath}`, error),\n ),\n );\n });\n const { contents, errors } = yield* Effect.try({\n try: () => generate.render({ ...input, modules }),\n catch: failed,\n });\n const [error, ...more] = errors.map(\n (reason) => new InvalidManifestSectionError({ sectionKey: key, reason }),\n );\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n return {\n modules,\n contents: [\n header(key),\n `// Sources: ${encodeSources(matched)}`,\n contents,\n ].join(\"\\n\"),\n };\n});\n\n/**\n * The files in `confect/_generated` a section wrote, which carry its header.\n */\nexport const written = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n if (!(yield* fs.exists(generated))) return [];\n return yield* Effect.filter(\n (yield* fs.readDirectory(generated)).filter((file) => file.endsWith(\".ts\")),\n (file) =>\n fs\n .readFileString(path.join(generated, file))\n .pipe(Effect.map((contents) => contents.startsWith(PREFIX))),\n );\n});\n\n/**\n * The `confect/` files the generating sections matched and the `confect/` files\n * those import, as recorded by the last codegen run that loaded them.\n */\nexport const inputs = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const record = path.join(yield* ConfectDirectory.get, \"_generated\", INPUTS);\n const none: ReadonlyArray<string> = [];\n if (!(yield* fs.exists(record))) return none;\n return Option.getOrElse(\n decodeSources(yield* fs.readFileString(record)),\n () => none,\n );\n});\n\n/**\n * Write each claimed file into `confect/_generated` once every section has\n * rendered. Every section renders before codegen fails with the first error\n * after logging the rest. The record of section inputs is written either way,\n * keeping the previous inputs after a failure, so `confect dev` sees the fix.\n * Returns the claimed file names, whether they differ from the section files\n * that existed before, and the modules each section key matched.\n */\nexport const sync = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<Leaf>,\n mounts: ManifestSection.GenerateInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n const claimed = yield* Effect.fromResult(claims(leaves));\n const functions: Array<{ path: string; source: string }> = [];\n visit(leaves, (_, functionPath, source) =>\n functions.push({ path: functionPath, source }),\n );\n const files = claimed.length === 0 ? [] : yield* sourceFiles;\n const watched = new Set<string>();\n const [rendered, failures] = yield* Effect.partition(claimed, (claim) =>\n render(claim, { functions, mounts, files }, watched).pipe(\n Effect.map((output) => ({ ...claim, ...output })),\n ),\n );\n if (failures.length > 0) for (const file of yield* inputs) watched.add(file);\n yield* claimed.length === 0\n ? removePathIfExists(path.join(generated, INPUTS))\n : writeFileStringAndLog(\n path.join(generated, INPUTS),\n encodeSources([...watched].sort()),\n );\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n const existing = yield* written;\n for (const { generate, contents } of rendered)\n yield* writeFileStringAndLog(path.join(generated, generate.file), contents);\n const names = rendered.map(({ generate }) => generate.file);\n return {\n modules: new Map(rendered.map(({ key, modules }) => [key, modules])),\n files: names,\n changed:\n names.length !== existing.length ||\n names.some((file) => !existing.includes(file)),\n };\n});\n\n/**\n * Remove each file a section wrote that is not in `files`. Codegen runs this\n * after it rewrites the registration files and the HTTP router, so a run that\n * fails earlier leaves no import of a removed file.\n */\nexport const removeUnclaimed = Effect.fnUntraced(function* (\n files: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n for (const file of yield* written)\n if (!files.includes(file)) {\n yield* removePathIfExists(path.join(generated, file));\n yield* logFileRemoved(path.join(generated, file));\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAa,UAA+B,IAAI,IAC9C;;2BAGG,MAAM,KAAK,CAAC,CACZ,KAAK,SAAS,GAAG,KAAK,IAAI,CAC/B;AAEA,MAAM,SAAS;AACf,MAAM,UAAU,QAAgB,GAAG,SAAS,KAAK,UAAU,GAAG,EAAE;AAChE,MAAM,UAAU,OAAO,eAAe,OAAO,MAAM,OAAO,MAAM,CAAC;AACjE,MAAM,gBAAgB,OAAO,WAAW,OAAO;AAC/C,MAAM,gBAAgB,OAAO,oBAAoB,OAAO;AACxD,MAAM,SAAS;AAOf,MAAM,SACJ,QACA,SACG;CACH,MAAM,QACJ,OACA,MACA,WACG;EACH,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,SAAS,GAC9C,KAAK,MAAM,GAAG,KAAK,GAAG,KAAK,QAAQ,MAAM;EAC3C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,MAAM,MAAM,GACrD,KAAK,OAAO,GAAG,KAAK,GAAG,QAAQ,MAAM;CACzC;CACA,KAAK,MAAM,QAAQ,QACjB,KAAK,KAAK,MAAM,KAAK,aAAa,KAAK,GAAG,GAAG,KAAK,YAAY;AAClE;;;;;;AA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