@gaganref/confect-cli 10.3.1-fork.45 → 10.3.1-fork.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Declaration.mjs +8 -5
- package/dist/Declaration.mjs.map +1 -1
- package/dist/ManifestSections.mjs +89 -0
- package/dist/ManifestSections.mjs.map +1 -0
- package/dist/confect/codegen.mjs +7 -3
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +53 -11
- package/dist/confect/declaration.mjs.map +1 -1
- package/package.json +3 -3
package/dist/Declaration.mjs
CHANGED
|
@@ -292,15 +292,17 @@ const authProviders = (providers) => [
|
|
|
292
292
|
/**
|
|
293
293
|
* `confect/_generated/manifest.ts`: plain data, no imports, for infra.
|
|
294
294
|
*/
|
|
295
|
-
const manifest = (declaration, digest) => {
|
|
295
|
+
const manifest = (declaration, digest, sections = {}) => {
|
|
296
296
|
const data = {
|
|
297
297
|
name: declaration.name,
|
|
298
298
|
env: Object.fromEntries(declaration.env),
|
|
299
299
|
http: { mounts: Object.fromEntries(declaration.mounts.flatMap(({ name, httpPrefix }) => httpPrefix === void 0 ? [] : [[name, httpPrefix]])) },
|
|
300
|
-
digest
|
|
300
|
+
digest,
|
|
301
|
+
...sections
|
|
301
302
|
};
|
|
302
|
-
return
|
|
303
|
+
return renderManifest(data);
|
|
303
304
|
};
|
|
305
|
+
const renderManifest = (data) => `${header("confect/env.ts and confect/app.ts")}\n\nexport default ${JSON.stringify(data, null, 2)} as const;\n`;
|
|
304
306
|
/**
|
|
305
307
|
* A digest of the declaration's inputs: every first-party file its modules
|
|
306
308
|
* import (by project-relative path and contents) and the versions of the
|
|
@@ -311,11 +313,12 @@ const digest = (input) => {
|
|
|
311
313
|
const byFirst = (a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
|
|
312
314
|
hash.update(JSON.stringify({
|
|
313
315
|
files: [...input.files].sort(byFirst),
|
|
314
|
-
versions: [...input.versions].sort(byFirst)
|
|
316
|
+
versions: [...input.versions].sort(byFirst),
|
|
317
|
+
...input.sections === void 0 ? {} : { sections: input.sections }
|
|
315
318
|
}));
|
|
316
319
|
return `sha256:${hash.digest("hex")}`;
|
|
317
320
|
};
|
|
318
321
|
//#endregion
|
|
319
|
-
export { AuthForAnotherBackend, ForeignEnvBinding, InvalidBinding, InvalidEnvKey, InvalidMountName, InvalidProviderEnv, NotADeclaration, UnknownComponentImport, authConfig, authProviders, convexConfig, digest, fileOf, header, isGenerated, manifest, parse };
|
|
322
|
+
export { AuthForAnotherBackend, ForeignEnvBinding, InvalidBinding, InvalidEnvKey, InvalidMountName, InvalidProviderEnv, NotADeclaration, UnknownComponentImport, authConfig, authProviders, convexConfig, digest, fileOf, header, isGenerated, manifest, parse, renderManifest };
|
|
320
323
|
|
|
321
324
|
//# sourceMappingURL=Declaration.mjs.map
|
package/dist/Declaration.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Declaration.mjs","names":[],"sources":["../src/Declaration.ts"],"sourcesContent":["import { App, Auth, Env } from \"@confect/core\";\nimport * as Data from \"effect/Data\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\n// oxlint-disable-next-line effecttsgo/node-builtin-import -- a synchronous hash of in-memory strings in a pure function; Effect's Crypto is a service.\nimport { createHash } from \"node:crypto\";\n\n/**\n * A backend's declaration (`confect/env.ts`, `app.ts`, `auth.ts`) reduced to\n * the plain data codegen renders. The evaluated modules are parsed into this\n * once, at {@link parse}; every renderer below is a pure function of it.\n */\nexport interface Declaration {\n readonly target: \"app\" | \"component\";\n readonly name: string;\n readonly env: ReadonlyArray<readonly [string, Env.Descriptor]>;\n readonly mounts: ReadonlyArray<Mount>;\n readonly providers: Option.Option<ReadonlyArray<Provider>>;\n}\n\nexport interface Mount {\n readonly name: string;\n readonly importPath: string;\n readonly componentName: string;\n readonly httpPrefix: string | undefined;\n readonly env: ReadonlyArray<readonly [string, Binding]>;\n}\n\nexport type Binding =\n | { readonly kind: \"value\"; readonly value: string }\n | { readonly kind: \"env\"; readonly key: string };\n\nexport type ProviderValue =\n | { readonly kind: \"value\"; readonly value: string }\n | { readonly kind: \"siteUrl\" | \"cloudUrl\"; readonly path: string }\n | { readonly kind: \"env\"; readonly key: string };\n\nexport type Provider = ReadonlyArray<readonly [string, ProviderValue]>;\n\nexport class NotADeclaration extends Data.TaggedError(\"NotADeclaration\")<{\n readonly file: string;\n readonly expected: string;\n}> {\n override get message(): string {\n return `${this.file} must default-export ${this.expected}.`;\n }\n}\n\nexport class InvalidEnvKey extends Data.TaggedError(\"InvalidEnvKey\")<{\n readonly key: string;\n}> {\n override get message(): string {\n return `\"${this.key}\" is not a valid Convex environment variable name; use letters, digits and underscores, starting with a letter.`;\n }\n}\n\nexport class InvalidMountName extends Data.TaggedError(\"InvalidMountName\")<{\n readonly mount: string;\n}> {\n override get message(): string {\n return `\"${this.mount}\" is not a valid mount name; use letters, digits and underscores, starting with a letter or underscore.`;\n }\n}\n\nexport class ForeignEnvBinding extends Data.TaggedError(\"ForeignEnvBinding\")<{\n readonly mount: string;\n readonly slot: string;\n readonly backend: string;\n readonly key: string;\n readonly expectedBackend: string;\n}> {\n override get message(): string {\n return `The mount \"${this.mount}\" binds ${this.slot} to ${this.key} of the \"${this.backend}\" env, but this backend's env is \"${this.expectedBackend}\".`;\n }\n}\n\nexport class InvalidBinding extends Data.TaggedError(\"InvalidBinding\")<{\n readonly mount: string;\n readonly slot: string;\n}> {\n override get message(): string {\n return `The mount \"${this.mount}\" binds ${this.slot} to something other than a string or an entry of this backend's env.`;\n }\n}\n\nexport class UnknownComponentImport extends Data.TaggedError(\n \"UnknownComponentImport\",\n)<{ readonly mount: string }> {\n override get message(): string {\n return `The mount \"${this.mount}\" must pass the default export of a component's convex.config module, imported directly in the declaration.`;\n }\n}\n\nexport class AuthForAnotherBackend extends Data.TaggedError(\n \"AuthForAnotherBackend\",\n)<{ readonly backend: string; readonly expectedBackend: string }> {\n override get message(): string {\n return `confect/auth.ts declares auth for the \"${this.backend}\" backend, but confect/app.ts declares \"${this.expectedBackend}\".`;\n }\n}\n\nexport class InvalidProviderEnv extends Data.TaggedError(\"InvalidProviderEnv\")<{\n readonly field: string;\n readonly key: string;\n readonly backend: string;\n}> {\n override get message(): string {\n return `Auth provider field \"${this.field}\" requires a non-secret, required string entry of the \"${this.backend}\" env; got \"${this.key}\".`;\n }\n}\n\nexport type DeclarationError =\n | NotADeclaration\n | InvalidEnvKey\n | InvalidMountName\n | ForeignEnvBinding\n | InvalidBinding\n | UnknownComponentImport\n | AuthForAnotherBackend\n | InvalidProviderEnv;\n\nconst ENV_KEY = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst MOUNT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * The declaration file a parse error is about.\n */\nexport const fileOf = (error: DeclarationError): string =>\n error._tag === \"NotADeclaration\"\n ? error.file\n : error._tag === \"AuthForAnotherBackend\" ||\n error._tag === \"InvalidProviderEnv\"\n ? \"confect/auth.ts\"\n : \"confect/app.ts\";\n\n/**\n * A mounted component's import as the generated `convex.config.ts` writes it.\n */\nexport interface ComponentImport {\n readonly importPath: string;\n readonly componentName: string;\n}\n\n/**\n * Parse the default exports of `confect/app.ts` and, when present,\n * `confect/auth.ts`. `componentImport` recovers how the generated config\n * imports a mounted definition; codegen's bundler records it.\n */\nexport const parse = (input: {\n readonly target: \"app\" | \"component\";\n readonly app: unknown;\n readonly auth: Option.Option<unknown>;\n readonly componentImport: (\n definition: unknown,\n ) => Option.Option<ComponentImport>;\n}): Result.Result<Declaration, DeclarationError> =>\n Result.gen(function* () {\n if (!App.isApp(input.app)) {\n return yield* Result.fail(\n new NotADeclaration({\n file: \"confect/app.ts\",\n expected: \"App.make(...)\",\n }),\n );\n }\n const env = App.env(input.app);\n const name = Env.name(env);\n const descriptors = Env.descriptors(env);\n for (const [key] of descriptors) {\n if (!ENV_KEY.test(key))\n return yield* Result.fail(new InvalidEnvKey({ key }));\n }\n\n const mounts: Array<Mount> = [];\n for (const mount of App.mounts(input.app)) {\n if (!MOUNT_NAME.test(mount.name)) {\n return yield* Result.fail(new InvalidMountName({ mount: mount.name }));\n }\n const component = input.componentImport(mount.definition);\n if (Option.isNone(component)) {\n return yield* Result.fail(\n new UnknownComponentImport({ mount: mount.name }),\n );\n }\n const bindings: Array<readonly [string, Binding]> = [];\n for (const [slot, bound] of Object.entries(mount.env)) {\n if (bound === undefined) continue;\n if (typeof bound === \"string\") {\n bindings.push([slot, { kind: \"value\", value: bound }]);\n continue;\n }\n if (!Env.isEntry(bound)) {\n return yield* Result.fail(\n new InvalidBinding({ mount: mount.name, slot }),\n );\n }\n const origin = Env.origin(bound);\n if (origin.backend !== name) {\n return yield* Result.fail(\n new ForeignEnvBinding({\n mount: mount.name,\n slot,\n backend: origin.backend,\n key: origin.key,\n expectedBackend: name,\n }),\n );\n }\n bindings.push([slot, { kind: \"env\", key: origin.key }]);\n }\n mounts.push({\n name: mount.name,\n importPath: component.value.importPath,\n componentName: component.value.componentName,\n httpPrefix: mount.httpPrefix,\n env: bindings,\n });\n }\n\n const providers: Option.Option<ReadonlyArray<Provider>> = Option.isNone(\n input.auth,\n )\n ? Option.none()\n : Option.some(yield* parseProviders(input.auth.value, name));\n\n return {\n target: input.target,\n name,\n env: descriptors,\n mounts,\n providers,\n };\n });\n\nconst parseProviders = (\n auth: unknown,\n backend: string,\n): Result.Result<ReadonlyArray<Provider>, DeclarationError> => {\n if (!Auth.isAuth(auth)) {\n return Result.fail(\n new NotADeclaration({\n file: \"confect/auth.ts\",\n expected: \"Auth.make(app, ...)\",\n }),\n );\n }\n const authBackend = Env.name(App.env(auth.app));\n if (authBackend !== backend) {\n return Result.fail(\n new AuthForAnotherBackend({\n backend: authBackend,\n expectedBackend: backend,\n }),\n );\n }\n return Result.gen(function* () {\n const providers: Provider[] = [];\n for (const provider of Auth.providers(auth)) {\n const fields: Array<readonly [string, ProviderValue]> = [];\n for (const [field, value] of Object.entries(provider)) {\n const sitePath = Auth.siteUrlPath(value);\n const cloudPath = Auth.cloudUrlPath(value);\n let lowered: ProviderValue;\n if (Env.isEntry(value)) {\n const { backend: owner, key } = Env.origin(value);\n const descriptor = value[\"~@confect/core/Env/Entry\"].descriptor;\n if (\n owner !== backend ||\n descriptor.optional ||\n descriptor.kind === \"secret\" ||\n !ENV_KEY.test(key)\n ) {\n return yield* Result.fail(\n new InvalidProviderEnv({ field, key, backend }),\n );\n }\n lowered = { kind: \"env\", key };\n } else if (sitePath !== undefined) {\n lowered = { kind: \"siteUrl\", path: sitePath };\n } else if (cloudPath !== undefined) {\n lowered = { kind: \"cloudUrl\", path: cloudPath };\n } else {\n lowered = {\n kind: \"value\",\n value: Predicate.isString(value) ? value : JSON.stringify(value),\n };\n }\n fields.push([field, lowered]);\n }\n providers.push(fields);\n }\n return providers;\n });\n};\n\nconst quote = (value: string): string => JSON.stringify(value);\n\nexport const header = (source: string): string =>\n `// Generated by \\`confect codegen\\` from ${source}. Do not edit.`;\n\nconst GENERATED_PREFIX = \"// Generated by `confect codegen` from \";\n\n/**\n * Whether codegen may overwrite or remove an existing file: it carries the\n * generated header, or it is exactly one of the files an earlier codegen wrote\n * there (`legacy`).\n */\nexport const isGenerated = (\n contents: string,\n legacy: ReadonlyArray<string>,\n): boolean =>\n contents.startsWith(GENERATED_PREFIX) || legacy.includes(contents);\n\nconst validator = (descriptor: Env.Descriptor): string => {\n const base =\n descriptor.kind === \"literals\"\n ? descriptor.values.length === 1\n ? `v.literal(${quote(descriptor.values[0])})`\n : `v.union(${descriptor.values.map((value) => `v.literal(${quote(value)})`).join(\", \")})`\n : \"v.string()\";\n return descriptor.optional ? `v.optional(${base})` : base;\n};\n\nconst RESERVED = new Set(\n \"await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield\".split(\n \" \",\n ),\n);\n\n/**\n * A safe import name for a component, from its Convex name.\n */\nconst identifier = (name: string): string => {\n const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, \"_\");\n const valid = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n return RESERVED.has(valid) ? `${valid}Component` : valid;\n};\n\n/**\n * `convex/convex.config.ts`: Convex's own app or component definition.\n */\nexport const convexConfig = (declaration: Declaration): string => {\n const self = declaration.target === \"app\" ? \"app\" : \"component\";\n const aliases = new Map<string, string>();\n const taken = new Set([self, \"v\", \"defineApp\", \"defineComponent\"]);\n for (const mount of declaration.mounts) {\n if (aliases.has(mount.importPath)) continue;\n const base = identifier(mount.componentName);\n let alias = base;\n for (let n = 2; taken.has(alias); n++) alias = `${base}${n}`;\n taken.add(alias);\n aliases.set(mount.importPath, alias);\n }\n\n const lines = [header(\"confect/app.ts\")];\n lines.push(\n declaration.target === \"app\"\n ? 'import { defineApp } from \"convex/server\";'\n : 'import { defineComponent } from \"convex/server\";',\n );\n if (declaration.env.length > 0)\n lines.push('import { v } from \"convex/values\";');\n for (const [importPath, alias] of aliases) {\n lines.push(`import ${alias} from ${quote(importPath)};`);\n }\n lines.push(\"\");\n\n const envBlock =\n declaration.env.length === 0\n ? []\n : [\n \" env: {\",\n ...declaration.env.map(\n ([key, descriptor]) => ` ${key}: ${validator(descriptor)},`,\n ),\n \" },\",\n ];\n if (declaration.target === \"app\") {\n lines.push(\n envBlock.length === 0\n ? \"const app = defineApp();\"\n : [\"const app = defineApp({\", ...envBlock, \"});\"].join(\"\\n\"),\n );\n } else {\n lines.push(\n envBlock.length === 0\n ? `const component = defineComponent(${quote(declaration.name)});`\n : [\n `const component = defineComponent(${quote(declaration.name)}, {`,\n ...envBlock,\n \"});\",\n ].join(\"\\n\"),\n );\n }\n\n for (const mount of declaration.mounts) {\n lines.push(\"\");\n lines.push(`${self}.use(${aliases.get(mount.importPath)}, {`);\n lines.push(` name: ${quote(mount.name)},`);\n if (mount.httpPrefix !== undefined) {\n lines.push(` httpPrefix: ${quote(mount.httpPrefix)},`);\n }\n if (mount.env.length > 0) {\n lines.push(\" env: {\");\n for (const [slot, binding] of mount.env) {\n lines.push(\n ` ${slot}: ${binding.kind === \"value\" ? quote(binding.value) : `${self}.env.${binding.key}`},`,\n );\n }\n lines.push(\" },\");\n }\n lines.push(\"});\");\n }\n\n lines.push(\"\", `export default ${self};`, \"\");\n return lines.join(\"\\n\");\n};\n\nconst providerValue = (value: ProviderValue): string => {\n switch (value.kind) {\n case \"value\":\n return quote(value.value);\n case \"env\":\n return `process.env[${quote(value.key)}]!`;\n default:\n return `\\`\\${process.env.${value.kind === \"siteUrl\" ? \"CONVEX_SITE_URL\" : \"CONVEX_CLOUD_URL\"}}${value.path.replaceAll(/[`$\\\\]/g, \"\\\\$&\")}\\``;\n }\n};\n\n/**\n * `convex/auth.config.ts`: Convex's provider list, with site URLs resolved\n * there.\n */\nexport const authConfig = (providers: ReadonlyArray<Provider>): string =>\n [\n header(\"confect/auth.ts\"),\n 'import type { AuthConfig } from \"convex/server\";',\n \"\",\n \"export default {\",\n providers.length === 0 ? \" providers: [],\" : \" providers: [\",\n ...(providers.length === 0\n ? []\n : [\n ...providers.flatMap((provider) => [\n \" {\",\n ...provider\n .filter(([field]) => field !== \"family\" && field !== \"name\")\n .map(\n ([field, value]) => ` ${field}: ${providerValue(value)},`,\n ),\n \" },\",\n ]),\n \" ],\",\n ]),\n \"} satisfies AuthConfig;\",\n \"\",\n ].join(\"\\n\");\n\n/**\n * Runtime issuer data with no dependency on declarations or component\n * definitions.\n */\nexport const authProviders = (providers: ReadonlyArray<Provider>): string =>\n [\n header(\"confect/auth.ts\"),\n \"\",\n \"export const providers = [\",\n ...providers.flatMap((provider) => [\n \" {\",\n ...provider.flatMap(([field, value]) => {\n const key =\n field === \"domain\"\n ? \"issuer\"\n : field === \"applicationID\"\n ? \"audience\"\n : field;\n return [\"issuer\", \"audience\", \"family\", \"name\"].includes(key)\n ? [` ${key}: ${providerValue(value)},`]\n : [];\n }),\n \" },\",\n ]),\n \"] as const;\",\n \"\",\n ].join(\"\\n\");\n\n/**\n * `confect/_generated/manifest.ts`: plain data, no imports, for infra.\n */\nexport const manifest = (declaration: Declaration, digest: string): string => {\n const data = {\n name: declaration.name,\n env: Object.fromEntries(declaration.env),\n http: {\n mounts: Object.fromEntries(\n declaration.mounts.flatMap(({ name, httpPrefix }) =>\n httpPrefix === undefined ? [] : [[name, httpPrefix]],\n ),\n ),\n },\n digest,\n };\n return `${header(\"confect/env.ts and confect/app.ts\")}\\n\\nexport default ${JSON.stringify(data, null, 2)} as const;\\n`;\n};\n\n/**\n * A digest of the declaration's inputs: every first-party file its modules\n * import (by project-relative path and contents) and the versions of the\n * packages that shape the generated output.\n */\nexport const digest = (input: {\n readonly files: ReadonlyArray<readonly [string, string]>;\n readonly versions: ReadonlyArray<readonly [string, string]>;\n}): string => {\n const hash = createHash(\"sha256\");\n const byFirst = (\n a: readonly [string, string],\n b: readonly [string, string],\n ) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);\n hash.update(\n JSON.stringify({\n files: [...input.files].sort(byFirst),\n versions: [...input.versions].sort(byFirst),\n }),\n );\n return `sha256:${hash.digest(\"hex\")}`;\n};\n"],"mappings":";;;;;;;AAwCA,IAAa,kBAAb,cAAqC,KAAK,YAAY,iBAAiB,CAAC,CAGrE;CACD,IAAa,UAAkB;EAC7B,OAAO,GAAG,KAAK,KAAK,uBAAuB,KAAK,SAAS;CAC3D;AACF;AAEA,IAAa,gBAAb,cAAmC,KAAK,YAAY,eAAe,CAAC,CAEjE;CACD,IAAa,UAAkB;EAC7B,OAAO,IAAI,KAAK,IAAI;CACtB;AACF;AAEA,IAAa,mBAAb,cAAsC,KAAK,YAAY,kBAAkB,CAAC,CAEvE;CACD,IAAa,UAAkB;EAC7B,OAAO,IAAI,KAAK,MAAM;CACxB;AACF;AAEA,IAAa,oBAAb,cAAuC,KAAK,YAAY,mBAAmB,CAAC,CAMzE;CACD,IAAa,UAAkB;EA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,YAAY,aAA0B,WAA2B;CAC5E,MAAM,OAAO;EACX,MAAM,YAAY;EAClB,KAAK,OAAO,YAAY,YAAY,GAAG;EACvC,MAAM,EACJ,QAAQ,OAAO,YACb,YAAY,OAAO,SAAS,EAAE,MAAM,iBAClC,eAAe,KAAA,IAAY,CAAC,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,CACrD,CACF,EACF;EACA;CACF;CACA,OAAO,GAAG,OAAO,mCAAmC,EAAE,qBAAqB,KAAK,UAAU,MAAM,MAAM,CAAC,EAAE;AAC3G;;;;;;AAOA,MAAa,UAAU,UAGT;CACZ,MAAM,OAAO,WAAW,QAAQ;CAChC,MAAM,WACJ,GACA,MACI,EAAE,KAAK,EAAE,KAAK,KAAK,EAAE,KAAK,EAAE,KAAK,IAAI;CAC3C,KAAK,OACH,KAAK,UAAU;EACb,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC,KAAK,OAAO;EACpC,UAAU,CAAC,GAAG,MAAM,QAAQ,CAAC,CAAC,KAAK,OAAO;CAC5C,CAAC,CACH;CACA,OAAO,UAAU,KAAK,OAAO,KAAK;AACpC"}
|
|
1
|
+
{"version":3,"file":"Declaration.mjs","names":[],"sources":["../src/Declaration.ts"],"sourcesContent":["import { App, Auth, Env } from \"@confect/core\";\nimport * as Data from \"effect/Data\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\n// oxlint-disable-next-line effecttsgo/node-builtin-import -- a synchronous hash of in-memory strings in a pure function; Effect's Crypto is a service.\nimport { createHash } from \"node:crypto\";\n\n/**\n * A backend's declaration (`confect/env.ts`, `app.ts`, `auth.ts`) reduced to\n * the plain data codegen renders. The evaluated modules are parsed into this\n * once, at {@link parse}; every renderer below is a pure function of it.\n */\nexport interface Declaration {\n readonly target: \"app\" | \"component\";\n readonly name: string;\n readonly env: ReadonlyArray<readonly [string, Env.Descriptor]>;\n readonly mounts: ReadonlyArray<Mount>;\n readonly providers: Option.Option<ReadonlyArray<Provider>>;\n}\n\nexport interface Mount {\n readonly name: string;\n readonly importPath: string;\n readonly componentName: string;\n readonly httpPrefix: string | undefined;\n readonly env: ReadonlyArray<readonly [string, Binding]>;\n}\n\nexport type Binding =\n | { readonly kind: \"value\"; readonly value: string }\n | { readonly kind: \"env\"; readonly key: string };\n\nexport type ProviderValue =\n | { readonly kind: \"value\"; readonly value: string }\n | { readonly kind: \"siteUrl\" | \"cloudUrl\"; readonly path: string }\n | { readonly kind: \"env\"; readonly key: string };\n\nexport type Provider = ReadonlyArray<readonly [string, ProviderValue]>;\n\nexport class NotADeclaration extends Data.TaggedError(\"NotADeclaration\")<{\n readonly file: string;\n readonly expected: string;\n}> {\n override get message(): string {\n return `${this.file} must default-export ${this.expected}.`;\n }\n}\n\nexport class InvalidEnvKey extends Data.TaggedError(\"InvalidEnvKey\")<{\n readonly key: string;\n}> {\n override get message(): string {\n return `\"${this.key}\" is not a valid Convex environment variable name; use letters, digits and underscores, starting with a letter.`;\n }\n}\n\nexport class InvalidMountName extends Data.TaggedError(\"InvalidMountName\")<{\n readonly mount: string;\n}> {\n override get message(): string {\n return `\"${this.mount}\" is not a valid mount name; use letters, digits and underscores, starting with a letter or underscore.`;\n }\n}\n\nexport class ForeignEnvBinding extends Data.TaggedError(\"ForeignEnvBinding\")<{\n readonly mount: string;\n readonly slot: string;\n readonly backend: string;\n readonly key: string;\n readonly expectedBackend: string;\n}> {\n override get message(): string {\n return `The mount \"${this.mount}\" binds ${this.slot} to ${this.key} of the \"${this.backend}\" env, but this backend's env is \"${this.expectedBackend}\".`;\n }\n}\n\nexport class InvalidBinding extends Data.TaggedError(\"InvalidBinding\")<{\n readonly mount: string;\n readonly slot: string;\n}> {\n override get message(): string {\n return `The mount \"${this.mount}\" binds ${this.slot} to something other than a string or an entry of this backend's env.`;\n }\n}\n\nexport class UnknownComponentImport extends Data.TaggedError(\n \"UnknownComponentImport\",\n)<{ readonly mount: string }> {\n override get message(): string {\n return `The mount \"${this.mount}\" must pass the default export of a component's convex.config module, imported directly in the declaration.`;\n }\n}\n\nexport class AuthForAnotherBackend extends Data.TaggedError(\n \"AuthForAnotherBackend\",\n)<{ readonly backend: string; readonly expectedBackend: string }> {\n override get message(): string {\n return `confect/auth.ts declares auth for the \"${this.backend}\" backend, but confect/app.ts declares \"${this.expectedBackend}\".`;\n }\n}\n\nexport class InvalidProviderEnv extends Data.TaggedError(\"InvalidProviderEnv\")<{\n readonly field: string;\n readonly key: string;\n readonly backend: string;\n}> {\n override get message(): string {\n return `Auth provider field \"${this.field}\" requires a non-secret, required string entry of the \"${this.backend}\" env; got \"${this.key}\".`;\n }\n}\n\nexport type DeclarationError =\n | NotADeclaration\n | InvalidEnvKey\n | InvalidMountName\n | ForeignEnvBinding\n | InvalidBinding\n | UnknownComponentImport\n | AuthForAnotherBackend\n | InvalidProviderEnv;\n\nconst ENV_KEY = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst MOUNT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * The declaration file a parse error is about.\n */\nexport const fileOf = (error: DeclarationError): string =>\n error._tag === \"NotADeclaration\"\n ? error.file\n : error._tag === \"AuthForAnotherBackend\" ||\n error._tag === \"InvalidProviderEnv\"\n ? \"confect/auth.ts\"\n : \"confect/app.ts\";\n\n/**\n * A mounted component's import as the generated `convex.config.ts` writes it.\n */\nexport interface ComponentImport {\n readonly importPath: string;\n readonly componentName: string;\n}\n\n/**\n * Parse the default exports of `confect/app.ts` and, when present,\n * `confect/auth.ts`. `componentImport` recovers how the generated config\n * imports a mounted definition; codegen's bundler records it.\n */\nexport const parse = (input: {\n readonly target: \"app\" | \"component\";\n readonly app: unknown;\n readonly auth: Option.Option<unknown>;\n readonly componentImport: (\n definition: unknown,\n ) => Option.Option<ComponentImport>;\n}): Result.Result<Declaration, DeclarationError> =>\n Result.gen(function* () {\n if (!App.isApp(input.app)) {\n return yield* Result.fail(\n new NotADeclaration({\n file: \"confect/app.ts\",\n expected: \"App.make(...)\",\n }),\n );\n }\n const env = App.env(input.app);\n const name = Env.name(env);\n const descriptors = Env.descriptors(env);\n for (const [key] of descriptors) {\n if (!ENV_KEY.test(key))\n return yield* Result.fail(new InvalidEnvKey({ key }));\n }\n\n const mounts: Array<Mount> = [];\n for (const mount of App.mounts(input.app)) {\n if (!MOUNT_NAME.test(mount.name)) {\n return yield* Result.fail(new InvalidMountName({ mount: mount.name }));\n }\n const component = input.componentImport(mount.definition);\n if (Option.isNone(component)) {\n return yield* Result.fail(\n new UnknownComponentImport({ mount: mount.name }),\n );\n }\n const bindings: Array<readonly [string, Binding]> = [];\n for (const [slot, bound] of Object.entries(mount.env)) {\n if (bound === undefined) continue;\n if (typeof bound === \"string\") {\n bindings.push([slot, { kind: \"value\", value: bound }]);\n continue;\n }\n if (!Env.isEntry(bound)) {\n return yield* Result.fail(\n new InvalidBinding({ mount: mount.name, slot }),\n );\n }\n const origin = Env.origin(bound);\n if (origin.backend !== name) {\n return yield* Result.fail(\n new ForeignEnvBinding({\n mount: mount.name,\n slot,\n backend: origin.backend,\n key: origin.key,\n expectedBackend: name,\n }),\n );\n }\n bindings.push([slot, { kind: \"env\", key: origin.key }]);\n }\n mounts.push({\n name: mount.name,\n importPath: component.value.importPath,\n componentName: component.value.componentName,\n httpPrefix: mount.httpPrefix,\n env: bindings,\n });\n }\n\n const providers: Option.Option<ReadonlyArray<Provider>> = Option.isNone(\n input.auth,\n )\n ? Option.none()\n : Option.some(yield* parseProviders(input.auth.value, name));\n\n return {\n target: input.target,\n name,\n env: descriptors,\n mounts,\n providers,\n };\n });\n\nconst parseProviders = (\n auth: unknown,\n backend: string,\n): Result.Result<ReadonlyArray<Provider>, DeclarationError> => {\n if (!Auth.isAuth(auth)) {\n return Result.fail(\n new NotADeclaration({\n file: \"confect/auth.ts\",\n expected: \"Auth.make(app, ...)\",\n }),\n );\n }\n const authBackend = Env.name(App.env(auth.app));\n if (authBackend !== backend) {\n return Result.fail(\n new AuthForAnotherBackend({\n backend: authBackend,\n expectedBackend: backend,\n }),\n );\n }\n return Result.gen(function* () {\n const providers: Provider[] = [];\n for (const provider of Auth.providers(auth)) {\n const fields: Array<readonly [string, ProviderValue]> = [];\n for (const [field, value] of Object.entries(provider)) {\n const sitePath = Auth.siteUrlPath(value);\n const cloudPath = Auth.cloudUrlPath(value);\n let lowered: ProviderValue;\n if (Env.isEntry(value)) {\n const { backend: owner, key } = Env.origin(value);\n const descriptor = value[\"~@confect/core/Env/Entry\"].descriptor;\n if (\n owner !== backend ||\n descriptor.optional ||\n descriptor.kind === \"secret\" ||\n !ENV_KEY.test(key)\n ) {\n return yield* Result.fail(\n new InvalidProviderEnv({ field, key, backend }),\n );\n }\n lowered = { kind: \"env\", key };\n } else if (sitePath !== undefined) {\n lowered = { kind: \"siteUrl\", path: sitePath };\n } else if (cloudPath !== undefined) {\n lowered = { kind: \"cloudUrl\", path: cloudPath };\n } else {\n lowered = {\n kind: \"value\",\n value: Predicate.isString(value) ? value : JSON.stringify(value),\n };\n }\n fields.push([field, lowered]);\n }\n providers.push(fields);\n }\n return providers;\n });\n};\n\nconst quote = (value: string): string => JSON.stringify(value);\n\nexport const header = (source: string): string =>\n `// Generated by \\`confect codegen\\` from ${source}. Do not edit.`;\n\nconst GENERATED_PREFIX = \"// Generated by `confect codegen` from \";\n\n/**\n * Whether codegen may overwrite or remove an existing file: it carries the\n * generated header, or it is exactly one of the files an earlier codegen wrote\n * there (`legacy`).\n */\nexport const isGenerated = (\n contents: string,\n legacy: ReadonlyArray<string>,\n): boolean =>\n contents.startsWith(GENERATED_PREFIX) || legacy.includes(contents);\n\nconst validator = (descriptor: Env.Descriptor): string => {\n const base =\n descriptor.kind === \"literals\"\n ? descriptor.values.length === 1\n ? `v.literal(${quote(descriptor.values[0])})`\n : `v.union(${descriptor.values.map((value) => `v.literal(${quote(value)})`).join(\", \")})`\n : \"v.string()\";\n return descriptor.optional ? `v.optional(${base})` : base;\n};\n\nconst RESERVED = new Set(\n \"await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield\".split(\n \" \",\n ),\n);\n\n/**\n * A safe import name for a component, from its Convex name.\n */\nconst identifier = (name: string): string => {\n const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, \"_\");\n const valid = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n return RESERVED.has(valid) ? `${valid}Component` : valid;\n};\n\n/**\n * `convex/convex.config.ts`: Convex's own app or component definition.\n */\nexport const convexConfig = (declaration: Declaration): string => {\n const self = declaration.target === \"app\" ? \"app\" : \"component\";\n const aliases = new Map<string, string>();\n const taken = new Set([self, \"v\", \"defineApp\", \"defineComponent\"]);\n for (const mount of declaration.mounts) {\n if (aliases.has(mount.importPath)) continue;\n const base = identifier(mount.componentName);\n let alias = base;\n for (let n = 2; taken.has(alias); n++) alias = `${base}${n}`;\n taken.add(alias);\n aliases.set(mount.importPath, alias);\n }\n\n const lines = [header(\"confect/app.ts\")];\n lines.push(\n declaration.target === \"app\"\n ? 'import { defineApp } from \"convex/server\";'\n : 'import { defineComponent } from \"convex/server\";',\n );\n if (declaration.env.length > 0)\n lines.push('import { v } from \"convex/values\";');\n for (const [importPath, alias] of aliases) {\n lines.push(`import ${alias} from ${quote(importPath)};`);\n }\n lines.push(\"\");\n\n const envBlock =\n declaration.env.length === 0\n ? []\n : [\n \" env: {\",\n ...declaration.env.map(\n ([key, descriptor]) => ` ${key}: ${validator(descriptor)},`,\n ),\n \" },\",\n ];\n if (declaration.target === \"app\") {\n lines.push(\n envBlock.length === 0\n ? \"const app = defineApp();\"\n : [\"const app = defineApp({\", ...envBlock, \"});\"].join(\"\\n\"),\n );\n } else {\n lines.push(\n envBlock.length === 0\n ? `const component = defineComponent(${quote(declaration.name)});`\n : [\n `const component = defineComponent(${quote(declaration.name)}, {`,\n ...envBlock,\n \"});\",\n ].join(\"\\n\"),\n );\n }\n\n for (const mount of declaration.mounts) {\n lines.push(\"\");\n lines.push(`${self}.use(${aliases.get(mount.importPath)}, {`);\n lines.push(` name: ${quote(mount.name)},`);\n if (mount.httpPrefix !== undefined) {\n lines.push(` httpPrefix: ${quote(mount.httpPrefix)},`);\n }\n if (mount.env.length > 0) {\n lines.push(\" env: {\");\n for (const [slot, binding] of mount.env) {\n lines.push(\n ` ${slot}: ${binding.kind === \"value\" ? quote(binding.value) : `${self}.env.${binding.key}`},`,\n );\n }\n lines.push(\" },\");\n }\n lines.push(\"});\");\n }\n\n lines.push(\"\", `export default ${self};`, \"\");\n return lines.join(\"\\n\");\n};\n\nconst providerValue = (value: ProviderValue): string => {\n switch (value.kind) {\n case \"value\":\n return quote(value.value);\n case \"env\":\n return `process.env[${quote(value.key)}]!`;\n default:\n return `\\`\\${process.env.${value.kind === \"siteUrl\" ? \"CONVEX_SITE_URL\" : \"CONVEX_CLOUD_URL\"}}${value.path.replaceAll(/[`$\\\\]/g, \"\\\\$&\")}\\``;\n }\n};\n\n/**\n * `convex/auth.config.ts`: Convex's provider list, with site URLs resolved\n * there.\n */\nexport const authConfig = (providers: ReadonlyArray<Provider>): string =>\n [\n header(\"confect/auth.ts\"),\n 'import type { AuthConfig } from \"convex/server\";',\n \"\",\n \"export default {\",\n providers.length === 0 ? \" providers: [],\" : \" providers: [\",\n ...(providers.length === 0\n ? []\n : [\n ...providers.flatMap((provider) => [\n \" {\",\n ...provider\n .filter(([field]) => field !== \"family\" && field !== \"name\")\n .map(\n ([field, value]) => ` ${field}: ${providerValue(value)},`,\n ),\n \" },\",\n ]),\n \" ],\",\n ]),\n \"} satisfies AuthConfig;\",\n \"\",\n ].join(\"\\n\");\n\n/**\n * Runtime issuer data with no dependency on declarations or component\n * definitions.\n */\nexport const authProviders = (providers: ReadonlyArray<Provider>): string =>\n [\n header(\"confect/auth.ts\"),\n \"\",\n \"export const providers = [\",\n ...providers.flatMap((provider) => [\n \" {\",\n ...provider.flatMap(([field, value]) => {\n const key =\n field === \"domain\"\n ? \"issuer\"\n : field === \"applicationID\"\n ? \"audience\"\n : field;\n return [\"issuer\", \"audience\", \"family\", \"name\"].includes(key)\n ? [` ${key}: ${providerValue(value)},`]\n : [];\n }),\n \" },\",\n ]),\n \"] as const;\",\n \"\",\n ].join(\"\\n\");\n\n/**\n * `confect/_generated/manifest.ts`: plain data, no imports, for infra.\n */\nexport const manifest = (\n declaration: Declaration,\n digest: string,\n sections: Readonly<Record<string, unknown>> = {},\n): string => {\n const data = {\n name: declaration.name,\n env: Object.fromEntries(declaration.env),\n http: {\n mounts: Object.fromEntries(\n declaration.mounts.flatMap(({ name, httpPrefix }) =>\n httpPrefix === undefined ? [] : [[name, httpPrefix]],\n ),\n ),\n },\n digest,\n ...sections,\n };\n return renderManifest(data);\n};\n\nexport const renderManifest = (\n data: Readonly<Record<string, unknown>>,\n): string =>\n `${header(\"confect/env.ts and confect/app.ts\")}\\n\\nexport default ${JSON.stringify(data, null, 2)} as const;\\n`;\n\n/**\n * A digest of the declaration's inputs: every first-party file its modules\n * import (by project-relative path and contents) and the versions of the\n * packages that shape the generated output.\n */\nexport const digest = (input: {\n readonly files: ReadonlyArray<readonly [string, string]>;\n readonly versions: ReadonlyArray<readonly [string, string]>;\n readonly sections?: Readonly<Record<string, unknown>>;\n}): string => {\n const hash = createHash(\"sha256\");\n const byFirst = (\n a: readonly [string, string],\n b: readonly [string, string],\n ) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);\n hash.update(\n JSON.stringify({\n files: [...input.files].sort(byFirst),\n versions: [...input.versions].sort(byFirst),\n ...(input.sections === undefined ? {} : { sections: input.sections }),\n }),\n );\n return `sha256:${hash.digest(\"hex\")}`;\n};\n"],"mappings":";;;;;;;AAwCA,IAAa,kBAAb,cAAqC,KAAK,YAAY,iBAAiB,CAAC,CAGrE;CACD,IAAa,UAAkB;EAC7B,OAAO,GAAG,KAAK,KAAK,uBAAuB,KAAK,SAAS;CAC3D;AACF;AAEA,IAAa,gBAAb,cAAmC,KAAK,YAAY,eAA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AC,OAAO,WAAW;GACtC,MAAM,MACJ,UAAU,WACN,WACA,UAAU,kBACR,aACA;GACR,OAAO;IAAC;IAAU;IAAY;IAAU;GAAM,CAAC,CAAC,SAAS,GAAG,IACxD,CAAC,OAAO,IAAI,IAAI,cAAc,KAAK,EAAE,EAAE,IACvC,CAAC;EACP,CAAC;EACD;CACF,CAAC;CACD;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;AAKb,MAAa,YACX,aACA,QACA,WAA8C,CAAC,MACpC;CACX,MAAM,OAAO;EACX,MAAM,YAAY;EAClB,KAAK,OAAO,YAAY,YAAY,GAAG;EACvC,MAAM,EACJ,QAAQ,OAAO,YACb,YAAY,OAAO,SAAS,EAAE,MAAM,iBAClC,eAAe,KAAA,IAAY,CAAC,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,CACrD,CACF,EACF;EACA;EACA,GAAG;CACL;CACA,OAAO,eAAe,IAAI;AAC5B;AAEA,MAAa,kBACX,SAEA,GAAG,OAAO,mCAAmC,EAAE,qBAAqB,KAAK,UAAU,MAAM,MAAM,CAAC,EAAE;;;;;;AAOpG,MAAa,UAAU,UAIT;CACZ,MAAM,OAAO,WAAW,QAAQ;CAChC,MAAM,WACJ,GACA,MACI,EAAE,KAAK,EAAE,KAAK,KAAK,EAAE,KAAK,EAAE,KAAK,IAAI;CAC3C,KAAK,OACH,KAAK,UAAU;EACb,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC,KAAK,OAAO;EACpC,UAAU,CAAC,GAAG,MAAM,QAAQ,CAAC,CAAC,KAAK,OAAO;EAC1C,GAAI,MAAM,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,MAAM,SAAS;CACrE,CAAC,CACH;CACA,OAAO,UAAU,KAAK,OAAO,KAAK;AACpC"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { InvalidDeclarationError } from "./CodegenError.mjs";
|
|
2
|
+
import * as Result from "effect/Result";
|
|
3
|
+
import * as Predicate from "effect/Predicate";
|
|
4
|
+
//#region src/ManifestSections.ts
|
|
5
|
+
const reserved = new Set("name env http digest __proto__ constructor prototype".split(" "));
|
|
6
|
+
const sections = (manifest) => Object.fromEntries(Object.entries(manifest).filter(([key]) => !reserved.has(key)));
|
|
7
|
+
const json = () => {
|
|
8
|
+
const ancestors = [];
|
|
9
|
+
return function(key, value) {
|
|
10
|
+
while (ancestors.length > 0 && ancestors.at(-1)?.value !== this) ancestors.pop();
|
|
11
|
+
const parent = ancestors.at(-1);
|
|
12
|
+
const path = parent === void 0 ? "$" : `${parent.path}[${JSON.stringify(key)}]`;
|
|
13
|
+
if (key === "__proto__" || ![
|
|
14
|
+
"string",
|
|
15
|
+
"number",
|
|
16
|
+
"boolean",
|
|
17
|
+
"object"
|
|
18
|
+
].includes(typeof value) || typeof value === "number" && !Number.isFinite(value) || typeof value === "object" && value !== null && !Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || ancestors.some((ancestor) => ancestor.value === value)) throw new TypeError(`Expected JSON data at ${path}`);
|
|
19
|
+
if (typeof value === "object" && value !== null) ancestors.push({
|
|
20
|
+
value,
|
|
21
|
+
path
|
|
22
|
+
});
|
|
23
|
+
return value;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
const collect = (leaves) => Result.gen(function* () {
|
|
27
|
+
const registry = /* @__PURE__ */ new Map();
|
|
28
|
+
const visit = (group, path, source) => Result.gen(function* () {
|
|
29
|
+
for (const spec of Object.values(group.functions)) {
|
|
30
|
+
const functionPath = `${path}:${spec.name}`;
|
|
31
|
+
for (const { key, section } of spec.manifestSections ?? []) {
|
|
32
|
+
const invalid = (reason) => new InvalidDeclarationError({
|
|
33
|
+
declarationPath: `confect/${source}`,
|
|
34
|
+
reason: `Manifest section "${key}" (${functionPath}): ${reason}`
|
|
35
|
+
});
|
|
36
|
+
if (reserved.has(key)) return yield* Result.fail(invalid("shadows a built-in key."));
|
|
37
|
+
const existing = registry.get(key);
|
|
38
|
+
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}).`));
|
|
39
|
+
const entry = existing ?? {
|
|
40
|
+
section,
|
|
41
|
+
source,
|
|
42
|
+
data: {
|
|
43
|
+
format: section.format,
|
|
44
|
+
functions: Object.create(null)
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
registry.set(key, entry);
|
|
48
|
+
entry.data.functions[functionPath] = yield* Result.try({
|
|
49
|
+
try: () => JSON.parse(JSON.stringify(section.describe({
|
|
50
|
+
path: functionPath,
|
|
51
|
+
spec,
|
|
52
|
+
middleware: [...group.middlewareSpecs, ...spec.middlewareSpecs]
|
|
53
|
+
}), json())),
|
|
54
|
+
catch: (cause) => invalid(`could not describe as JSON: ${String(cause)}`)
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const [name, child] of Object.entries(group.groups)) yield* visit(child, `${path}/${name}`, source);
|
|
59
|
+
});
|
|
60
|
+
for (const leaf of leaves) yield* visit(leaf.spec, leaf.pathSegments.join("/"), leaf.relativePath);
|
|
61
|
+
return registry;
|
|
62
|
+
});
|
|
63
|
+
const check = (registry, previous) => {
|
|
64
|
+
const errors = [];
|
|
65
|
+
const notes = [];
|
|
66
|
+
for (const [key, { section, source, data }] of registry) try {
|
|
67
|
+
const checked = section.check?.(data, previous[key]);
|
|
68
|
+
if (checked === void 0) continue;
|
|
69
|
+
notes.push(...checked.notes);
|
|
70
|
+
if (checked.errors.length > 0) errors.push(new InvalidDeclarationError({
|
|
71
|
+
declarationPath: `confect/${source}`,
|
|
72
|
+
reason: [...new Set(checked.errors)].join("\n")
|
|
73
|
+
}));
|
|
74
|
+
} catch (cause) {
|
|
75
|
+
errors.push(new InvalidDeclarationError({
|
|
76
|
+
declarationPath: `confect/${source}`,
|
|
77
|
+
reason: `Manifest section "${key}" check failed: ${String(cause)}`
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
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(", ")}.`);
|
|
81
|
+
return {
|
|
82
|
+
errors,
|
|
83
|
+
notes
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
//#endregion
|
|
87
|
+
export { check, collect, sections };
|
|
88
|
+
|
|
89
|
+
//# 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 type { LoadedLeafModule } from \"./LeafModule.js\";\nimport { InvalidDeclarationError } 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 );\nconst json = () => {\n const ancestors: { value: object; path: string }[] = [];\n return function (this: object, key: string, value: unknown) {\n while (ancestors.length > 0 && ancestors.at(-1)?.value !== this)\n ancestors.pop();\n const parent = ancestors.at(-1);\n const path =\n parent === undefined ? \"$\" : `${parent.path}[${JSON.stringify(key)}]`;\n if (\n key === \"__proto__\" ||\n ![\"string\", \"number\", \"boolean\", \"object\"].includes(typeof value) ||\n (typeof value === \"number\" && !Number.isFinite(value)) ||\n (typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n ![Object.prototype, null].includes(Object.getPrototypeOf(value))) ||\n ancestors.some((ancestor) => ancestor.value === value)\n )\n throw new TypeError(`Expected JSON data at ${path}`);\n if (typeof value === \"object\" && value !== null)\n ancestors.push({ value, path });\n return value;\n };\n};\nexport type Registry = Map<\n string,\n {\n section: ManifestSection.ManifestSection;\n source: string;\n data: { format: number; functions: Record<string, unknown> };\n }\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 source,\n data: {\n format: section.format,\n functions: Object.create(null) as Record<string, unknown>,\n },\n };\n registry.set(key, entry);\n entry.data.functions[functionPath] = yield* Result.try({\n try: () =>\n JSON.parse(\n JSON.stringify(\n section.describe({\n path: functionPath,\n spec,\n middleware: [\n ...group.middlewareSpecs,\n ...spec.middlewareSpecs,\n ],\n }),\n json(),\n ),\n ),\n catch: (cause) =>\n invalid(`could not describe as JSON: ${String(cause)}`),\n });\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\nexport const check = (\n registry: Registry,\n previous: Readonly<Record<string, unknown>>,\n) => {\n const errors: InvalidDeclarationError[] = [];\n const notes: string[] = [];\n for (const [key, { section, source, 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 InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: [...new Set(checked.errors)].join(\"\\n\"),\n }),\n );\n } catch (cause) {\n errors.push(\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `Manifest section \"${key}\" 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":";;;;AAMA,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;AACF,MAAM,aAAa;CACjB,MAAM,YAA+C,CAAC;CACtD,OAAO,SAAwB,KAAa,OAAgB;EAC1D,OAAO,UAAU,SAAS,KAAK,UAAU,GAAG,EAAE,CAAC,EAAE,UAAU,MACzD,UAAU,IAAI;EAChB,MAAM,SAAS,UAAU,GAAG,EAAE;EAC9B,MAAM,OACJ,WAAW,KAAA,IAAY,MAAM,GAAG,OAAO,KAAK,GAAG,KAAK,UAAU,GAAG,EAAE;EACrE,IACE,QAAQ,eACR,CAAC;GAAC;GAAU;GAAU;GAAW;EAAQ,CAAC,CAAC,SAAS,OAAO,KAAK,KAC/D,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KACnD,OAAO,UAAU,YAChB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK,KACpB,CAAC,C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DAAoD,OAAO,KAAK,MAAM,SAAS,CAAC,CAAC,KAAK,IAAI,EAAE,EACvH;CAEJ,OAAO;EAAE;EAAQ;CAAM;AACzB"}
|
package/dist/confect/codegen.mjs
CHANGED
|
@@ -18,7 +18,7 @@ import { implPathForSpec, loadAll, registeredFunctionsRelativePath, validateAllI
|
|
|
18
18
|
import { TABLES_DIRNAME, discover, validate } from "../TableModule.mjs";
|
|
19
19
|
import { planDeclarations } from "../EntryPoint.mjs";
|
|
20
20
|
import { preserveComponentOutput } from "../Rollback.mjs";
|
|
21
|
-
import { syncDeclaration, syncDeclaredHttp } from "./declaration.mjs";
|
|
21
|
+
import { readPrevious, syncDeclaration, syncDeclaredHttp, syncManifestSections } from "./declaration.mjs";
|
|
22
22
|
import * as Effect from "effect/Effect";
|
|
23
23
|
import * as Command from "effect/cli/Command";
|
|
24
24
|
import { App, Callback, Env, Spec } from "@confect/core";
|
|
@@ -62,7 +62,8 @@ const generateWithSnapshot = Effect.gen(function* () {
|
|
|
62
62
|
yield* assertOwnedEntrypoints;
|
|
63
63
|
yield* validateComponentConfiguration;
|
|
64
64
|
yield* generateConfectGeneratedDirectory;
|
|
65
|
-
const
|
|
65
|
+
const previousManifest = yield* readPrevious;
|
|
66
|
+
const { app: declared, digest } = yield* syncDeclaration(previousManifest);
|
|
66
67
|
yield* rejectLegacySchemaFile;
|
|
67
68
|
const tableModules = yield* discover;
|
|
68
69
|
yield* warnIfNoTables(tableModules);
|
|
@@ -76,6 +77,7 @@ const generateWithSnapshot = Effect.gen(function* () {
|
|
|
76
77
|
yield* generateRuntimeSchema(tableModules);
|
|
77
78
|
const leaves = yield* loadAll;
|
|
78
79
|
yield* rejectComponentNodeGroups(leaves);
|
|
80
|
+
yield* syncManifestSections(leaves, previousManifest, digest);
|
|
79
81
|
yield* removeLegacyFiles;
|
|
80
82
|
const snapshot = yield* Effect.fromResult(fromLoadedLeaves(leaves));
|
|
81
83
|
yield* generateAssembledSpecs(leaves);
|
|
@@ -111,13 +113,15 @@ const generateWithSnapshot = Effect.gen(function* () {
|
|
|
111
113
|
const makeCodegenHandler = (duringRestore) => preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(Effect.tap(() => touchConvexSchema), Effect.map(({ functionPaths }) => ({ functionPaths })));
|
|
112
114
|
const codegenHandler = makeCodegenHandler();
|
|
113
115
|
const updateDeclarations = Effect.fn("Cli.updateDeclarations")(function* (snapshot, declarations, affectedImpls) {
|
|
116
|
+
const previousManifest = yield* readPrevious;
|
|
114
117
|
const path = yield* Path.Path;
|
|
115
118
|
const { paths, tables } = planDeclarations(declarations, affectedImpls, path);
|
|
116
119
|
yield* validate(tables);
|
|
117
120
|
return yield* withImplFiles(paths, (leaves) => Effect.gen(function* () {
|
|
118
121
|
yield* rejectComponentNodeGroups(leaves);
|
|
119
122
|
const next = yield* Effect.fromResult(update(snapshot, leaves));
|
|
120
|
-
const declared = yield* syncDeclaration;
|
|
123
|
+
const { app: declared, digest } = yield* syncDeclaration(previousManifest);
|
|
124
|
+
if (Option.isSome(declared)) yield* syncManifestSections(yield* loadAll, previousManifest, digest);
|
|
121
125
|
const required = Option.isSome(declared) ? declared.value.requiresMiddleware : [];
|
|
122
126
|
yield* validateAllImpls(leaves, required);
|
|
123
127
|
yield* generateGroupRegisteredFunctions(leaves, required);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen.mjs","names":["DirectoryOptions.flags","CodegenError.tapAndLog","DirectoryOptions.layer","FunctionModule.assertOwnedEntrypoints","TableModule.discover","TableModule.validate","GenerationSnapshot.fromLoadedLeaves","FunctionModule.generateFunctions","EntryPoint.planDeclarations","GenerationSnapshot.update","FunctionModule.applyFunctionPlan","GenerationSnapshot.diff","CodegenError.ComponentNodeGroupError","ConvexConfig.componentName","ConvexConfig.CONVEX_CONFIG_FILENAME","Bundler.bundle","CodegenError.CallbackPrefixError","CodegenError.InvalidConvexConfigError","templates.componentContract","templates.assembledSpec","templates.registeredFunctionsForGroup","FunctionPaths.make","TableModule.TABLES_DIRNAME","templates.id","templates.tableWrapper","templates.runtimeSchema","templates.convexSchema","templates.schema","templates.services","DocName.fromTableName","CodegenError.ConflictingDocNameError","templates.docs","templates.refs","ConvexConfig.discoverInstalledComponents","templates.components","ConvexConfig.typeImportPath","CodegenError.InvalidDeclarationError","Bundler.resolveModule","Bundler.exportNames","ConvexConfig.resolveDefinition"],"sources":["../../src/confect/codegen.ts"],"sourcesContent":["import { App, Callback, Env, type GroupSpec, Spec } from \"@confect/core\";\nimport * as Command from \"effect/cli/Command\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport type * as PlatformError from \"effect/PlatformError\";\nimport type { BuildError } from \"../BuildError.js\";\nimport { pipe } from \"effect/Function\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Record from \"effect/Record\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Bundler from \"../Bundler.js\";\nimport { fromBundlerError } from \"../BuildError.js\";\nimport * as CodegenError from \"../CodegenError.js\";\nimport { LegacySchemaFileError } from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as DocName from \"../DocName.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as FunctionModule from \"../FunctionModule.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport * as EntryPoint from \"../EntryPoint.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport {\n implPathForSpec,\n loadAll,\n registeredFunctionsRelativePath,\n validateAllImpls,\n withImplFiles,\n type LeafModule,\n type LoadedLeafModule,\n} from \"../LeafModule.js\";\nimport {\n logFileAdded,\n logFileModified,\n logFileRemoved,\n logPending,\n logSuccess,\n logWarn,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport { assemblyNodesFromLeaves } from \"../SpecAssemblyNode.js\";\nimport * as TableModule from \"../TableModule.js\";\nimport * as templates from \"../templates.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n removePathIfExists,\n toModuleImportPath,\n touchConvexSchema,\n writeFileStringAndLog,\n} from \"../utils.js\";\nimport { syncDeclaration, syncDeclaredHttp } from \"./declaration.js\";\n\nconst GENERATED_DIRNAME = \"_generated\";\n\nconst isComponent = Effect.map(\n ConvexDirectory.target,\n (target) => target.kind === \"component\",\n);\n\nconst GENERATED_SPEC_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"spec.ts\"),\n);\nconst GENERATED_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"schema.ts\"),\n);\nconst GENERATED_CONVEX_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"convexSchema.ts\"),\n);\nconst GENERATED_ID_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"id.ts\"),\n);\nconst GENERATED_COMPONENTS_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"components.ts\"),\n);\nconst GENERATED_TABLES_DIRNAME = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"tables\"),\n);\n\nconst LEGACY_PATHS = Effect.gen(function* () {\n const path = yield* Path.Path;\n\n return [\n \"spec.ts\",\n \"nodeSpec.ts\",\n \"impl.ts\",\n \"nodeImpl.ts\",\n path.join(GENERATED_DIRNAME, \"registeredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeRegisteredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"impl.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeImpl.ts\"),\n // `_generated/nodeSpec.ts` is not part of the generated output (all groups\n // live in `_generated/spec.ts`); delete any copy left by an older version.\n path.join(GENERATED_DIRNAME, \"nodeSpec.ts\"),\n ];\n});\n\nexport const codegen = Command.make(\"codegen\", DirectoryOptions.flags, () =>\n Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n yield* codegenHandler.pipe(\n Effect.asVoid,\n Effect.tap(() => logSuccess(\"Generated files are up-to-date\")),\n CodegenError.tapAndLog,\n );\n }),\n).pipe(\n Command.provide(DirectoryOptions.layer),\n Command.withDescription(\n \"Generate `confect/_generated` files and the contents of the `convex` directory (except `tsconfig.json`, and `convex.config.ts` unless `confect/app.ts` declares the backend)\",\n ),\n);\n\nconst runCodegen = Effect.gen(function* () {\n yield* FunctionModule.assertOwnedEntrypoints;\n yield* validateComponentConfiguration;\n yield* generateConfectGeneratedDirectory;\n // A declared backend's `convex.config.ts` and manifest come first: the\n // components registry below reads the config, and nothing may validate\n // against a manifest the current declaration did not produce.\n const declared = yield* syncDeclaration;\n // Reject a legacy `confect/schema.ts` up front so the user-facing\n // migration message surfaces before any bundler error from impl\n // validation (each impl imports `_generated/schema.ts`).\n yield* rejectLegacySchemaFile;\n // List `confect/tables/*.ts` (filename-only—no bundling yet) so the\n // `_generated/id.ts` constructor can be emitted *before* we bundle any\n // user-authored table module. Tables import from `_generated/id.ts` for\n // cross-table id refs, so it must exist on disk first.\n const tableModules = yield* TableModule.discover;\n yield* warnIfNoTables(tableModules);\n yield* generateIdConstructor(tableModules);\n // Tables and specs can use bound component IDs and schemas, so their\n // imports need the registry even on a project's first codegen run.\n yield* generateComponents;\n yield* validateCallbackPrefixes(declared);\n // Now that `_generated/id.ts` is on disk, bundle each table module and\n // check its default export is an `UnnamedTable`. Surface diagnostics\n // here (rather than later) so they appear before impl-validation noise.\n yield* TableModule.validate(tableModules);\n yield* validateNoDocNameCollisions(tableModules);\n yield* generateTableWrappers(tableModules);\n yield* removeObsoleteTableWrappers(tableModules);\n yield* generateRuntimeSchema(tableModules);\n const leaves = yield* loadAll;\n yield* rejectComponentNodeGroups(leaves);\n yield* removeLegacyFiles;\n const snapshot = yield* Effect.fromResult(\n GenerationSnapshot.fromLoadedLeaves(leaves),\n );\n yield* generateAssembledSpecs(leaves);\n // `_generated/api.ts`/`nodeApi.ts` are no longer imported by generated or\n // impl code (impls take the database schema from `_generated/schema`\n // directly), so remove any copies left over from earlier versions before\n // impl validation runs.\n yield* Effect.all(\n [\n removeGeneratedApi,\n generateRefs,\n generateComponentContract(tableModules),\n removeGeneratedNodeApi,\n generateDocs(tableModules),\n generateServices,\n generateConvexSchema(tableModules),\n ],\n { concurrency: \"unbounded\" },\n );\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n yield* generateGroupRegisteredFunctions(leaves, required);\n yield* removeObsoleteRegisteredFunctions(leaves);\n const [functionPaths] = yield* Effect.all(\n [\n FunctionModule.generateFunctions(snapshot),\n generateConvexSchemaReexport,\n logGenerated(\n Option.match(declared, {\n onNone: () => generateHttp,\n onSome: syncDeclaredHttp,\n }),\n ),\n logGenerated(generateCrons),\n Option.isNone(declared)\n ? logGenerated(generateAuthConfig)\n : Effect.succeedNone,\n ],\n { concurrency: \"unbounded\" },\n );\n if (Option.isSome(declared)) yield* generateTesting(declared.value);\n return {\n functionPaths,\n snapshot,\n };\n});\n\nexport const generateWithSnapshot = runCodegen.pipe(\n Effect.withSpan(\"Cli.codegen\"),\n);\n\nexport const makeCodegenHandler = (\n duringRestore?: Effect.Effect<void, never, Scope.Scope>,\n) =>\n preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(\n Effect.tap(() => touchConvexSchema),\n Effect.map(({ functionPaths }) => ({ functionPaths })),\n );\n\nexport const codegenHandler = makeCodegenHandler();\n\nexport const updateDeclarations = Effect.fn(\"Cli.updateDeclarations\")(\n function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n ) {\n const path = yield* Path.Path;\n const { paths, tables } = EntryPoint.planDeclarations(\n declarations,\n affectedImpls,\n path,\n );\n yield* TableModule.validate(tables);\n return yield* withImplFiles(paths, (leaves) =>\n Effect.gen(function* () {\n yield* rejectComponentNodeGroups(leaves);\n const next = yield* Effect.fromResult(\n GenerationSnapshot.update(snapshot, leaves),\n );\n const declared = yield* syncDeclaration;\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n yield* generateGroupRegisteredFunctions(leaves, required);\n yield* FunctionModule.applyFunctionPlan(\n GenerationSnapshot.diff(snapshot, next),\n );\n return next;\n }),\n );\n },\n);\n\n// Convex components cannot run Node.js functions, at any nesting depth.\nconst validateComponentGroupRuntime = (\n group: GroupSpec.AnyWithProps,\n groupPath: string,\n specPath: string,\n): Result.Result<void, CodegenError.ComponentNodeGroupError> =>\n Result.gen(function* () {\n if (group.runtime === \"Node\") {\n return yield* Result.fail(\n new CodegenError.ComponentNodeGroupError({ specPath, groupPath }),\n );\n }\n for (const [name, child] of Object.entries(group.groups)) {\n yield* validateComponentGroupRuntime(\n child,\n `${groupPath}.${name}`,\n specPath,\n );\n }\n });\n\nconst rejectComponentNodeGroups = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n if ((yield* ConvexDirectory.target).kind === \"app\") return;\n yield* Effect.forEach(leaves, (leaf) =>\n Effect.fromResult(\n validateComponentGroupRuntime(\n leaf.spec,\n leaf.groupPathDot,\n leaf.relativePath,\n ),\n ),\n );\n});\n\nconst validateCallbackPrefixes = Effect.fnUntraced(function* (\n declared: Option.Option<App.Any>,\n) {\n if ((yield* ConvexDirectory.target).kind !== \"component\") return;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const callbacksPath = path.join(yield* ConfectDirectory.get, \"callbacks.ts\");\n if (!(yield* fs.exists(callbacksPath))) return;\n const name = Option.isSome(declared)\n ? Env.name(App.env(declared.value))\n : yield* ConvexConfig.componentName(\n path.join(\n yield* ConvexDirectory.get,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n ),\n );\n const { module } = yield* Bundler.bundle(callbacksPath).pipe(\n Effect.mapError((error) => fromBundlerError(\"confect/callbacks.ts\", error)),\n );\n for (const contract of Object.values(module)) {\n if (Callback.isContract(contract) && !contract.id.startsWith(`${name}/`)) {\n return yield* new CodegenError.CallbackPrefixError({\n declarationPath: \"confect/callbacks.ts\",\n contractId: contract.id,\n componentName: name,\n });\n }\n }\n});\n\nconst validateComponentConfiguration = Effect.gen(function* () {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const authPath = path.join(confectDirectory, \"auth.ts\");\n if (yield* fs.exists(authPath)) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: authPath,\n reason:\n \"Components cannot configure application authentication. Pass identity explicitly through function arguments.\",\n });\n }\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateComponentContract = Effect.fnUntraced(function* (\n tables: ReadonlyArray<TableModule.TableModule>,\n) {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const directory = yield* ConfectDirectory.get;\n const contents = yield* templates.componentContract({\n tableNames: Array.map(tables, (table) => table.tableName),\n });\n yield* writeFileStringAndLog(\n path.join(directory, GENERATED_DIRNAME, \"component.ts\"),\n contents,\n );\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateConfectGeneratedDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n if (!(yield* fs.exists(path.join(confectDirectory, \"_generated\")))) {\n yield* fs.makeDirectory(path.join(confectDirectory, \"_generated\"), {\n recursive: true,\n });\n yield* logFileAdded(path.join(confectDirectory, \"_generated\") + \"/\");\n }\n});\n\nconst removeLegacyFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPaths = yield* LEGACY_PATHS;\n\n yield* Effect.forEach(\n legacyPaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const absolutePath = path.join(confectDirectory, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n }),\n );\n});\n\nconst generateAssembledSpecs = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n // A single assembled spec holds every group regardless of runtime—a Node\n // group's `makeNode()` lives in its imported leaf spec, so the assembled\n // file is runtime-agnostic. Always emit it (even empty) so downstream\n // readers (`loadGeneratedSpec`, `generateRefs`) always find a spec module.\n const nodes = assemblyNodesFromLeaves(leaves);\n const specContents = yield* templates.assembledSpec({ nodes });\n yield* writeFileStringAndLog(\n path.join(confectDirectory, generatedSpecPath),\n specContents,\n );\n});\n\nconst generateGroupRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const confectDirectory = yield* ConfectDirectory.get;\n const runtimePath = path.join(confectDirectory, \"runtime.ts\");\n const hasRuntime = yield* fs.exists(runtimePath);\n\n yield* Effect.forEach(\n leaves,\n Effect.fnUntraced(function* (leaf: LoadedLeafModule) {\n const registryRelativePath = yield* registeredFunctionsRelativePath(leaf);\n const registryPath = path.join(\n confectDirectory,\n \"_generated\",\n registryRelativePath,\n );\n const registryDir = path.dirname(registryPath);\n if (!(yield* fs.exists(registryDir))) {\n yield* fs.makeDirectory(registryDir, { recursive: true });\n }\n\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n );\n // The group's own leaf spec (sibling of its impl), referenced\n // type-only by the registry to shape its returned record.\n const specImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, leaf.relativePath),\n ),\n );\n const implImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, implRelativePath),\n ),\n );\n\n const contents = yield* templates.registeredFunctionsForGroup({\n spec: leaf.spec,\n required,\n groupPath: leaf.groupPathDot,\n schemaImportPath,\n specImportPath,\n implImportPath,\n runtimeImportPath: hasRuntime\n ? yield* toModuleImportPath(path.relative(registryDir, runtimePath))\n : undefined,\n });\n\n yield* writeFileStringAndLog(registryPath, contents);\n }),\n );\n});\n\nconst removeObsoleteRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const registryRoot = path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n );\n\n if (!(yield* fs.exists(registryRoot))) {\n return;\n }\n\n const expected = new Set(\n yield* Effect.forEach(leaves, (leaf) =>\n registeredFunctionsRelativePath(leaf),\n ),\n );\n\n const existing = yield* fs.readDirectory(registryRoot, { recursive: true });\n yield* Effect.forEach(existing, (relativePath) => {\n if (path.extname(relativePath) !== \".ts\") {\n return Effect.void;\n }\n const normalized = path.join(\"registeredFunctions\", relativePath);\n if (!expected.has(normalized)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(registryRoot, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst getGeneratedSpecPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n return path.join(confectDirectory, generatedSpecPath);\n});\n\nconst loadGeneratedSpec = Effect.gen(function* () {\n const specPath = yield* getGeneratedSpecPath;\n const { module: specModule } = yield* Bundler.bundle(specPath);\n const spec = specModule.default;\n\n if (!Spec.isSpec(spec)) {\n return yield* Effect.die(\n new Error(\"_generated/spec.ts does not export a valid Spec\"),\n );\n }\n\n return spec;\n});\n\nconst emptyFunctionPaths = FunctionPaths.FunctionPaths.make(HashSet.empty());\n\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const specPath = yield* getGeneratedSpecPath;\n\n if (!(yield* fs.exists(specPath))) {\n return emptyFunctionPaths;\n }\n\n const specResult = yield* loadGeneratedSpec.pipe(Effect.result);\n\n return Result.match(specResult, {\n onFailure: () => emptyFunctionPaths,\n onSuccess: (spec) => FunctionPaths.make(spec),\n });\n});\n\n/**\n * Remove a now-obsolete `_generated/<name>.ts` if present (and log it), for\n * projects upgrading from a version that still emitted it.\n */\nconst removeObsoleteGeneratedFile = Effect.fnUntraced(function* (\n fileName: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const filePath = path.join(confectDirectory, \"_generated\", fileName);\n\n if (yield* fs.exists(filePath)) {\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n }\n});\n\n// `_generated/api.ts` is no longer imported by generated or impl code: impls\n// take the database schema (`_generated/schema`) directly, and per-group\n// registries reference the spec type-only. Remove any stale copy.\nconst removeGeneratedApi = removeObsoleteGeneratedFile(\"api.ts\");\n\n// `_generated/nodeApi.ts` is obsolete for the same reason.\nconst removeGeneratedNodeApi = removeObsoleteGeneratedFile(\"nodeApi.ts\");\n\n/**\n * The user-authored `confect/schema.ts` is no longer supported: codegen now\n * owns both `_generated/schema.ts` (runtime) and `_generated/convexSchema.ts`\n * (deploy), derived from a single scan of `confect/tables/*.ts`. Detect a stray\n * file and fail with a clear migration message—leaving it in place would\n * silently shadow the codegen-owned\n * `_generated/schema.ts`/`_generated/convexSchema.ts`.\n */\nconst rejectLegacySchemaFile = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPath = path.join(confectDirectory, \"schema.ts\");\n\n if (yield* fs.exists(legacyPath)) {\n return yield* new LegacySchemaFileError({ schemaPath: \"schema.ts\" });\n }\n});\n\n/**\n * Surface a yellow `⚠` warning when codegen sees no tables—either the\n * `confect/tables/` directory is missing or it contains no `.ts` files.\n * Generation still succeeds (emitting an empty `DatabaseSchema` and\n * `defineSchema({})`), since action-only/table-free Confect backends are\n * legal—but the warning catches the much more common case of a typoed directory\n * or files placed under the wrong root.\n */\nconst warnIfNoTables = (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) =>\n tableModules.length === 0\n ? logWarn(\n `No tables discovered in \\`confect/${TableModule.TABLES_DIRNAME}/\\`. ` +\n `Generating an empty schema; add a \\`Table.make(...)\\` module under that ` +\n `directory unless this backend is intentionally tables-free.`,\n )\n : Effect.void;\n\nconst tableModuleBindings = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n generatedFilePath: string,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDir = path.dirname(generatedFilePath);\n\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n\n return yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperAbsolutePath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const importPath = yield* toModuleImportPath(\n path.relative(generatedDir, wrapperAbsolutePath),\n );\n return {\n importPath,\n tableName: tableModule.tableName,\n };\n }),\n );\n});\n\nconst generateIdConstructor = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedIdPath = yield* GENERATED_ID_PATH;\n const idPath = path.join(confectDirectory, generatedIdPath);\n\n const tableNames = Array.map(\n tableModules,\n (tableModule) => tableModule.tableName,\n );\n const contents = yield* Match.value(yield* ConvexDirectory.target).pipe(\n Match.when({ kind: \"app\" }, () => templates.id({ tableNames })),\n Match.when({ kind: \"component\" }, ({ scope }) =>\n templates.id({ tableNames, scope }),\n ),\n Match.exhaustive,\n );\n\n yield* writeFileStringAndLog(idPath, contents);\n});\n\nconst generateTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n yield* fs.makeDirectory(wrappersDir, { recursive: true });\n }\n\n yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperPath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const unnamedAbsolutePath = path.join(\n confectDirectory,\n tableModule.relativePath,\n );\n const unnamedImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(wrapperPath), unnamedAbsolutePath),\n );\n const contents = yield* templates.tableWrapper({\n tableName: tableModule.tableName,\n unnamedImportPath,\n component: yield* isComponent,\n });\n yield* writeFileStringAndLog(wrapperPath, contents);\n }),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * Remove any stale `_generated/tables/*.ts` wrapper whose source table has been\n * deleted or renamed. Mirrors `removeObsoleteRegisteredFunctions` for the\n * wrapper directory.\n */\nconst removeObsoleteTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n return;\n }\n\n const expected = new Set(\n Array.map(tableModules, (tableModule) => `${tableModule.tableName}.ts`),\n );\n const existing = yield* fs.readDirectory(wrappersDir, { recursive: true });\n yield* Effect.forEach(existing, (entry) => {\n if (path.extname(entry) !== \".ts\") {\n return Effect.void;\n }\n if (!expected.has(entry)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(wrappersDir, entry);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst generateRuntimeSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaPath = path.join(confectDirectory, generatedSchemaPath);\n\n const bindings = yield* tableModuleBindings(tableModules, schemaPath);\n const contents = yield* templates.runtimeSchema({\n tableModules: bindings,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(schemaPath, contents);\n});\n\nconst generateConvexSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedConvexSchemaPath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n const convexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaPath,\n );\n\n const bindings = yield* tableModuleBindings(tableModules, convexSchemaPath);\n const contents = yield* templates.convexSchema({ tableModules: bindings });\n\n yield* writeFileStringAndLog(convexSchemaPath, contents);\n});\n\nconst generateConvexSchemaReexport = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generatedConvexSchemaRelativePath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n\n const convexSchemaPath = path.join(convexDirectory, \"schema.ts\");\n const generatedConvexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaRelativePath,\n );\n\n const convexSchemaImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(convexSchemaPath), generatedConvexSchemaPath),\n );\n\n const schemaContents = yield* templates.schema({\n convexSchemaImportPath,\n });\n\n yield* writeFileStringAndLog(convexSchemaPath, schemaContents);\n});\n\nconst generateServices = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const servicesPath = path.join(confectGeneratedDirectory, \"services.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(servicesPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const servicesContentsString = yield* templates.services({\n schemaImportPath,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(servicesPath, servicesContentsString);\n});\n\n/**\n * Two tables whose names fold to the same PascalCase document type name (e.g.\n * `user_profiles` and `userProfiles` → `UserProfilesDoc`) would emit duplicate\n * interfaces in `_generated/docs.ts`. Catch that up front with a clear error\n * rather than letting `tsc` report a duplicate-identifier later.\n */\nconst validateNoDocNameCollisions = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const collisions = pipe(\n tableModules,\n Array.groupBy((tableModule) =>\n DocName.fromTableName(tableModule.tableName),\n ),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([docName, group]) => ({\n docName,\n tableNames: Array.map(group, (tableModule) => tableModule.tableName),\n })),\n );\n\n if (Array.isReadonlyArrayNonEmpty(collisions)) {\n return yield* new CodegenError.ConflictingDocNameError({ collisions });\n }\n});\n\nconst generateDocs = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const docsPath = path.join(confectGeneratedDirectory, \"docs.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(docsPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const docsContentsString = yield* templates.docs({\n schemaImportPath,\n tables: Array.map(tableModules, (tableModule) => ({\n tableName: tableModule.tableName,\n docName: DocName.fromTableName(tableModule.tableName),\n })),\n });\n\n yield* writeFileStringAndLog(docsPath, docsContentsString);\n});\n\nconst generateRefs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n const refsPath = path.join(confectGeneratedDirectory, \"refs.ts\");\n const refsDir = path.dirname(refsPath);\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n const specImportPath = yield* toModuleImportPath(\n path.relative(refsDir, path.join(confectDirectory, generatedSpecPath)),\n );\n\n const refsContents = yield* templates.refs({ specImportPath });\n\n yield* writeFileStringAndLog(refsPath, refsContents);\n});\n\n/**\n * Generate `confect/_generated/components.ts`—the typed registry of Convex\n * components installed in `convex/convex.config.ts` (see\n * {@link templates.components}). The file is emitted even when there is no\n * `convex.config.ts` (as an empty registry) so the import surface stays stable.\n * It must exist before loading tables and specs because they may import bound\n * component IDs and schemas.\n */\nexport const generateComponents = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n\n const confectGeneratedDirectory = path.join(\n confectDirectory,\n GENERATED_DIRNAME,\n );\n const generatedComponentsPath = yield* GENERATED_COMPONENTS_PATH;\n const componentsPath = path.join(confectDirectory, generatedComponentsPath);\n\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n\n const installedComponents = (yield* fs.exists(convexConfigPath))\n ? yield* ConvexConfig.discoverInstalledComponents(\n convexConfigPath,\n path.relative(projectRoot, convexConfigPath),\n (yield* ConvexDirectory.target).kind,\n )\n : [];\n\n const contents = yield* templates.components({\n components: Array.map(\n installedComponents,\n ({ name, componentDefinitionPath }) => ({\n name,\n typeImportPath: ConvexConfig.typeImportPath(\n path,\n componentDefinitionPath,\n confectGeneratedDirectory,\n ),\n }),\n ),\n });\n\n yield* writeFileStringAndLog(componentsPath, contents);\n});\n\nconst logGenerated = <E, R>(\n effect: Effect.Effect<\n Option.Option<{\n readonly change: \"Added\" | \"Modified\" | \"Unchanged\";\n readonly convexFilePath: string;\n }>,\n E,\n R\n >,\n) =>\n effect.pipe(\n Effect.tap(\n Option.match({\n onNone: () => Effect.void,\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(convexFilePath)),\n Match.when(\"Modified\", () => logFileModified(convexFilePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n ),\n }),\n ),\n );\n\n/**\n * Test-only imports never enter the runtime schema or function wrappers.\n */\nconst quote = (value: string) => JSON.stringify(value);\n\n/**\n * A mount's `testing` kit must be a package specifier, so the generated\n * registry holds no machine-specific path, and must export `register`. A kit\n * whose exports cannot be listed without running it passes here, and\n * `TestConfect.layer` names the mount if it has no `register`.\n */\nconst checkTestKit = Effect.fnUntraced(function* (\n mount: string,\n specifier: string,\n config: string,\n configDisplay: string,\n) {\n const path = yield* Path.Path;\n const invalid = (problem: string) =>\n new CodegenError.InvalidDeclarationError({\n declarationPath: \"confect/app.ts\",\n reason: `the mount ${quote(mount)} names the test kit ${quote(specifier)}${problem}`,\n });\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) {\n return yield* invalid(\n '; name it by a package specifier, such as \"<package>/testing\".',\n );\n }\n const resolved = Bundler.resolveModule(specifier, config);\n if (Option.isNone(resolved)) {\n return yield* invalid(`, which does not resolve from ${configDisplay}.`);\n }\n const exports = yield* Bundler.exportNames(resolved.value).pipe(\n Effect.mapError((error) => fromBundlerError(specifier, error)),\n );\n if (Option.isSome(exports) && !exports.value.includes(\"register\")) {\n return yield* invalid(\", which does not export `register(t, name)`.\");\n }\n});\n\nconst generateTesting = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const configDisplay = path\n .relative(\n yield* ProjectRoot.get,\n path.join(convexDirectory, ConvexConfig.CONVEX_CONFIG_FILENAME),\n )\n .split(path.sep)\n .join(\"/\");\n const relative = (file: string) => {\n const value = path.relative(generated, file).split(path.sep).join(\"/\");\n return value.startsWith(\".\") ? value : `./${value}`;\n };\n const imports = [\n 'import schema from \"./schema.js\";',\n 'import convexSchema from \"./convexSchema.js\";',\n ];\n const moduleMap = Effect.fnUntraced(function* (directory: string) {\n const files = (yield* fs.readDirectory(directory, { recursive: true }))\n .filter(\n (file) =>\n /\\.[cm]?[jt]s$/.test(file) &&\n !file.endsWith(\".d.ts\") &&\n !file.split(path.sep).includes(\"_generated\") &&\n !file.includes(\".config.\"),\n )\n .sort();\n return `{ \"_generated/testing.ts\": () => Promise.resolve({}),\\n${files\n .map((file) => {\n const specifier = relative(path.join(directory, file));\n return `${quote(file.split(path.sep).join(\"/\"))}: () => import(${quote(specifier.replace(/\\.([cm]?)[jt]s$/, \".$1js\"))}),`;\n })\n .join(\"\\n\")}\\n}`;\n });\n const declarations: Array<string> = [];\n const identifiers = new Set([\"schema\", \"convexSchema\"]);\n const components: Array<string> = [];\n const httpMounts: Array<string> = [];\n const kits = new Map<string, string>();\n const visit = Effect.fnUntraced(function* (\n directory: string,\n prefix: string,\n kind: \"app\" | \"component\",\n parentHttpPrefix: string | undefined,\n registeredByKit: boolean,\n ): Effect.fn.Return<\n void,\n | PlatformError.PlatformError\n | BuildError\n | CodegenError.InvalidConvexConfigError\n | CodegenError.InvalidDeclarationError,\n FileSystem.FileSystem | Path.Path\n > {\n const config = path.join(directory, ConvexConfig.CONVEX_CONFIG_FILENAME);\n if (!(yield* fs.exists(config))) return;\n const installed = yield* ConvexConfig.discoverInstalledComponents(\n config,\n relative(config),\n kind,\n );\n for (const component of installed) {\n const name = prefix + component.name;\n const mount =\n prefix === \"\"\n ? App.mounts(app).find((declared) => declared.name === component.name)\n : undefined;\n // A bare definition belongs to another package. Its directory is read\n // here but never written out; tests reach it through `<package>/test`\n // or the kit its mount names.\n const fromPackage = !path.isAbsolute(component.componentDefinitionPath);\n const kitEntry =\n mount?.testing ??\n (fromPackage ? `${component.componentDefinitionPath}/test` : undefined);\n const resolved = fromPackage\n ? path.dirname(\n yield* ConvexConfig.resolveDefinition(\n `${component.componentDefinitionPath}/convex.config`,\n config,\n path,\n ).pipe(\n Effect.fromOption,\n Effect.mapError(\n () =>\n new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`,\n }),\n ),\n ),\n )\n : component.componentDefinitionPath;\n const localPrefix =\n prefix === \"\" ? mount?.httpPrefix : component.httpPrefix;\n const httpPrefix =\n parentHttpPrefix === undefined || localPrefix === undefined\n ? undefined\n : `${parentHttpPrefix.replace(/\\/+$/, \"\")}${localPrefix}`.replace(\n /\\/+$/,\n \"\",\n ) || \"/\";\n if (\n httpPrefix !== undefined &&\n ((yield* fs.exists(path.join(resolved, \"http.ts\"))) ||\n (yield* fs.exists(path.join(resolved, \"http.js\"))))\n ) {\n httpMounts.push(\n `{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`,\n );\n }\n // A kit's `register` installs the mount's own children, so below it the\n // walk only collects HTTP mounts.\n if (!registeredByKit) {\n const kitKey = kitEntry ?? resolved;\n let identifier = kits.get(kitKey);\n if (identifier === undefined) {\n const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, \"_\");\n const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n identifier = `${base}Kit`;\n let schemaIdentifier = `${base}Schema`;\n for (\n let n = 2;\n identifiers.has(identifier) || identifiers.has(schemaIdentifier);\n n++\n ) {\n identifier = `${base}Kit${n}`;\n schemaIdentifier = `${base}Schema${n}`;\n }\n identifiers.add(identifier);\n identifiers.add(schemaIdentifier);\n kits.set(kitKey, identifier);\n if (kitEntry === undefined) {\n imports.push(\n `import ${schemaIdentifier} from ${quote(relative(path.join(resolved, \"schema.js\")))};`,\n );\n declarations.push(\n `const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`,\n );\n } else {\n if (mount?.testing !== undefined) {\n yield* checkTestKit(\n mount.name,\n mount.testing,\n config,\n configDisplay,\n );\n } else if (Option.isNone(Bundler.resolveModule(kitEntry, config))) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `the component package ${quote(component.componentDefinitionPath)} has no ${quote(kitEntry)} export. Tests register a component from another package through that entry's \\`register(t, name)\\`.`,\n });\n }\n imports.push(`import * as ${identifier} from ${quote(kitEntry)};`);\n }\n }\n components.push(`${quote(name)}: ${identifier},`);\n }\n // A package's own `register` installs its children.\n if (!fromPackage) {\n yield* visit(\n resolved,\n `${name}/`,\n \"component\",\n httpPrefix,\n registeredByKit || kitEntry !== undefined,\n );\n }\n }\n });\n yield* visit(\n convexDirectory,\n \"\",\n (yield* ConvexDirectory.target).kind,\n \"\",\n false,\n );\n yield* writeFileStringAndLog(\n path.join(generated, \"testing.ts\"),\n [\n \"// Generated by `confect codegen`. Test-only; do not import in backend functions.\",\n ...imports,\n ...declarations,\n `export default { httpMounts: [${httpMounts.join(\",\")}], schema, convexSchema, modules: ${yield* moduleMap(convexDirectory)}, components: {${components.join(\"\\n\")}} };`,\n ].join(\"\\n\"),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,oBAAoB;AAE1B,MAAM,cAAc,OAAO,IACzB,gBAAgB,SACf,WAAW,OAAO,SAAS,WAC9B;AAEA,MAAM,sBAAsB,OAAO,IAAI,KAAK,OAAO,SACjD,KAAK,KAAK,mBAAmB,SAAS,CACxC;AACA,MAAM,wBAAwB,OAAO,IAAI,KAAK,OAAO,SACnD,KAAK,KAAK,mBAAmB,WAAW,CAC1C;AACA,MAAM,+BAA+B,OAAO,IAAI,KAAK,OAAO,SAC1D,KAAK,KAAK,mBAAmB,iBAAiB,CAChD;AACA,MAAM,oBAAoB,OAAO,IAAI,KAAK,OAAO,SAC/C,KAAK,KAAK,mBAAmB,OAAO,CACtC;AACA,MAAM,4BAA4B,OAAO,IAAI,KAAK,OAAO,SACvD,KAAK,KAAK,mBAAmB,eAAe,CAC9C;AACA,MAAM,2BAA2B,OAAO,IAAI,KAAK,OAAO,SACtD,KAAK,KAAK,mBAAmB,QAAQ,CACvC;AAEA,MAAM,eAAe,OAAO,IAAI,aAAa;CAC3C,MAAM,OAAO,OAAO,KAAK;CAEzB,OAAO;EACL;EACA;EACA;EACA;EACA,KAAK,KAAK,mBAAmB,wBAAwB;EACrD,KAAK,KAAK,mBAAmB,4BAA4B;EACzD,KAAK,KAAK,mBAAmB,SAAS;EACtC,KAAK,KAAK,mBAAmB,aAAa;EAG1C,KAAK,KAAK,mBAAmB,aAAa;CAC5C;AACF,CAAC;AAED,MAAa,UAAU,QAAQ,KAAK,WAAWA,aAC7C,OAAO,IAAI,a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CAAC;CACD,OAAO,MACL,iBACA,KACC,OAAO,gBAAgB,OAAA,CAAQ,MAChC,IACA,KACF;CACA,OAAO,sBACL,KAAK,KAAK,WAAW,YAAY,GACjC;EACE;EACA,GAAG;EACH,GAAG;EACH,iCAAiC,WAAW,KAAK,GAAG,EAAE,oCAAoC,OAAO,UAAU,eAAe,EAAE,iBAAiB,WAAW,KAAK,IAAI,EAAE;CACrK,CAAC,CAAC,KAAK,IAAI,CACb;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"codegen.mjs","names":["DirectoryOptions.flags","CodegenError.tapAndLog","DirectoryOptions.layer","FunctionModule.assertOwnedEntrypoints","TableModule.discover","TableModule.validate","GenerationSnapshot.fromLoadedLeaves","FunctionModule.generateFunctions","EntryPoint.planDeclarations","GenerationSnapshot.update","FunctionModule.applyFunctionPlan","GenerationSnapshot.diff","CodegenError.ComponentNodeGroupError","ConvexConfig.componentName","ConvexConfig.CONVEX_CONFIG_FILENAME","Bundler.bundle","CodegenError.CallbackPrefixError","CodegenError.InvalidConvexConfigError","templates.componentContract","templates.assembledSpec","templates.registeredFunctionsForGroup","FunctionPaths.make","TableModule.TABLES_DIRNAME","templates.id","templates.tableWrapper","templates.runtimeSchema","templates.convexSchema","templates.schema","templates.services","DocName.fromTableName","CodegenError.ConflictingDocNameError","templates.docs","templates.refs","ConvexConfig.discoverInstalledComponents","templates.components","ConvexConfig.typeImportPath","CodegenError.InvalidDeclarationError","Bundler.resolveModule","Bundler.exportNames","ConvexConfig.resolveDefinition"],"sources":["../../src/confect/codegen.ts"],"sourcesContent":["import { App, Callback, Env, type GroupSpec, Spec } from \"@confect/core\";\nimport * as Command from \"effect/cli/Command\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport type * as PlatformError from \"effect/PlatformError\";\nimport type { BuildError } from \"../BuildError.js\";\nimport { pipe } from \"effect/Function\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Record from \"effect/Record\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Bundler from \"../Bundler.js\";\nimport { fromBundlerError } from \"../BuildError.js\";\nimport * as CodegenError from \"../CodegenError.js\";\nimport { LegacySchemaFileError } from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as DocName from \"../DocName.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as FunctionModule from \"../FunctionModule.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport * as EntryPoint from \"../EntryPoint.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport {\n implPathForSpec,\n loadAll,\n registeredFunctionsRelativePath,\n validateAllImpls,\n withImplFiles,\n type LeafModule,\n type LoadedLeafModule,\n} from \"../LeafModule.js\";\nimport {\n logFileAdded,\n logFileModified,\n logFileRemoved,\n logPending,\n logSuccess,\n logWarn,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport { assemblyNodesFromLeaves } from \"../SpecAssemblyNode.js\";\nimport * as TableModule from \"../TableModule.js\";\nimport * as templates from \"../templates.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n removePathIfExists,\n toModuleImportPath,\n touchConvexSchema,\n writeFileStringAndLog,\n} from \"../utils.js\";\nimport {\n syncManifestSections,\n readPrevious,\n syncDeclaration,\n syncDeclaredHttp,\n} from \"./declaration.js\";\n\nconst GENERATED_DIRNAME = \"_generated\";\n\nconst isComponent = Effect.map(\n ConvexDirectory.target,\n (target) => target.kind === \"component\",\n);\n\nconst GENERATED_SPEC_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"spec.ts\"),\n);\nconst GENERATED_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"schema.ts\"),\n);\nconst GENERATED_CONVEX_SCHEMA_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"convexSchema.ts\"),\n);\nconst GENERATED_ID_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"id.ts\"),\n);\nconst GENERATED_COMPONENTS_PATH = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"components.ts\"),\n);\nconst GENERATED_TABLES_DIRNAME = Effect.map(Path.Path, (path) =>\n path.join(GENERATED_DIRNAME, \"tables\"),\n);\n\nconst LEGACY_PATHS = Effect.gen(function* () {\n const path = yield* Path.Path;\n\n return [\n \"spec.ts\",\n \"nodeSpec.ts\",\n \"impl.ts\",\n \"nodeImpl.ts\",\n path.join(GENERATED_DIRNAME, \"registeredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeRegisteredFunctions.ts\"),\n path.join(GENERATED_DIRNAME, \"impl.ts\"),\n path.join(GENERATED_DIRNAME, \"nodeImpl.ts\"),\n // `_generated/nodeSpec.ts` is not part of the generated output (all groups\n // live in `_generated/spec.ts`); delete any copy left by an older version.\n path.join(GENERATED_DIRNAME, \"nodeSpec.ts\"),\n ];\n});\n\nexport const codegen = Command.make(\"codegen\", DirectoryOptions.flags, () =>\n Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n yield* codegenHandler.pipe(\n Effect.asVoid,\n Effect.tap(() => logSuccess(\"Generated files are up-to-date\")),\n CodegenError.tapAndLog,\n );\n }),\n).pipe(\n Command.provide(DirectoryOptions.layer),\n Command.withDescription(\n \"Generate `confect/_generated` files and the contents of the `convex` directory (except `tsconfig.json`, and `convex.config.ts` unless `confect/app.ts` declares the backend)\",\n ),\n);\n\nconst runCodegen = Effect.gen(function* () {\n yield* FunctionModule.assertOwnedEntrypoints;\n yield* validateComponentConfiguration;\n yield* generateConfectGeneratedDirectory;\n // A declared backend's `convex.config.ts` and manifest come first: the\n // components registry below reads the config, and nothing may validate\n // against a manifest the current declaration did not produce.\n const previousManifest = yield* readPrevious;\n const { app: declared, digest } = yield* syncDeclaration(previousManifest);\n // Reject a legacy `confect/schema.ts` up front so the user-facing\n // migration message surfaces before any bundler error from impl\n // validation (each impl imports `_generated/schema.ts`).\n yield* rejectLegacySchemaFile;\n // List `confect/tables/*.ts` (filename-only—no bundling yet) so the\n // `_generated/id.ts` constructor can be emitted *before* we bundle any\n // user-authored table module. Tables import from `_generated/id.ts` for\n // cross-table id refs, so it must exist on disk first.\n const tableModules = yield* TableModule.discover;\n yield* warnIfNoTables(tableModules);\n yield* generateIdConstructor(tableModules);\n // Tables and specs can use bound component IDs and schemas, so their\n // imports need the registry even on a project's first codegen run.\n yield* generateComponents;\n yield* validateCallbackPrefixes(declared);\n // Now that `_generated/id.ts` is on disk, bundle each table module and\n // check its default export is an `UnnamedTable`. Surface diagnostics\n // here (rather than later) so they appear before impl-validation noise.\n yield* TableModule.validate(tableModules);\n yield* validateNoDocNameCollisions(tableModules);\n yield* generateTableWrappers(tableModules);\n yield* removeObsoleteTableWrappers(tableModules);\n yield* generateRuntimeSchema(tableModules);\n const leaves = yield* loadAll;\n yield* rejectComponentNodeGroups(leaves);\n yield* syncManifestSections(leaves, previousManifest, digest);\n yield* removeLegacyFiles;\n const snapshot = yield* Effect.fromResult(\n GenerationSnapshot.fromLoadedLeaves(leaves),\n );\n yield* generateAssembledSpecs(leaves);\n // `_generated/api.ts`/`nodeApi.ts` are no longer imported by generated or\n // impl code (impls take the database schema from `_generated/schema`\n // directly), so remove any copies left over from earlier versions before\n // impl validation runs.\n yield* Effect.all(\n [\n removeGeneratedApi,\n generateRefs,\n generateComponentContract(tableModules),\n removeGeneratedNodeApi,\n generateDocs(tableModules),\n generateServices,\n generateConvexSchema(tableModules),\n ],\n { concurrency: \"unbounded\" },\n );\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n yield* generateGroupRegisteredFunctions(leaves, required);\n yield* removeObsoleteRegisteredFunctions(leaves);\n const [functionPaths] = yield* Effect.all(\n [\n FunctionModule.generateFunctions(snapshot),\n generateConvexSchemaReexport,\n logGenerated(\n Option.match(declared, {\n onNone: () => generateHttp,\n onSome: syncDeclaredHttp,\n }),\n ),\n logGenerated(generateCrons),\n Option.isNone(declared)\n ? logGenerated(generateAuthConfig)\n : Effect.succeedNone,\n ],\n { concurrency: \"unbounded\" },\n );\n if (Option.isSome(declared)) yield* generateTesting(declared.value);\n return {\n functionPaths,\n snapshot,\n };\n});\n\nexport const generateWithSnapshot = runCodegen.pipe(\n Effect.withSpan(\"Cli.codegen\"),\n);\n\nexport const makeCodegenHandler = (\n duringRestore?: Effect.Effect<void, never, Scope.Scope>,\n) =>\n preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(\n Effect.tap(() => touchConvexSchema),\n Effect.map(({ functionPaths }) => ({ functionPaths })),\n );\n\nexport const codegenHandler = makeCodegenHandler();\n\nexport const updateDeclarations = Effect.fn(\"Cli.updateDeclarations\")(\n function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n affectedImpls: ReadonlyArray<ImplModulePath>,\n ) {\n const previousManifest = yield* readPrevious;\n const path = yield* Path.Path;\n const { paths, tables } = EntryPoint.planDeclarations(\n declarations,\n affectedImpls,\n path,\n );\n yield* TableModule.validate(tables);\n return yield* withImplFiles(paths, (leaves) =>\n Effect.gen(function* () {\n yield* rejectComponentNodeGroups(leaves);\n const next = yield* Effect.fromResult(\n GenerationSnapshot.update(snapshot, leaves),\n );\n const { app: declared, digest } =\n yield* syncDeclaration(previousManifest);\n if (Option.isSome(declared))\n yield* syncManifestSections(yield* loadAll, previousManifest, digest);\n const required = Option.isSome(declared)\n ? declared.value.requiresMiddleware\n : [];\n yield* validateAllImpls(leaves, required);\n yield* generateGroupRegisteredFunctions(leaves, required);\n yield* FunctionModule.applyFunctionPlan(\n GenerationSnapshot.diff(snapshot, next),\n );\n return next;\n }),\n );\n },\n);\n\n// Convex components cannot run Node.js functions, at any nesting depth.\nconst validateComponentGroupRuntime = (\n group: GroupSpec.AnyWithProps,\n groupPath: string,\n specPath: string,\n): Result.Result<void, CodegenError.ComponentNodeGroupError> =>\n Result.gen(function* () {\n if (group.runtime === \"Node\") {\n return yield* Result.fail(\n new CodegenError.ComponentNodeGroupError({ specPath, groupPath }),\n );\n }\n for (const [name, child] of Object.entries(group.groups)) {\n yield* validateComponentGroupRuntime(\n child,\n `${groupPath}.${name}`,\n specPath,\n );\n }\n });\n\nconst rejectComponentNodeGroups = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n) {\n if ((yield* ConvexDirectory.target).kind === \"app\") return;\n yield* Effect.forEach(leaves, (leaf) =>\n Effect.fromResult(\n validateComponentGroupRuntime(\n leaf.spec,\n leaf.groupPathDot,\n leaf.relativePath,\n ),\n ),\n );\n});\n\nconst validateCallbackPrefixes = Effect.fnUntraced(function* (\n declared: Option.Option<App.Any>,\n) {\n if ((yield* ConvexDirectory.target).kind !== \"component\") return;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const callbacksPath = path.join(yield* ConfectDirectory.get, \"callbacks.ts\");\n if (!(yield* fs.exists(callbacksPath))) return;\n const name = Option.isSome(declared)\n ? Env.name(App.env(declared.value))\n : yield* ConvexConfig.componentName(\n path.join(\n yield* ConvexDirectory.get,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n ),\n );\n const { module } = yield* Bundler.bundle(callbacksPath).pipe(\n Effect.mapError((error) => fromBundlerError(\"confect/callbacks.ts\", error)),\n );\n for (const contract of Object.values(module)) {\n if (Callback.isContract(contract) && !contract.id.startsWith(`${name}/`)) {\n return yield* new CodegenError.CallbackPrefixError({\n declarationPath: \"confect/callbacks.ts\",\n contractId: contract.id,\n componentName: name,\n });\n }\n }\n});\n\nconst validateComponentConfiguration = Effect.gen(function* () {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const authPath = path.join(confectDirectory, \"auth.ts\");\n if (yield* fs.exists(authPath)) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: authPath,\n reason:\n \"Components cannot configure application authentication. Pass identity explicitly through function arguments.\",\n });\n }\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateComponentContract = Effect.fnUntraced(function* (\n tables: ReadonlyArray<TableModule.TableModule>,\n) {\n return yield* Match.value((yield* ConvexDirectory.target).kind).pipe(\n Match.when(\"app\", () => Effect.void),\n Match.when(\"component\", () =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const directory = yield* ConfectDirectory.get;\n const contents = yield* templates.componentContract({\n tableNames: Array.map(tables, (table) => table.tableName),\n });\n yield* writeFileStringAndLog(\n path.join(directory, GENERATED_DIRNAME, \"component.ts\"),\n contents,\n );\n }),\n ),\n Match.exhaustive,\n );\n});\n\nconst generateConfectGeneratedDirectory = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n if (!(yield* fs.exists(path.join(confectDirectory, \"_generated\")))) {\n yield* fs.makeDirectory(path.join(confectDirectory, \"_generated\"), {\n recursive: true,\n });\n yield* logFileAdded(path.join(confectDirectory, \"_generated\") + \"/\");\n }\n});\n\nconst removeLegacyFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPaths = yield* LEGACY_PATHS;\n\n yield* Effect.forEach(\n legacyPaths,\n Effect.fnUntraced(function* (relativePath: string) {\n const absolutePath = path.join(confectDirectory, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n }),\n );\n});\n\nconst generateAssembledSpecs = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n // A single assembled spec holds every group regardless of runtime—a Node\n // group's `makeNode()` lives in its imported leaf spec, so the assembled\n // file is runtime-agnostic. Always emit it (even empty) so downstream\n // readers (`loadGeneratedSpec`, `generateRefs`) always find a spec module.\n const nodes = assemblyNodesFromLeaves(leaves);\n const specContents = yield* templates.assembledSpec({ nodes });\n yield* writeFileStringAndLog(\n path.join(confectDirectory, generatedSpecPath),\n specContents,\n );\n});\n\nconst generateGroupRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n required: ReadonlyArray<{ readonly key: string }> = [],\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const confectDirectory = yield* ConfectDirectory.get;\n const runtimePath = path.join(confectDirectory, \"runtime.ts\");\n const hasRuntime = yield* fs.exists(runtimePath);\n\n yield* Effect.forEach(\n leaves,\n Effect.fnUntraced(function* (leaf: LoadedLeafModule) {\n const registryRelativePath = yield* registeredFunctionsRelativePath(leaf);\n const registryPath = path.join(\n confectDirectory,\n \"_generated\",\n registryRelativePath,\n );\n const registryDir = path.dirname(registryPath);\n if (!(yield* fs.exists(registryDir))) {\n yield* fs.makeDirectory(registryDir, { recursive: true });\n }\n\n const implRelativePath = yield* implPathForSpec(leaf.relativePath);\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n );\n // The group's own leaf spec (sibling of its impl), referenced\n // type-only by the registry to shape its returned record.\n const specImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, leaf.relativePath),\n ),\n );\n const implImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(registryPath),\n path.join(confectDirectory, implRelativePath),\n ),\n );\n\n const contents = yield* templates.registeredFunctionsForGroup({\n spec: leaf.spec,\n required,\n groupPath: leaf.groupPathDot,\n schemaImportPath,\n specImportPath,\n implImportPath,\n runtimeImportPath: hasRuntime\n ? yield* toModuleImportPath(path.relative(registryDir, runtimePath))\n : undefined,\n });\n\n yield* writeFileStringAndLog(registryPath, contents);\n }),\n );\n});\n\nconst removeObsoleteRegisteredFunctions = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<LeafModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const registryRoot = path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n );\n\n if (!(yield* fs.exists(registryRoot))) {\n return;\n }\n\n const expected = new Set(\n yield* Effect.forEach(leaves, (leaf) =>\n registeredFunctionsRelativePath(leaf),\n ),\n );\n\n const existing = yield* fs.readDirectory(registryRoot, { recursive: true });\n yield* Effect.forEach(existing, (relativePath) => {\n if (path.extname(relativePath) !== \".ts\") {\n return Effect.void;\n }\n const normalized = path.join(\"registeredFunctions\", relativePath);\n if (!expected.has(normalized)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(registryRoot, relativePath);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst getGeneratedSpecPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n return path.join(confectDirectory, generatedSpecPath);\n});\n\nconst loadGeneratedSpec = Effect.gen(function* () {\n const specPath = yield* getGeneratedSpecPath;\n const { module: specModule } = yield* Bundler.bundle(specPath);\n const spec = specModule.default;\n\n if (!Spec.isSpec(spec)) {\n return yield* Effect.die(\n new Error(\"_generated/spec.ts does not export a valid Spec\"),\n );\n }\n\n return spec;\n});\n\nconst emptyFunctionPaths = FunctionPaths.FunctionPaths.make(HashSet.empty());\n\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const specPath = yield* getGeneratedSpecPath;\n\n if (!(yield* fs.exists(specPath))) {\n return emptyFunctionPaths;\n }\n\n const specResult = yield* loadGeneratedSpec.pipe(Effect.result);\n\n return Result.match(specResult, {\n onFailure: () => emptyFunctionPaths,\n onSuccess: (spec) => FunctionPaths.make(spec),\n });\n});\n\n/**\n * Remove a now-obsolete `_generated/<name>.ts` if present (and log it), for\n * projects upgrading from a version that still emitted it.\n */\nconst removeObsoleteGeneratedFile = Effect.fnUntraced(function* (\n fileName: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const filePath = path.join(confectDirectory, \"_generated\", fileName);\n\n if (yield* fs.exists(filePath)) {\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n }\n});\n\n// `_generated/api.ts` is no longer imported by generated or impl code: impls\n// take the database schema (`_generated/schema`) directly, and per-group\n// registries reference the spec type-only. Remove any stale copy.\nconst removeGeneratedApi = removeObsoleteGeneratedFile(\"api.ts\");\n\n// `_generated/nodeApi.ts` is obsolete for the same reason.\nconst removeGeneratedNodeApi = removeObsoleteGeneratedFile(\"nodeApi.ts\");\n\n/**\n * The user-authored `confect/schema.ts` is no longer supported: codegen now\n * owns both `_generated/schema.ts` (runtime) and `_generated/convexSchema.ts`\n * (deploy), derived from a single scan of `confect/tables/*.ts`. Detect a stray\n * file and fail with a clear migration message—leaving it in place would\n * silently shadow the codegen-owned\n * `_generated/schema.ts`/`_generated/convexSchema.ts`.\n */\nconst rejectLegacySchemaFile = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const legacyPath = path.join(confectDirectory, \"schema.ts\");\n\n if (yield* fs.exists(legacyPath)) {\n return yield* new LegacySchemaFileError({ schemaPath: \"schema.ts\" });\n }\n});\n\n/**\n * Surface a yellow `⚠` warning when codegen sees no tables—either the\n * `confect/tables/` directory is missing or it contains no `.ts` files.\n * Generation still succeeds (emitting an empty `DatabaseSchema` and\n * `defineSchema({})`), since action-only/table-free Confect backends are\n * legal—but the warning catches the much more common case of a typoed directory\n * or files placed under the wrong root.\n */\nconst warnIfNoTables = (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) =>\n tableModules.length === 0\n ? logWarn(\n `No tables discovered in \\`confect/${TableModule.TABLES_DIRNAME}/\\`. ` +\n `Generating an empty schema; add a \\`Table.make(...)\\` module under that ` +\n `directory unless this backend is intentionally tables-free.`,\n )\n : Effect.void;\n\nconst tableModuleBindings = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n generatedFilePath: string,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDir = path.dirname(generatedFilePath);\n\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n\n return yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperAbsolutePath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const importPath = yield* toModuleImportPath(\n path.relative(generatedDir, wrapperAbsolutePath),\n );\n return {\n importPath,\n tableName: tableModule.tableName,\n };\n }),\n );\n});\n\nconst generateIdConstructor = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedIdPath = yield* GENERATED_ID_PATH;\n const idPath = path.join(confectDirectory, generatedIdPath);\n\n const tableNames = Array.map(\n tableModules,\n (tableModule) => tableModule.tableName,\n );\n const contents = yield* Match.value(yield* ConvexDirectory.target).pipe(\n Match.when({ kind: \"app\" }, () => templates.id({ tableNames })),\n Match.when({ kind: \"component\" }, ({ scope }) =>\n templates.id({ tableNames, scope }),\n ),\n Match.exhaustive,\n );\n\n yield* writeFileStringAndLog(idPath, contents);\n});\n\nconst generateTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n yield* fs.makeDirectory(wrappersDir, { recursive: true });\n }\n\n yield* Effect.forEach(\n tableModules,\n Effect.fnUntraced(function* (tableModule: TableModule.TableModule) {\n const wrapperPath = path.join(\n confectDirectory,\n generatedTablesDirname,\n `${tableModule.tableName}.ts`,\n );\n const unnamedAbsolutePath = path.join(\n confectDirectory,\n tableModule.relativePath,\n );\n const unnamedImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(wrapperPath), unnamedAbsolutePath),\n );\n const contents = yield* templates.tableWrapper({\n tableName: tableModule.tableName,\n unnamedImportPath,\n component: yield* isComponent,\n });\n yield* writeFileStringAndLog(wrapperPath, contents);\n }),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * Remove any stale `_generated/tables/*.ts` wrapper whose source table has been\n * deleted or renamed. Mirrors `removeObsoleteRegisteredFunctions` for the\n * wrapper directory.\n */\nconst removeObsoleteTableWrappers = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedTablesDirname = yield* GENERATED_TABLES_DIRNAME;\n const wrappersDir = path.join(confectDirectory, generatedTablesDirname);\n\n if (!(yield* fs.exists(wrappersDir))) {\n return;\n }\n\n const expected = new Set(\n Array.map(tableModules, (tableModule) => `${tableModule.tableName}.ts`),\n );\n const existing = yield* fs.readDirectory(wrappersDir, { recursive: true });\n yield* Effect.forEach(existing, (entry) => {\n if (path.extname(entry) !== \".ts\") {\n return Effect.void;\n }\n if (!expected.has(entry)) {\n return Effect.gen(function* () {\n const absolutePath = path.join(wrappersDir, entry);\n if (yield* fs.exists(absolutePath)) {\n yield* removePathIfExists(absolutePath);\n yield* logFileRemoved(absolutePath);\n }\n });\n }\n return Effect.void;\n });\n});\n\nconst generateRuntimeSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaPath = path.join(confectDirectory, generatedSchemaPath);\n\n const bindings = yield* tableModuleBindings(tableModules, schemaPath);\n const contents = yield* templates.runtimeSchema({\n tableModules: bindings,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(schemaPath, contents);\n});\n\nconst generateConvexSchema = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedConvexSchemaPath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n const convexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaPath,\n );\n\n const bindings = yield* tableModuleBindings(tableModules, convexSchemaPath);\n const contents = yield* templates.convexSchema({ tableModules: bindings });\n\n yield* writeFileStringAndLog(convexSchemaPath, contents);\n});\n\nconst generateConvexSchemaReexport = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generatedConvexSchemaRelativePath = yield* GENERATED_CONVEX_SCHEMA_PATH;\n\n const convexSchemaPath = path.join(convexDirectory, \"schema.ts\");\n const generatedConvexSchemaPath = path.join(\n confectDirectory,\n generatedConvexSchemaRelativePath,\n );\n\n const convexSchemaImportPath = yield* toModuleImportPath(\n path.relative(path.dirname(convexSchemaPath), generatedConvexSchemaPath),\n );\n\n const schemaContents = yield* templates.schema({\n convexSchemaImportPath,\n });\n\n yield* writeFileStringAndLog(convexSchemaPath, schemaContents);\n});\n\nconst generateServices = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const servicesPath = path.join(confectGeneratedDirectory, \"services.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(servicesPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const servicesContentsString = yield* templates.services({\n schemaImportPath,\n component: yield* isComponent,\n });\n\n yield* writeFileStringAndLog(servicesPath, servicesContentsString);\n});\n\n/**\n * Two tables whose names fold to the same PascalCase document type name (e.g.\n * `user_profiles` and `userProfiles` → `UserProfilesDoc`) would emit duplicate\n * interfaces in `_generated/docs.ts`. Catch that up front with a clear error\n * rather than letting `tsc` report a duplicate-identifier later.\n */\nconst validateNoDocNameCollisions = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const collisions = pipe(\n tableModules,\n Array.groupBy((tableModule) =>\n DocName.fromTableName(tableModule.tableName),\n ),\n Record.toEntries,\n Array.filter(([, group]) => group.length > 1),\n Array.map(([docName, group]) => ({\n docName,\n tableNames: Array.map(group, (tableModule) => tableModule.tableName),\n })),\n );\n\n if (Array.isReadonlyArrayNonEmpty(collisions)) {\n return yield* new CodegenError.ConflictingDocNameError({ collisions });\n }\n});\n\nconst generateDocs = Effect.fnUntraced(function* (\n tableModules: ReadonlyArray<TableModule.TableModule>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n\n const docsPath = path.join(confectGeneratedDirectory, \"docs.ts\");\n const generatedSchemaPath = yield* GENERATED_SCHEMA_PATH;\n const schemaImportPath = yield* toModuleImportPath(\n path.relative(\n path.dirname(docsPath),\n path.join(confectDirectory, generatedSchemaPath),\n ),\n );\n\n const docsContentsString = yield* templates.docs({\n schemaImportPath,\n tables: Array.map(tableModules, (tableModule) => ({\n tableName: tableModule.tableName,\n docName: DocName.fromTableName(tableModule.tableName),\n })),\n });\n\n yield* writeFileStringAndLog(docsPath, docsContentsString);\n});\n\nconst generateRefs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const confectGeneratedDirectory = path.join(confectDirectory, \"_generated\");\n const refsPath = path.join(confectGeneratedDirectory, \"refs.ts\");\n const refsDir = path.dirname(refsPath);\n const generatedSpecPath = yield* GENERATED_SPEC_PATH;\n\n const specImportPath = yield* toModuleImportPath(\n path.relative(refsDir, path.join(confectDirectory, generatedSpecPath)),\n );\n\n const refsContents = yield* templates.refs({ specImportPath });\n\n yield* writeFileStringAndLog(refsPath, refsContents);\n});\n\n/**\n * Generate `confect/_generated/components.ts`—the typed registry of Convex\n * components installed in `convex/convex.config.ts` (see\n * {@link templates.components}). The file is emitted even when there is no\n * `convex.config.ts` (as an empty registry) so the import surface stays stable.\n * It must exist before loading tables and specs because they may import bound\n * component IDs and schemas.\n */\nexport const generateComponents = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n\n const confectGeneratedDirectory = path.join(\n confectDirectory,\n GENERATED_DIRNAME,\n );\n const generatedComponentsPath = yield* GENERATED_COMPONENTS_PATH;\n const componentsPath = path.join(confectDirectory, generatedComponentsPath);\n\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n\n const installedComponents = (yield* fs.exists(convexConfigPath))\n ? yield* ConvexConfig.discoverInstalledComponents(\n convexConfigPath,\n path.relative(projectRoot, convexConfigPath),\n (yield* ConvexDirectory.target).kind,\n )\n : [];\n\n const contents = yield* templates.components({\n components: Array.map(\n installedComponents,\n ({ name, componentDefinitionPath }) => ({\n name,\n typeImportPath: ConvexConfig.typeImportPath(\n path,\n componentDefinitionPath,\n confectGeneratedDirectory,\n ),\n }),\n ),\n });\n\n yield* writeFileStringAndLog(componentsPath, contents);\n});\n\nconst logGenerated = <E, R>(\n effect: Effect.Effect<\n Option.Option<{\n readonly change: \"Added\" | \"Modified\" | \"Unchanged\";\n readonly convexFilePath: string;\n }>,\n E,\n R\n >,\n) =>\n effect.pipe(\n Effect.tap(\n Option.match({\n onNone: () => Effect.void,\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(convexFilePath)),\n Match.when(\"Modified\", () => logFileModified(convexFilePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n ),\n }),\n ),\n );\n\n/**\n * Test-only imports never enter the runtime schema or function wrappers.\n */\nconst quote = (value: string) => JSON.stringify(value);\n\n/**\n * A mount's `testing` kit must be a package specifier, so the generated\n * registry holds no machine-specific path, and must export `register`. A kit\n * whose exports cannot be listed without running it passes here, and\n * `TestConfect.layer` names the mount if it has no `register`.\n */\nconst checkTestKit = Effect.fnUntraced(function* (\n mount: string,\n specifier: string,\n config: string,\n configDisplay: string,\n) {\n const path = yield* Path.Path;\n const invalid = (problem: string) =>\n new CodegenError.InvalidDeclarationError({\n declarationPath: \"confect/app.ts\",\n reason: `the mount ${quote(mount)} names the test kit ${quote(specifier)}${problem}`,\n });\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) {\n return yield* invalid(\n '; name it by a package specifier, such as \"<package>/testing\".',\n );\n }\n const resolved = Bundler.resolveModule(specifier, config);\n if (Option.isNone(resolved)) {\n return yield* invalid(`, which does not resolve from ${configDisplay}.`);\n }\n const exports = yield* Bundler.exportNames(resolved.value).pipe(\n Effect.mapError((error) => fromBundlerError(specifier, error)),\n );\n if (Option.isSome(exports) && !exports.value.includes(\"register\")) {\n return yield* invalid(\", which does not export `register(t, name)`.\");\n }\n});\n\nconst generateTesting = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const convexDirectory = yield* ConvexDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const configDisplay = path\n .relative(\n yield* ProjectRoot.get,\n path.join(convexDirectory, ConvexConfig.CONVEX_CONFIG_FILENAME),\n )\n .split(path.sep)\n .join(\"/\");\n const relative = (file: string) => {\n const value = path.relative(generated, file).split(path.sep).join(\"/\");\n return value.startsWith(\".\") ? value : `./${value}`;\n };\n const imports = [\n 'import schema from \"./schema.js\";',\n 'import convexSchema from \"./convexSchema.js\";',\n ];\n const moduleMap = Effect.fnUntraced(function* (directory: string) {\n const files = (yield* fs.readDirectory(directory, { recursive: true }))\n .filter(\n (file) =>\n /\\.[cm]?[jt]s$/.test(file) &&\n !file.endsWith(\".d.ts\") &&\n !file.split(path.sep).includes(\"_generated\") &&\n !file.includes(\".config.\"),\n )\n .sort();\n return `{ \"_generated/testing.ts\": () => Promise.resolve({}),\\n${files\n .map((file) => {\n const specifier = relative(path.join(directory, file));\n return `${quote(file.split(path.sep).join(\"/\"))}: () => import(${quote(specifier.replace(/\\.([cm]?)[jt]s$/, \".$1js\"))}),`;\n })\n .join(\"\\n\")}\\n}`;\n });\n const declarations: Array<string> = [];\n const identifiers = new Set([\"schema\", \"convexSchema\"]);\n const components: Array<string> = [];\n const httpMounts: Array<string> = [];\n const kits = new Map<string, string>();\n const visit = Effect.fnUntraced(function* (\n directory: string,\n prefix: string,\n kind: \"app\" | \"component\",\n parentHttpPrefix: string | undefined,\n registeredByKit: boolean,\n ): Effect.fn.Return<\n void,\n | PlatformError.PlatformError\n | BuildError\n | CodegenError.InvalidConvexConfigError\n | CodegenError.InvalidDeclarationError,\n FileSystem.FileSystem | Path.Path\n > {\n const config = path.join(directory, ConvexConfig.CONVEX_CONFIG_FILENAME);\n if (!(yield* fs.exists(config))) return;\n const installed = yield* ConvexConfig.discoverInstalledComponents(\n config,\n relative(config),\n kind,\n );\n for (const component of installed) {\n const name = prefix + component.name;\n const mount =\n prefix === \"\"\n ? App.mounts(app).find((declared) => declared.name === component.name)\n : undefined;\n // A bare definition belongs to another package. Its directory is read\n // here but never written out; tests reach it through `<package>/test`\n // or the kit its mount names.\n const fromPackage = !path.isAbsolute(component.componentDefinitionPath);\n const kitEntry =\n mount?.testing ??\n (fromPackage ? `${component.componentDefinitionPath}/test` : undefined);\n const resolved = fromPackage\n ? path.dirname(\n yield* ConvexConfig.resolveDefinition(\n `${component.componentDefinitionPath}/convex.config`,\n config,\n path,\n ).pipe(\n Effect.fromOption,\n Effect.mapError(\n () =>\n new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`,\n }),\n ),\n ),\n )\n : component.componentDefinitionPath;\n const localPrefix =\n prefix === \"\" ? mount?.httpPrefix : component.httpPrefix;\n const httpPrefix =\n parentHttpPrefix === undefined || localPrefix === undefined\n ? undefined\n : `${parentHttpPrefix.replace(/\\/+$/, \"\")}${localPrefix}`.replace(\n /\\/+$/,\n \"\",\n ) || \"/\";\n if (\n httpPrefix !== undefined &&\n ((yield* fs.exists(path.join(resolved, \"http.ts\"))) ||\n (yield* fs.exists(path.join(resolved, \"http.js\"))))\n ) {\n httpMounts.push(\n `{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`,\n );\n }\n // A kit's `register` installs the mount's own children, so below it the\n // walk only collects HTTP mounts.\n if (!registeredByKit) {\n const kitKey = kitEntry ?? resolved;\n let identifier = kits.get(kitKey);\n if (identifier === undefined) {\n const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, \"_\");\n const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n identifier = `${base}Kit`;\n let schemaIdentifier = `${base}Schema`;\n for (\n let n = 2;\n identifiers.has(identifier) || identifiers.has(schemaIdentifier);\n n++\n ) {\n identifier = `${base}Kit${n}`;\n schemaIdentifier = `${base}Schema${n}`;\n }\n identifiers.add(identifier);\n identifiers.add(schemaIdentifier);\n kits.set(kitKey, identifier);\n if (kitEntry === undefined) {\n imports.push(\n `import ${schemaIdentifier} from ${quote(relative(path.join(resolved, \"schema.js\")))};`,\n );\n declarations.push(\n `const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`,\n );\n } else {\n if (mount?.testing !== undefined) {\n yield* checkTestKit(\n mount.name,\n mount.testing,\n config,\n configDisplay,\n );\n } else if (Option.isNone(Bundler.resolveModule(kitEntry, config))) {\n return yield* new CodegenError.InvalidConvexConfigError({\n configPath: relative(config),\n reason: `the component package ${quote(component.componentDefinitionPath)} has no ${quote(kitEntry)} export. Tests register a component from another package through that entry's \\`register(t, name)\\`.`,\n });\n }\n imports.push(`import * as ${identifier} from ${quote(kitEntry)};`);\n }\n }\n components.push(`${quote(name)}: ${identifier},`);\n }\n // A package's own `register` installs its children.\n if (!fromPackage) {\n yield* visit(\n resolved,\n `${name}/`,\n \"component\",\n httpPrefix,\n registeredByKit || kitEntry !== undefined,\n );\n }\n }\n });\n yield* visit(\n convexDirectory,\n \"\",\n (yield* ConvexDirectory.target).kind,\n \"\",\n false,\n );\n yield* writeFileStringAndLog(\n path.join(generated, \"testing.ts\"),\n [\n \"// Generated by `confect codegen`. Test-only; do not import in backend functions.\",\n ...imports,\n ...declarations,\n `export default { httpMounts: [${httpMounts.join(\",\")}], schema, convexSchema, modules: ${yield* moduleMap(convexDirectory)}, components: {${components.join(\"\\n\")}} };`,\n ].join(\"\\n\"),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAM,oBAAoB;AAE1B,MAAM,cA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ACL,KAAK,KAAK,WAAW,YAAY,GACjC;EACE;EACA,GAAG;EACH,GAAG;EACH,iCAAiC,WAAW,KAAK,GAAG,EAAE,oCAAoC,OAAO,UAAU,eAAe,EAAE,iBAAiB,WAAW,KAAK,IAAI,EAAE;CACrK,CAAC,CAAC,KAAK,IAAI,CACb;AACF,CAAC"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { fromBundlerError } from "../BuildError.mjs";
|
|
2
2
|
import { ProjectRoot } from "../ProjectRoot.mjs";
|
|
3
|
-
import { logFileRemoved } from "../log.mjs";
|
|
3
|
+
import { logFileRemoved, logWarn } from "../log.mjs";
|
|
4
4
|
import { bundle, resolveModule } from "../Bundler.mjs";
|
|
5
|
-
import { DeclarationKindMismatchError, HandWrittenConvexFileError, InvalidDeclarationError } from "../CodegenError.mjs";
|
|
5
|
+
import { DeclarationKindMismatchError, HandWrittenConvexFileError, InvalidDeclarationError, logCodegenError } from "../CodegenError.mjs";
|
|
6
6
|
import { ConvexDirectory } from "../ConvexDirectory.mjs";
|
|
7
7
|
import { ConfectDirectory } from "../ConfectDirectory.mjs";
|
|
8
8
|
import { authConfig, declaredHttp, http } from "../templates.mjs";
|
|
9
9
|
import { removePathIfExists, toModuleImportPath, toPosixPath, writeFileString, writeFileStringAndLog } from "../utils.mjs";
|
|
10
10
|
import { CONVEX_CONFIG_FILENAME, componentConfigPlugin, componentImportOf } from "../ConvexConfig.mjs";
|
|
11
|
-
import { authConfig as authConfig$1, authProviders, convexConfig, digest, fileOf, isGenerated, manifest, parse } from "../Declaration.mjs";
|
|
11
|
+
import { authConfig as authConfig$1, authProviders, convexConfig, digest, fileOf, isGenerated, manifest, parse, renderManifest } from "../Declaration.mjs";
|
|
12
|
+
import { check, collect, sections } from "../ManifestSections.mjs";
|
|
12
13
|
import * as Effect from "effect/Effect";
|
|
13
14
|
import { App, Http } from "@confect/core";
|
|
14
15
|
import * as FileSystem from "effect/FileSystem";
|
|
@@ -117,13 +118,46 @@ const removeGenerated = Effect.fnUntraced(function* (filePath, legacy) {
|
|
|
117
118
|
const removeManifest = Effect.gen(function* () {
|
|
118
119
|
yield* removeGenerated(yield* manifestPath, []);
|
|
119
120
|
});
|
|
121
|
+
const readManifest = Effect.gen(function* () {
|
|
122
|
+
const fs = yield* FileSystem.FileSystem;
|
|
123
|
+
const file = yield* manifestPath;
|
|
124
|
+
if (!(yield* fs.exists(file))) return {};
|
|
125
|
+
const data = (yield* bundle(file).pipe(Effect.mapError((error) => fromBundlerError("confect/_generated/manifest.ts", error)))).module.default;
|
|
126
|
+
return Predicate.isObject(data) ? data : {};
|
|
127
|
+
});
|
|
128
|
+
const readPrevious = readManifest.pipe(Effect.orElseSucceed(() => ({})));
|
|
129
|
+
const sectionDigest = (base, sections) => Object.keys(sections).length === 0 ? base : digest({
|
|
130
|
+
files: [["declaration", base]],
|
|
131
|
+
versions: [],
|
|
132
|
+
sections
|
|
133
|
+
});
|
|
134
|
+
const syncManifestSections = Effect.fnUntraced(function* (leaves, previous, baseDigest) {
|
|
135
|
+
if (baseDigest === void 0) return;
|
|
136
|
+
const current = yield* readManifest;
|
|
137
|
+
const registry = yield* Effect.fromResult(collect(leaves));
|
|
138
|
+
const checked = check(registry, previous);
|
|
139
|
+
for (const note of checked.notes) yield* logWarn(note);
|
|
140
|
+
const [error, ...more] = checked.errors;
|
|
141
|
+
for (const other of more) yield* logCodegenError(other);
|
|
142
|
+
if (error !== void 0) return yield* error;
|
|
143
|
+
const sections = Object.fromEntries([...registry].map(([key, { data }]) => [key, data]));
|
|
144
|
+
const { name, env, http } = current;
|
|
145
|
+
const digest = sectionDigest(baseDigest, sections);
|
|
146
|
+
yield* writeFileStringAndLog(yield* manifestPath, renderManifest({
|
|
147
|
+
name,
|
|
148
|
+
env,
|
|
149
|
+
http,
|
|
150
|
+
digest,
|
|
151
|
+
...sections
|
|
152
|
+
}));
|
|
153
|
+
}, Effect.tapError(() => removeManifest));
|
|
120
154
|
const authProvidersPath = Effect.gen(function* () {
|
|
121
155
|
return (yield* Path.Path).join(yield* ConfectDirectory.get, "_generated", "auth.providers.ts");
|
|
122
156
|
});
|
|
123
157
|
const removeAuthProviders = Effect.gen(function* () {
|
|
124
158
|
yield* removeGenerated(yield* authProvidersPath, []);
|
|
125
159
|
});
|
|
126
|
-
const writeDeclaration = Effect.
|
|
160
|
+
const writeDeclaration = Effect.fnUntraced(function* (previous) {
|
|
127
161
|
const fs = yield* FileSystem.FileSystem;
|
|
128
162
|
const path = yield* Path.Path;
|
|
129
163
|
const convexDirectory = yield* ConvexDirectory.get;
|
|
@@ -153,12 +187,14 @@ const writeDeclaration = Effect.gen(function* () {
|
|
|
153
187
|
const legacyAuthConfigs = yield* Effect.forEach([authImportPath, authImportPath.replace(/\.js$/, "")], (importPath) => authConfig({ authImportPath: importPath }));
|
|
154
188
|
yield* assertOwned(convexConfigPath, "app.ts", []);
|
|
155
189
|
yield* assertOwned(authConfigPath, "auth.ts", legacyAuthConfigs);
|
|
190
|
+
let digest$1;
|
|
156
191
|
if (target === "app") {
|
|
157
|
-
|
|
192
|
+
digest$1 = digest({
|
|
158
193
|
files: yield* declarationInputs([app, ...Option.toArray(auth)]),
|
|
159
194
|
versions: [["convex", yield* packageVersion("convex", projectRoot)], ["@confect/cli generator format", GENERATOR_FORMAT]]
|
|
160
195
|
});
|
|
161
|
-
|
|
196
|
+
const sections$1 = sections(previous);
|
|
197
|
+
yield* writeFileStringAndLog(yield* manifestPath, manifest(declaration, sectionDigest(digest$1, sections$1), sections$1));
|
|
162
198
|
}
|
|
163
199
|
yield* writeFileStringAndLog(convexConfigPath, convexConfig(declaration));
|
|
164
200
|
yield* Option.match(declaration.providers, {
|
|
@@ -174,7 +210,10 @@ const writeDeclaration = Effect.gen(function* () {
|
|
|
174
210
|
yield* writeFileStringAndLog(yield* authProvidersPath, authProviders(providers));
|
|
175
211
|
})
|
|
176
212
|
});
|
|
177
|
-
return
|
|
213
|
+
return {
|
|
214
|
+
app: App.isApp(appValue) ? Option.some(appValue) : Option.none(),
|
|
215
|
+
digest: digest$1
|
|
216
|
+
};
|
|
178
217
|
});
|
|
179
218
|
/**
|
|
180
219
|
* Write the declaration's Convex files and manifest from `confect/app.ts`,
|
|
@@ -182,13 +221,16 @@ const writeDeclaration = Effect.gen(function* () {
|
|
|
182
221
|
* any failure the previous manifest is removed, so a stale manifest never
|
|
183
222
|
* outlives a declaration that no longer produces it.
|
|
184
223
|
*/
|
|
185
|
-
const syncDeclaration = Effect.
|
|
224
|
+
const syncDeclaration = Effect.fnUntraced(function* (previous) {
|
|
186
225
|
if (!(yield* isDeclared)) {
|
|
187
226
|
yield* removeManifest;
|
|
188
227
|
yield* removeAuthProviders;
|
|
189
|
-
return
|
|
228
|
+
return {
|
|
229
|
+
app: Option.none(),
|
|
230
|
+
digest: void 0
|
|
231
|
+
};
|
|
190
232
|
}
|
|
191
|
-
return yield* writeDeclaration.pipe(Effect.tapError(() => removeManifest.pipe(Effect.andThen(removeAuthProviders))));
|
|
233
|
+
return yield* writeDeclaration(previous).pipe(Effect.tapError(() => removeManifest.pipe(Effect.andThen(removeAuthProviders))));
|
|
192
234
|
});
|
|
193
235
|
/**
|
|
194
236
|
* Check every HTTP route the backend serves and write `convex/http.ts` from
|
|
@@ -226,6 +268,6 @@ const checkAndWriteHttp = Effect.fnUntraced(function* (app) {
|
|
|
226
268
|
});
|
|
227
269
|
});
|
|
228
270
|
//#endregion
|
|
229
|
-
export { isDeclared, syncDeclaration, syncDeclaredHttp };
|
|
271
|
+
export { isDeclared, readPrevious, syncDeclaration, syncDeclaredHttp, syncManifestSections };
|
|
230
272
|
|
|
231
273
|
//# sourceMappingURL=declaration.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"declaration.mjs","names":["Bundler.bundle","ConvexConfig.componentConfigPlugin","Declaration.isGenerated","Bundler.resolveModule","ConvexConfig.componentImportOf","Declaration.parse","Declaration.fileOf","ConvexConfig.CONVEX_CONFIG_FILENAME","templates.authConfig","digest","Declaration.digest","Declaration.manifest","Declaration.convexConfig","Declaration.authConfig","Declaration.authProviders","templates.http","http","templates.declaredHttp"],"sources":["../../src/confect/declaration.ts"],"sourcesContent":["import { App, Http } from \"@confect/core\";\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 Predicate from \"effect/Predicate\";\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 HandWrittenConvexFileError,\n DeclarationKindMismatchError,\n InvalidDeclarationError,\n} from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as Declaration from \"../Declaration.js\";\nimport { logFileRemoved } from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport * as templates from \"../templates.js\";\nimport {\n removePathIfExists,\n toModuleImportPath,\n toPosixPath,\n writeFileString,\n writeFileStringAndLog,\n} from \"../utils.js\";\n\n/**\n * Bumped when the generated files change shape, so a manifest written by an\n * older generator never matches a current one.\n */\nconst GENERATOR_FORMAT = \"2\";\n\nconst confectPath = Effect.fnUntraced(function* (file: string) {\n const path = yield* Path.Path;\n return path.join(yield* ConfectDirectory.get, file);\n});\n\n/**\n * A backend opts in to the declaration by writing `confect/app.ts`.\n */\nexport const isDeclared = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n return yield* fs.exists(yield* confectPath(\"app.ts\"));\n});\n\nconst displayPath = Effect.fnUntraced(function* (absolutePath: string) {\n const path = yield* Path.Path;\n return toPosixPath(path, path.relative(yield* ProjectRoot.get, absolutePath));\n});\n\nconst bundleDeclaration = Effect.fnUntraced(function* (file: string) {\n const path = yield* Path.Path;\n const absolutePath = yield* confectPath(file);\n return yield* Bundler.bundle(absolutePath, {\n plugins: [ConvexConfig.componentConfigPlugin(path)],\n }).pipe(\n Effect.mapError((error) => fromBundlerError(`confect/${file}`, error)),\n );\n});\n\nconst invalid = (file: string) => (error: { readonly message: string }) =>\n new InvalidDeclarationError({\n declarationPath: `confect/${file}`,\n reason: error.message,\n });\n\n/**\n * Fail instead of overwriting a Convex file someone wrote by hand. A file with\n * the generated header, or one of the exact files an earlier codegen wrote\n * there, is ours to replace.\n */\nconst assertOwned = Effect.fnUntraced(function* (\n convexPath: string,\n declarationFile: string,\n legacy: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(convexPath))) return;\n if (Declaration.isGenerated(yield* fs.readFileString(convexPath), legacy)) {\n return;\n }\n return yield* new HandWrittenConvexFileError({\n convexPath: yield* displayPath(convexPath),\n declarationPath: `confect/${declarationFile}`,\n });\n});\n\nconst decodeVersion = Schema.decodeUnknownOption(\n Schema.fromJsonString(Schema.Struct({ version: Schema.String })),\n);\n\nconst packageVersion = Effect.fnUntraced(function* (\n name: string,\n from: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n return yield* Option.match(\n Bundler.resolveModule(`${name}/package.json`, path.join(from, \"_\")),\n {\n onNone: () => Effect.succeed(\"unresolved\"),\n onSome: (packageJson) =>\n fs.readFileString(packageJson).pipe(\n Effect.map((contents) =>\n Option.match(decodeVersion(contents), {\n onNone: () => \"unknown\",\n onSome: ({ version }) => version,\n }),\n ),\n ),\n },\n );\n});\n\n/**\n * Every first-party file the declaration modules import, by project-relative\n * path and contents. Files under `node_modules` and outside the project count\n * through package versions instead, so rebuilding a dependency does not change\n * the digest.\n */\nconst declarationInputs = Effect.fnUntraced(function* (\n bundles: ReadonlyArray<Bundler.Bundled>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const projectRoot = yield* ProjectRoot.get;\n const files = new Set<string>();\n for (const { metafile } of bundles) {\n for (const input of Object.keys(metafile.inputs)) {\n const relative = path.relative(projectRoot, input);\n if (\n path.isAbsolute(input) &&\n !relative.startsWith(\"..\") &&\n !relative.split(path.sep).includes(\"node_modules\")\n ) {\n files.add(input);\n }\n }\n }\n // Plugin namespaces (component config wrappers) appear as inputs too;\n // only real files count.\n const real = yield* Effect.filter([...files], (file) => fs.exists(file));\n return yield* Effect.forEach(real, (file) =>\n fs\n .readFileString(file)\n .pipe(\n Effect.map(\n (contents) =>\n [\n toPosixPath(path, path.relative(projectRoot, file)),\n contents,\n ] as const,\n ),\n ),\n );\n});\n\nconst componentImport = Effect.fnUntraced(function* () {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n return (definition: unknown): Option.Option<Declaration.ComponentImport> =>\n Option.map(ConvexConfig.componentImportOf(definition), (recorded) => {\n const bare =\n !recorded.specifier.startsWith(\".\") &&\n !path.isAbsolute(recorded.specifier);\n const relative = toPosixPath(\n path,\n path.relative(convexDirectory, recorded.path),\n ).replace(/\\.([cm]?)[jt]s$/, \".$1js\");\n return {\n importPath: bare\n ? recorded.specifier\n : relative.startsWith(\".\")\n ? relative\n : `./${relative}`,\n componentName:\n Predicate.hasProperty(definition, \"defaultName\") &&\n Predicate.isString(definition.defaultName)\n ? definition.defaultName\n : \"component\",\n };\n });\n});\n\nconst manifestPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n return path.join(yield* ConfectDirectory.get, \"_generated\", \"manifest.ts\");\n});\n\n/**\n * Remove a file codegen wrote whose source is gone; leave anything else.\n */\nconst removeGenerated = Effect.fnUntraced(function* (\n filePath: string,\n legacy: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(filePath))) return;\n if (!Declaration.isGenerated(yield* fs.readFileString(filePath), legacy)) {\n return;\n }\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n});\n\nconst removeManifest = Effect.gen(function* () {\n yield* removeGenerated(yield* manifestPath, []);\n});\n\nconst authProvidersPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n return path.join(\n yield* ConfectDirectory.get,\n \"_generated\",\n \"auth.providers.ts\",\n );\n});\n\nconst removeAuthProviders = Effect.gen(function* () {\n yield* removeGenerated(yield* authProvidersPath, []);\n});\n\nconst writeDeclaration = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n const target = (yield* ConvexDirectory.target).kind;\n\n const app = yield* bundleDeclaration(\"app.ts\");\n const appValue: unknown = app.module.default;\n if (App.isApp(appValue) && appValue.kind !== target) {\n return yield* new DeclarationKindMismatchError({\n declarationPath: \"confect/app.ts\",\n declaredKind: appValue.kind,\n targetKind: target,\n });\n }\n const authPath = yield* confectPath(\"auth.ts\");\n const auth = (yield* fs.exists(authPath))\n ? Option.some(yield* bundleDeclaration(\"auth.ts\"))\n : Option.none();\n\n const declaration = yield* Declaration.parse({\n target,\n app: app.module.default,\n auth: Option.map(auth, ({ module }) => module.default),\n componentImport: yield* componentImport(),\n }).pipe(\n Result.mapError(\n (error) =>\n new InvalidDeclarationError({\n declarationPath: Declaration.fileOf(error),\n reason: error.message,\n }),\n ),\n Effect.fromResult,\n );\n\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n const authConfigPath = path.join(convexDirectory, \"auth.config.ts\");\n const authImportPath = yield* toModuleImportPath(\n path.relative(convexDirectory, authPath),\n );\n const legacyAuthConfigs = yield* Effect.forEach(\n [authImportPath, authImportPath.replace(/\\.js$/, \"\")],\n (importPath) => templates.authConfig({ authImportPath: importPath }),\n );\n yield* assertOwned(convexConfigPath, \"app.ts\", []);\n yield* assertOwned(authConfigPath, \"auth.ts\", legacyAuthConfigs);\n\n if (target === \"app\") {\n const digest = Declaration.digest({\n files: yield* declarationInputs([app, ...Option.toArray(auth)]),\n versions: [\n [\"convex\", yield* packageVersion(\"convex\", projectRoot)],\n [\"@confect/cli generator format\", GENERATOR_FORMAT],\n ],\n });\n yield* writeFileStringAndLog(\n yield* manifestPath,\n Declaration.manifest(declaration, digest),\n );\n }\n yield* writeFileStringAndLog(\n convexConfigPath,\n Declaration.convexConfig(declaration),\n );\n yield* Option.match(declaration.providers, {\n onNone: () =>\n Effect.gen(function* () {\n yield* removeAuthProviders;\n if (yield* fs.exists(authConfigPath)) {\n yield* removePathIfExists(authConfigPath);\n yield* logFileRemoved(authConfigPath);\n }\n }),\n onSome: (providers) =>\n Effect.gen(function* () {\n yield* writeFileStringAndLog(\n authConfigPath,\n Declaration.authConfig(providers),\n );\n yield* writeFileStringAndLog(\n yield* authProvidersPath,\n Declaration.authProviders(providers),\n );\n }),\n });\n return App.isApp(appValue) ? Option.some(appValue) : Option.none<App.Any>();\n});\n\n/**\n * Write the declaration's Convex files and manifest from `confect/app.ts`,\n * `confect/env.ts` and `confect/auth.ts`, before anything else is validated. On\n * any failure the previous manifest is removed, so a stale manifest never\n * outlives a declaration that no longer produces it.\n */\nexport const syncDeclaration = Effect.gen(function* () {\n if (!(yield* isDeclared)) {\n yield* removeManifest;\n yield* removeAuthProviders;\n return Option.none<App.Any>();\n }\n return yield* writeDeclaration.pipe(\n Effect.tapError(() =>\n removeManifest.pipe(Effect.andThen(removeAuthProviders)),\n ),\n );\n});\n\n/**\n * Check every HTTP route the backend serves and write `convex/http.ts` from\n * `confect/http.ts`. Runs after generation, because `http.ts` imports its\n * handlers, which import generated services.\n */\nexport const syncDeclaredHttp = (app: App.Any) =>\n checkAndWriteHttp(app).pipe(Effect.tapError(() => removeManifest));\n\nconst checkAndWriteHttp = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const httpPath = yield* confectPath(\"http.ts\");\n\n const convexHttpPath = path.join(convexDirectory, \"http.ts\");\n if (!(yield* fs.exists(httpPath))) {\n yield* Http.routes(app).pipe(\n Result.mapError(invalid(\"app.ts\")),\n Effect.fromResult,\n );\n yield* removeGenerated(convexHttpPath, [\n yield* templates.http({\n httpImportPath: yield* toModuleImportPath(\n path.relative(convexDirectory, httpPath),\n ),\n }),\n ]);\n return Option.none();\n }\n\n const http = (yield* bundleDeclaration(\"http.ts\")).module.default;\n if (!Http.isHttp(http)) {\n return yield* new InvalidDeclarationError({\n declarationPath: \"confect/http.ts\",\n reason: \"it must default-export Http.make(...).\",\n });\n }\n yield* Http.routes(app, http).pipe(\n Result.mapError(invalid(\"http.ts\")),\n Effect.fromResult,\n );\n\n const contents = yield* templates.declaredHttp({\n runtimeImportPath: (yield* fs.exists(\n path.join(confectDirectory, \"runtime.ts\"),\n ))\n ? yield* toModuleImportPath(\n path.relative(\n convexDirectory,\n path.join(confectDirectory, \"runtime.ts\"),\n ),\n )\n : undefined,\n schemaImportPath: yield* toModuleImportPath(\n path.relative(\n convexDirectory,\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n ),\n httpImportPath: yield* toModuleImportPath(\n path.relative(convexDirectory, httpPath),\n ),\n });\n const change = yield* writeFileString(convexHttpPath, contents);\n return Option.some({ change, convexFilePath: convexHttpPath });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,mBAAmB;AAEzB,MAAM,cAAc,OAAO,WAAW,WAAW,MAAc;CAE7D,QAAO,OADa,KAAK,KAAA,CACb,KAAK,OAAO,iBAAiB,KAAK,IAAI;AACpD,CAAC;;;;AAKD,MAAa,aAAa,OAAO,IAAI,aAAa;CAEhD,OAAO,QAAO,OADI,WAAW,WAAA,CACZ,OAAO,OAAO,YAAY,QAAQ,CAAC;AACtD,CAAC;AAED,MAAM,cAAc,OAAO,WAAW,WAAW,cAAsB;CACrE,MAAM,OAAO,OAAO,KAAK;CACzB,OAAO,YAAY,MAAM,KAAK,SAAS,OAAO,YAAY,KAAK,YAAY,CAAC;AAC9E,CAAC;AAED,MAAM,oBAAoB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iBAAiB;EACjB,QAAQ;CACV,CAAC;CAEH,OAAO,KAAK,OAAO,KAAKA,MAAI,CAAC,CAAC,KAC5B,OAAO,SAAS,QAAQ,SAAS,CAAC,GAClC,OAAO,UACT;CAEA,MAAM,WAAW,OAAOC,aAAuB;EAC7C,oBAAoB,OAAO,GAAG,OAC5B,KAAK,KAAK,kBAAkB,YAAY,CAC1C,KACI,OAAO,mBACL,KAAK,SACH,iBACA,KAAK,KAAK,kBAAkB,YAAY,CAC1C,CACF,IACA,KAAA;EACJ,kBAAkB,OAAO,mBACvB,KAAK,SACH,iBACA,KAAK,KAAK,kBAAkB,cAAc,WAAW,CACvD,CACF;EACA,gBAAgB,OAAO,mBACrB,KAAK,SAAS,iBAAiB,QAAQ,CACzC;CACF,CAAC;CACD,MAAM,SAAS,OAAO,gBAAgB,gBAAgB,QAAQ;CAC9D,OAAO,OAAO,KAAK;EAAE;EAAQ,gBAAgB;CAAe,CAAC;AAC/D,CAAC"}
|
|
1
|
+
{"version":3,"file":"declaration.mjs","names":["Bundler.bundle","ConvexConfig.componentConfigPlugin","Declaration.isGenerated","Bundler.resolveModule","ConvexConfig.componentImportOf","Declaration.digest","ManifestSections.collect","ManifestSections.check","Declaration.renderManifest","Declaration.parse","Declaration.fileOf","ConvexConfig.CONVEX_CONFIG_FILENAME","templates.authConfig","digest","sections","ManifestSections.sections","Declaration.manifest","Declaration.convexConfig","Declaration.authConfig","Declaration.authProviders","templates.http","http","templates.declaredHttp"],"sources":["../../src/confect/declaration.ts"],"sourcesContent":["import { App, Http } from \"@confect/core\";\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 Predicate from \"effect/Predicate\";\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 HandWrittenConvexFileError,\n DeclarationKindMismatchError,\n InvalidDeclarationError,\n logCodegenError,\n} from \"../CodegenError.js\";\nimport { ConfectDirectory } from \"../ConfectDirectory.js\";\nimport * as ConvexConfig from \"../ConvexConfig.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as Declaration from \"../Declaration.js\";\nimport * as ManifestSections from \"../ManifestSections.js\";\nimport type { LoadedLeafModule } from \"../LeafModule.js\";\nimport { logWarn, logFileRemoved } from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport * as templates from \"../templates.js\";\nimport {\n removePathIfExists,\n toModuleImportPath,\n toPosixPath,\n writeFileString,\n writeFileStringAndLog,\n} from \"../utils.js\";\n\n/**\n * Bumped when the generated files change shape, so a manifest written by an\n * older generator never matches a current one.\n */\nconst GENERATOR_FORMAT = \"2\";\n\nconst confectPath = Effect.fnUntraced(function* (file: string) {\n const path = yield* Path.Path;\n return path.join(yield* ConfectDirectory.get, file);\n});\n\n/**\n * A backend opts in to the declaration by writing `confect/app.ts`.\n */\nexport const isDeclared = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n return yield* fs.exists(yield* confectPath(\"app.ts\"));\n});\n\nconst displayPath = Effect.fnUntraced(function* (absolutePath: string) {\n const path = yield* Path.Path;\n return toPosixPath(path, path.relative(yield* ProjectRoot.get, absolutePath));\n});\n\nconst bundleDeclaration = Effect.fnUntraced(function* (file: string) {\n const path = yield* Path.Path;\n const absolutePath = yield* confectPath(file);\n return yield* Bundler.bundle(absolutePath, {\n plugins: [ConvexConfig.componentConfigPlugin(path)],\n }).pipe(\n Effect.mapError((error) => fromBundlerError(`confect/${file}`, error)),\n );\n});\n\nconst invalid = (file: string) => (error: { readonly message: string }) =>\n new InvalidDeclarationError({\n declarationPath: `confect/${file}`,\n reason: error.message,\n });\n\n/**\n * Fail instead of overwriting a Convex file someone wrote by hand. A file with\n * the generated header, or one of the exact files an earlier codegen wrote\n * there, is ours to replace.\n */\nconst assertOwned = Effect.fnUntraced(function* (\n convexPath: string,\n declarationFile: string,\n legacy: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(convexPath))) return;\n if (Declaration.isGenerated(yield* fs.readFileString(convexPath), legacy)) {\n return;\n }\n return yield* new HandWrittenConvexFileError({\n convexPath: yield* displayPath(convexPath),\n declarationPath: `confect/${declarationFile}`,\n });\n});\n\nconst decodeVersion = Schema.decodeUnknownOption(\n Schema.fromJsonString(Schema.Struct({ version: Schema.String })),\n);\n\nconst packageVersion = Effect.fnUntraced(function* (\n name: string,\n from: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n return yield* Option.match(\n Bundler.resolveModule(`${name}/package.json`, path.join(from, \"_\")),\n {\n onNone: () => Effect.succeed(\"unresolved\"),\n onSome: (packageJson) =>\n fs.readFileString(packageJson).pipe(\n Effect.map((contents) =>\n Option.match(decodeVersion(contents), {\n onNone: () => \"unknown\",\n onSome: ({ version }) => version,\n }),\n ),\n ),\n },\n );\n});\n\n/**\n * Every first-party file the declaration modules import, by project-relative\n * path and contents. Files under `node_modules` and outside the project count\n * through package versions instead, so rebuilding a dependency does not change\n * the digest.\n */\nconst declarationInputs = Effect.fnUntraced(function* (\n bundles: ReadonlyArray<Bundler.Bundled>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const projectRoot = yield* ProjectRoot.get;\n const files = new Set<string>();\n for (const { metafile } of bundles) {\n for (const input of Object.keys(metafile.inputs)) {\n const relative = path.relative(projectRoot, input);\n if (\n path.isAbsolute(input) &&\n !relative.startsWith(\"..\") &&\n !relative.split(path.sep).includes(\"node_modules\")\n ) {\n files.add(input);\n }\n }\n }\n // Plugin namespaces (component config wrappers) appear as inputs too;\n // only real files count.\n const real = yield* Effect.filter([...files], (file) => fs.exists(file));\n return yield* Effect.forEach(real, (file) =>\n fs\n .readFileString(file)\n .pipe(\n Effect.map(\n (contents) =>\n [\n toPosixPath(path, path.relative(projectRoot, file)),\n contents,\n ] as const,\n ),\n ),\n );\n});\n\nconst componentImport = Effect.fnUntraced(function* () {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n return (definition: unknown): Option.Option<Declaration.ComponentImport> =>\n Option.map(ConvexConfig.componentImportOf(definition), (recorded) => {\n const bare =\n !recorded.specifier.startsWith(\".\") &&\n !path.isAbsolute(recorded.specifier);\n const relative = toPosixPath(\n path,\n path.relative(convexDirectory, recorded.path),\n ).replace(/\\.([cm]?)[jt]s$/, \".$1js\");\n return {\n importPath: bare\n ? recorded.specifier\n : relative.startsWith(\".\")\n ? relative\n : `./${relative}`,\n componentName:\n Predicate.hasProperty(definition, \"defaultName\") &&\n Predicate.isString(definition.defaultName)\n ? definition.defaultName\n : \"component\",\n };\n });\n});\n\nconst manifestPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n return path.join(yield* ConfectDirectory.get, \"_generated\", \"manifest.ts\");\n});\n\n/**\n * Remove a file codegen wrote whose source is gone; leave anything else.\n */\nconst removeGenerated = Effect.fnUntraced(function* (\n filePath: string,\n legacy: ReadonlyArray<string>,\n) {\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(filePath))) return;\n if (!Declaration.isGenerated(yield* fs.readFileString(filePath), legacy)) {\n return;\n }\n yield* removePathIfExists(filePath);\n yield* logFileRemoved(filePath);\n});\n\nconst removeManifest = Effect.gen(function* () {\n yield* removeGenerated(yield* manifestPath, []);\n});\n\nconst readManifest = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const file = yield* manifestPath;\n if (!(yield* fs.exists(file))) return {} as Record<string, unknown>;\n const data: unknown = (yield* Bundler.bundle(file).pipe(\n Effect.mapError((error) =>\n fromBundlerError(\"confect/_generated/manifest.ts\", error),\n ),\n )).module.default;\n return Predicate.isObject(data) ? data : {};\n});\n\nexport const readPrevious = readManifest.pipe(\n Effect.orElseSucceed(() => ({}) as Record<string, unknown>),\n);\n\nconst sectionDigest = (\n base: string,\n sections: Readonly<Record<string, unknown>>,\n) =>\n Object.keys(sections).length === 0\n ? base\n : Declaration.digest({\n files: [[\"declaration\", base]],\n versions: [],\n sections,\n });\n\nexport const syncManifestSections = Effect.fnUntraced(\n function* (\n leaves: ReadonlyArray<LoadedLeafModule>,\n previous: Readonly<Record<string, unknown>>,\n baseDigest: string | undefined,\n ) {\n if (baseDigest === undefined) return;\n const current = yield* readManifest;\n const registry = yield* Effect.fromResult(ManifestSections.collect(leaves));\n const checked = ManifestSections.check(registry, previous);\n for (const note of checked.notes) yield* logWarn(note);\n const [error, ...more] = checked.errors;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n const sections = Object.fromEntries(\n [...registry].map(([key, { data }]) => [key, data]),\n );\n const { name, env, http } = current;\n const digest = sectionDigest(baseDigest, sections);\n yield* writeFileStringAndLog(\n yield* manifestPath,\n Declaration.renderManifest({ name, env, http, digest, ...sections }),\n );\n },\n Effect.tapError(() => removeManifest),\n);\n\nconst authProvidersPath = Effect.gen(function* () {\n const path = yield* Path.Path;\n return path.join(\n yield* ConfectDirectory.get,\n \"_generated\",\n \"auth.providers.ts\",\n );\n});\n\nconst removeAuthProviders = Effect.gen(function* () {\n yield* removeGenerated(yield* authProvidersPath, []);\n});\n\nconst writeDeclaration = Effect.fnUntraced(function* (\n previous: Readonly<Record<string, unknown>>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n const target = (yield* ConvexDirectory.target).kind;\n\n const app = yield* bundleDeclaration(\"app.ts\");\n const appValue: unknown = app.module.default;\n if (App.isApp(appValue) && appValue.kind !== target) {\n return yield* new DeclarationKindMismatchError({\n declarationPath: \"confect/app.ts\",\n declaredKind: appValue.kind,\n targetKind: target,\n });\n }\n const authPath = yield* confectPath(\"auth.ts\");\n const auth = (yield* fs.exists(authPath))\n ? Option.some(yield* bundleDeclaration(\"auth.ts\"))\n : Option.none();\n\n const declaration = yield* Declaration.parse({\n target,\n app: app.module.default,\n auth: Option.map(auth, ({ module }) => module.default),\n componentImport: yield* componentImport(),\n }).pipe(\n Result.mapError(\n (error) =>\n new InvalidDeclarationError({\n declarationPath: Declaration.fileOf(error),\n reason: error.message,\n }),\n ),\n Effect.fromResult,\n );\n\n const convexConfigPath = path.join(\n convexDirectory,\n ConvexConfig.CONVEX_CONFIG_FILENAME,\n );\n const authConfigPath = path.join(convexDirectory, \"auth.config.ts\");\n const authImportPath = yield* toModuleImportPath(\n path.relative(convexDirectory, authPath),\n );\n const legacyAuthConfigs = yield* Effect.forEach(\n [authImportPath, authImportPath.replace(/\\.js$/, \"\")],\n (importPath) => templates.authConfig({ authImportPath: importPath }),\n );\n yield* assertOwned(convexConfigPath, \"app.ts\", []);\n yield* assertOwned(authConfigPath, \"auth.ts\", legacyAuthConfigs);\n\n let digest: string | undefined;\n if (target === \"app\") {\n digest = Declaration.digest({\n files: yield* declarationInputs([app, ...Option.toArray(auth)]),\n versions: [\n [\"convex\", yield* packageVersion(\"convex\", projectRoot)],\n [\"@confect/cli generator format\", GENERATOR_FORMAT],\n ],\n });\n const sections = ManifestSections.sections(previous);\n yield* writeFileStringAndLog(\n yield* manifestPath,\n Declaration.manifest(\n declaration,\n sectionDigest(digest, sections),\n sections,\n ),\n );\n }\n yield* writeFileStringAndLog(\n convexConfigPath,\n Declaration.convexConfig(declaration),\n );\n yield* Option.match(declaration.providers, {\n onNone: () =>\n Effect.gen(function* () {\n yield* removeAuthProviders;\n if (yield* fs.exists(authConfigPath)) {\n yield* removePathIfExists(authConfigPath);\n yield* logFileRemoved(authConfigPath);\n }\n }),\n onSome: (providers) =>\n Effect.gen(function* () {\n yield* writeFileStringAndLog(\n authConfigPath,\n Declaration.authConfig(providers),\n );\n yield* writeFileStringAndLog(\n yield* authProvidersPath,\n Declaration.authProviders(providers),\n );\n }),\n });\n return {\n app: App.isApp(appValue) ? Option.some(appValue) : Option.none<App.Any>(),\n digest,\n };\n});\n\n/**\n * Write the declaration's Convex files and manifest from `confect/app.ts`,\n * `confect/env.ts` and `confect/auth.ts`, before anything else is validated. On\n * any failure the previous manifest is removed, so a stale manifest never\n * outlives a declaration that no longer produces it.\n */\nexport const syncDeclaration = Effect.fnUntraced(function* (\n previous: Readonly<Record<string, unknown>>,\n) {\n if (!(yield* isDeclared)) {\n yield* removeManifest;\n yield* removeAuthProviders;\n return { app: Option.none<App.Any>(), digest: undefined };\n }\n return yield* writeDeclaration(previous).pipe(\n Effect.tapError(() =>\n removeManifest.pipe(Effect.andThen(removeAuthProviders)),\n ),\n );\n});\n\n/**\n * Check every HTTP route the backend serves and write `convex/http.ts` from\n * `confect/http.ts`. Runs after generation, because `http.ts` imports its\n * handlers, which import generated services.\n */\nexport const syncDeclaredHttp = (app: App.Any) =>\n checkAndWriteHttp(app).pipe(Effect.tapError(() => removeManifest));\n\nconst checkAndWriteHttp = Effect.fnUntraced(function* (app: App.Any) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const httpPath = yield* confectPath(\"http.ts\");\n\n const convexHttpPath = path.join(convexDirectory, \"http.ts\");\n if (!(yield* fs.exists(httpPath))) {\n yield* Http.routes(app).pipe(\n Result.mapError(invalid(\"app.ts\")),\n Effect.fromResult,\n );\n yield* removeGenerated(convexHttpPath, [\n yield* templates.http({\n httpImportPath: yield* toModuleImportPath(\n path.relative(convexDirectory, httpPath),\n ),\n }),\n ]);\n return Option.none();\n }\n\n const http = (yield* bundleDeclaration(\"http.ts\")).module.default;\n if (!Http.isHttp(http)) {\n return yield* new InvalidDeclarationError({\n declarationPath: \"confect/http.ts\",\n reason: \"it must default-export Http.make(...).\",\n });\n }\n yield* Http.routes(app, http).pipe(\n Result.mapError(invalid(\"http.ts\")),\n Effect.fromResult,\n );\n\n const contents = yield* templates.declaredHttp({\n runtimeImportPath: (yield* fs.exists(\n path.join(confectDirectory, \"runtime.ts\"),\n ))\n ? yield* toModuleImportPath(\n path.relative(\n convexDirectory,\n path.join(confectDirectory, \"runtime.ts\"),\n ),\n )\n : undefined,\n schemaImportPath: yield* toModuleImportPath(\n path.relative(\n convexDirectory,\n path.join(confectDirectory, \"_generated\", \"schema.ts\"),\n ),\n ),\n httpImportPath: yield* toModuleImportPath(\n path.relative(convexDirectory, httpPath),\n ),\n });\n const change = yield* writeFileString(convexHttpPath, contents);\n return Option.some({ change, convexFilePath: convexHttpPath });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,mBAAmB;AAEzB,MAAM,cAAc,OAAO,WAAW,WAAW,MAAc;CAE7D,QAAO,OADa,KAAK,KAAA,CACb,KAAK,OAAO,iBAAiB,KAAK,IAAI;AACpD,CAAC;;;;AAKD,MAAa,aAAa,OAAO,IAAI,aAAa;CAEhD,OAAO,QAAO,OADI,WAAW,WAAA,CACZ,OAAO,OAAO,YAAY,QAAQ,CAAC;AACtD,CAAC;AAED,MAAM,cAAc,OAAO,WAAW,WAAW,cAAsB;CACrE,MAAM,OAAO,OAAO,KAAK;CACzB,OAAO,YAAY,MAAM,KAAK,SAAS,OAAO,YAAY,KAAK,YAAY,CAAC;AAC9E,CAAC;AAED,MAAM,oBAAoB,OAAO,WAAW,WAAW,MAAc;CACnE,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,eAAe,OAAO,YAAY,IAAI;CAC5C,OAAO,OAAOA,OAAe,cAAc,EACzC,SAAS,CAACC,sBAAmC,IAAI,CAAC,EACpD,CAAC,CAAC,CAAC,KACD,OAAO,UAAU,UAAU,iBAAiB,WAAW,QAAQ,KAAK,CAAC,CACvE;AACF,CAAC;AAED,MAAM,WAAW,UAAkB,UACjC,IAAI,wBAAwB;CAC1B,iBAAiB,WAAW;CAC5B,QAAQ,MAAM;AAChB,CAAC;;;;;;AAOH,MAAM,cAAc,OAAO,WAAW,WACpC,YACA,iBACA,QACA;CACA,MAAM,KAAK,OAAO,WAAW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,KACI,OAAO,mBACL,KAAK,SACH,iBACA,KAAK,KAAK,kBAAkB,YAAY,CAC1C,CACF,IACA,KAAA;EACJ,kBAAkB,OAAO,mBACvB,KAAK,SACH,iBACA,KAAK,KAAK,kBAAkB,cAAc,WAAW,CACvD,CACF;EACA,gBAAgB,OAAO,mBACrB,KAAK,SAAS,iBAAiB,QAAQ,CACzC;CACF,CAAC;CACD,MAAM,SAAS,OAAO,gBAAgB,gBAAgB,QAAQ;CAC9D,OAAO,OAAO,KAAK;EAAE;EAAQ,gBAAgB;CAAe,CAAC;AAC/D,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gaganref/confect-cli",
|
|
3
|
-
"version": "10.3.1-fork.
|
|
3
|
+
"version": "10.3.1-fork.47",
|
|
4
4
|
"dependencies": {
|
|
5
5
|
"@effect/platform-node": ">=4.0.4 <4.1.0",
|
|
6
6
|
"bundle-require": "^5.1.0",
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
"exsolve": "^1.1.3"
|
|
10
10
|
},
|
|
11
11
|
"peerDependencies": {
|
|
12
|
-
"@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.
|
|
13
|
-
"@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.
|
|
12
|
+
"@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.47",
|
|
13
|
+
"@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.47",
|
|
14
14
|
"@effect/platform-node-shared": ">=4.0.4 <4.1.0",
|
|
15
15
|
"effect": ">=4.0.4 <4.1.0"
|
|
16
16
|
},
|