@gaganref/confect-cli 10.3.1-fork.71 → 10.3.1-fork.73

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.
@@ -30,9 +30,29 @@ var InvalidBinding = class extends Data.TaggedError("InvalidBinding") {
30
30
  return `The mount "${this.mount}" binds ${this.slot} to something other than a string or an entry of this backend's env.`;
31
31
  }
32
32
  };
33
- var UnknownComponentImport = class extends Data.TaggedError("UnknownComponentImport") {
33
+ var InvalidComponentDefinition = class extends Data.TaggedError("InvalidComponentDefinition") {
34
34
  get message() {
35
- return `The mount "${this.mount}" must pass the default export of a component's convex.config module, imported directly in the declaration.`;
35
+ return `App.make's components[${this.index}] must be the default export of a component's convex.config module, imported directly in the declaration.`;
36
+ }
37
+ };
38
+ var MountWithoutDefinition = class extends Data.TaggedError("MountWithoutDefinition") {
39
+ get message() {
40
+ return `The mount "${this.mount}" mounts the component "${this.component}", but App.make's components lists no definition named "${this.component}".`;
41
+ }
42
+ };
43
+ var DefinitionWithoutMount = class extends Data.TaggedError("DefinitionWithoutMount") {
44
+ get message() {
45
+ return `App.make's components lists the definition "${this.component}" from ${this.importPath}, but no mount mounts it.`;
46
+ }
47
+ };
48
+ var DuplicateMountName = class extends Data.TaggedError("DuplicateMountName") {
49
+ get message() {
50
+ return `Two mounts are named "${this.mount}", one of "${this.first}" and one of "${this.second}"; give each mount its own name.`;
51
+ }
52
+ };
53
+ var DuplicateDefinitionName = class extends Data.TaggedError("DuplicateDefinitionName") {
54
+ get message() {
55
+ return `Two component definitions are named "${this.component}", from ${this.first} and ${this.second}; give each definition its own name.`;
36
56
  }
37
57
  };
38
58
  var AuthForAnotherBackend = class extends Data.TaggedError("AuthForAnotherBackend") {
@@ -54,7 +74,8 @@ const fileOf = (error) => error._tag === "NotADeclaration" ? error.file : error.
54
74
  /**
55
75
  * Parse the default exports of `confect/app.ts` and, when present,
56
76
  * `confect/auth.ts`. `componentImport` recovers how the generated config
57
- * imports a mounted definition; codegen's bundler records it.
77
+ * imports a listed definition; codegen's bundler records it. Each mount takes
78
+ * the definition whose `defineComponent` name is its component's name.
58
79
  */
59
80
  const parse = (input) => Result.gen(function* () {
60
81
  if (!App.isApp(input.app)) return yield* Result.fail(new NotADeclaration({
@@ -65,13 +86,35 @@ const parse = (input) => Result.gen(function* () {
65
86
  const name = Env.name(env);
66
87
  const descriptors = Env.descriptors(env);
67
88
  for (const [key] of descriptors) if (!ENV_KEY.test(key)) return yield* Result.fail(new InvalidEnvKey({ key }));
89
+ const definitions = /* @__PURE__ */ new Map();
90
+ for (const [index, definition] of App.components(input.app).entries()) {
91
+ const component = input.componentImport(definition);
92
+ if (Option.isNone(component)) return yield* Result.fail(new InvalidComponentDefinition({ index }));
93
+ const { componentName, importPath } = component.value;
94
+ const named = definitions.get(componentName);
95
+ if (named !== void 0 && named.importPath !== importPath) return yield* Result.fail(new DuplicateDefinitionName({
96
+ component: componentName,
97
+ first: named.importPath,
98
+ second: importPath
99
+ }));
100
+ definitions.set(componentName, component.value);
101
+ }
68
102
  const mounts = [];
69
103
  for (const mount of App.mounts(input.app)) {
70
104
  if (!MOUNT_NAME.test(mount.name)) return yield* Result.fail(new InvalidMountName({ mount: mount.name }));
71
- const component = input.componentImport(mount.definition);
72
- if (Option.isNone(component)) return yield* Result.fail(new UnknownComponentImport({ mount: mount.name }));
105
+ const component = definitions.get(mount.component.name);
106
+ if (component === void 0) return yield* Result.fail(new MountWithoutDefinition({
107
+ mount: mount.name,
108
+ component: mount.component.name
109
+ }));
110
+ const named = mounts.find((declared) => declared.name === mount.name);
111
+ if (named !== void 0) return yield* Result.fail(new DuplicateMountName({
112
+ mount: mount.name,
113
+ first: named.componentName,
114
+ second: component.componentName
115
+ }));
73
116
  const bindings = [];
74
- for (const [slot, bound] of Object.entries(mount.env)) {
117
+ for (const [slot, bound] of Object.entries(mount.env ?? {})) {
75
118
  if (bound === void 0) continue;
76
119
  if (typeof bound === "string") {
77
120
  bindings.push([slot, {
@@ -99,12 +142,16 @@ const parse = (input) => Result.gen(function* () {
99
142
  }
100
143
  mounts.push({
101
144
  name: mount.name,
102
- importPath: component.value.importPath,
103
- componentName: component.value.componentName,
145
+ importPath: component.importPath,
146
+ componentName: component.componentName,
104
147
  httpPrefix: mount.httpPrefix,
105
148
  env: bindings
106
149
  });
107
150
  }
151
+ for (const [component, { importPath }] of definitions) if (!mounts.some(({ componentName }) => componentName === component)) return yield* Result.fail(new DefinitionWithoutMount({
152
+ component,
153
+ importPath
154
+ }));
108
155
  const providers = Option.isNone(input.auth) ? Option.none() : Option.some(yield* parseProviders(input.auth.value, name));
109
156
  return {
110
157
  target: input.target,
@@ -319,6 +366,6 @@ const digest = (input) => {
319
366
  return `sha256:${hash.digest("hex")}`;
320
367
  };
321
368
  //#endregion
322
- export { AuthForAnotherBackend, ForeignEnvBinding, InvalidBinding, InvalidEnvKey, InvalidMountName, InvalidProviderEnv, NotADeclaration, UnknownComponentImport, authConfig, authProviders, convexConfig, digest, fileOf, header, isGenerated, manifest, parse, renderManifest };
369
+ export { AuthForAnotherBackend, DefinitionWithoutMount, DuplicateDefinitionName, DuplicateMountName, ForeignEnvBinding, InvalidBinding, InvalidComponentDefinition, InvalidEnvKey, InvalidMountName, InvalidProviderEnv, MountWithoutDefinition, NotADeclaration, authConfig, authProviders, convexConfig, digest, fileOf, header, isGenerated, manifest, parse, renderManifest };
323
370
 
324
371
  //# sourceMappingURL=Declaration.mjs.map
@@ -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 = (\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"],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UAAU,MAAM,SAAS;CACrE,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 InvalidComponentDefinition extends Data.TaggedError(\n \"InvalidComponentDefinition\",\n)<{ readonly index: number }> {\n override get message(): string {\n return `App.make's components[${this.index}] must be the default export of a component's convex.config module, imported directly in the declaration.`;\n }\n}\n\nexport class MountWithoutDefinition extends Data.TaggedError(\n \"MountWithoutDefinition\",\n)<{ readonly mount: string; readonly component: string }> {\n override get message(): string {\n return `The mount \"${this.mount}\" mounts the component \"${this.component}\", but App.make's components lists no definition named \"${this.component}\".`;\n }\n}\n\nexport class DefinitionWithoutMount extends Data.TaggedError(\n \"DefinitionWithoutMount\",\n)<{ readonly component: string; readonly importPath: string }> {\n override get message(): string {\n return `App.make's components lists the definition \"${this.component}\" from ${this.importPath}, but no mount mounts it.`;\n }\n}\n\nexport class DuplicateMountName extends Data.TaggedError(\"DuplicateMountName\")<{\n readonly mount: string;\n readonly first: string;\n readonly second: string;\n}> {\n override get message(): string {\n return `Two mounts are named \"${this.mount}\", one of \"${this.first}\" and one of \"${this.second}\"; give each mount its own name.`;\n }\n}\n\nexport class DuplicateDefinitionName extends Data.TaggedError(\n \"DuplicateDefinitionName\",\n)<{\n readonly component: string;\n readonly first: string;\n readonly second: string;\n}> {\n override get message(): string {\n return `Two component definitions are named \"${this.component}\", from ${this.first} and ${this.second}; give each definition its own name.`;\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 | InvalidComponentDefinition\n | MountWithoutDefinition\n | DefinitionWithoutMount\n | DuplicateMountName\n | DuplicateDefinitionName\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 listed definition; codegen's bundler records it. Each mount takes\n * the definition whose `defineComponent` name is its component's name.\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 definitions = new Map<string, ComponentImport>();\n for (const [index, definition] of App.components(input.app).entries()) {\n const component = input.componentImport(definition);\n if (Option.isNone(component)) {\n return yield* Result.fail(new InvalidComponentDefinition({ index }));\n }\n const { componentName, importPath } = component.value;\n const named = definitions.get(componentName);\n if (named !== undefined && named.importPath !== importPath) {\n return yield* Result.fail(\n new DuplicateDefinitionName({\n component: componentName,\n first: named.importPath,\n second: importPath,\n }),\n );\n }\n definitions.set(componentName, component.value);\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 = definitions.get(mount.component.name);\n if (component === undefined) {\n return yield* Result.fail(\n new MountWithoutDefinition({\n mount: mount.name,\n component: mount.component.name,\n }),\n );\n }\n const named = mounts.find((declared) => declared.name === mount.name);\n if (named !== undefined) {\n return yield* Result.fail(\n new DuplicateMountName({\n mount: mount.name,\n first: named.componentName,\n second: component.componentName,\n }),\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.importPath,\n componentName: component.componentName,\n httpPrefix: mount.httpPrefix,\n env: bindings,\n });\n }\n for (const [component, { importPath }] of definitions) {\n if (!mounts.some(({ componentName }) => componentName === component)) {\n return yield* Result.fail(\n new DefinitionWithoutMount({ component, importPath }),\n );\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,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;EAC7B,OAAO,cAAc,KAAK,MAAM,UAAU,KAAK,KAAK,MAAM,KAAK,IAAI,WAAW,KAAK,QAAQ,oCAAoC,KAAK,gBAAgB;CACtJ;AACF;AAEA,IAAa,iBAAb,cAAoC,KAAK,YAAY,gBAAgB,CAAC,CAGnE;CACD,IAAa,UAAkB;EAC7B,OAAO,cAAc,KAAK,MAAM,UAAU,KAAK,KAAK;CACtD;AACF;AAEA,IAAa,6BAAb,cAAg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,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"}
@@ -45,7 +45,8 @@ const collect = (leaves) => Result.gen(function* () {
45
45
  data: {
46
46
  format: section.format,
47
47
  functions: Object.create(null)
48
- }
48
+ },
49
+ sources: Object.create(null)
49
50
  };
50
51
  registry.set(key, entry);
51
52
  const description = yield* Result.try({
@@ -57,6 +58,7 @@ const collect = (leaves) => Result.gen(function* () {
57
58
  catch: (cause) => invalid(String(cause))
58
59
  });
59
60
  entry.data.functions[functionPath] = yield* Result.mapError(json(description), (reason) => invalid(`could not describe as JSON: ${reason}`));
61
+ entry.sources[functionPath] = source;
60
62
  }
61
63
  }
62
64
  for (const [name, child] of Object.entries(group.groups)) yield* visit(child, `${path}/${name}`, source);
@@ -66,15 +68,16 @@ const collect = (leaves) => Result.gen(function* () {
66
68
  });
67
69
  /**
68
70
  * Replace the data of each section that has `summarize` with what it returns
69
- * from its matched modules and its functions' descriptions.
71
+ * from its matched modules, its functions' descriptions and their spec files.
70
72
  */
71
73
  const summarize = (registry, modules) => Result.gen(function* () {
72
74
  const summarized = new Map(registry);
73
- for (const [key, { section, data }] of registry) {
75
+ for (const [key, { section, data, sources }] of registry) {
74
76
  if (section.summarize === void 0) continue;
75
77
  const input = {
76
78
  modules: modules.get(key) ?? [],
77
- functions: data.functions
79
+ functions: data.functions,
80
+ sources
78
81
  };
79
82
  const invalid = (reason) => new InvalidManifestSectionError({
80
83
  sectionKey: key,
@@ -1 +1 @@
1
- {"version":3,"file":"ManifestSections.mjs","names":[],"sources":["../src/ManifestSections.ts"],"sourcesContent":["import type { GroupSpec, ManifestSection } from \"@confect/core\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport {\n InvalidDeclarationError,\n InvalidManifestSectionError,\n} from \"./CodegenError.js\";\n\nconst reserved = new Set(\n \"name env http digest __proto__ constructor prototype\".split(\" \"),\n);\nexport const sections = (manifest: Readonly<Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(manifest).filter(([key]) => !reserved.has(key)),\n );\n// Read only property descriptors, through static functions, so no getter,\n// `toJSON` or other method of the input runs before the check and nothing\n// `JSON.stringify` would call, skip or convert passes.\nconst nonJsonPath = (\n value: unknown,\n path = \"$\",\n ancestors: ReadonlyArray<object> = [],\n): string | undefined => {\n if (value === null || [\"string\", \"boolean\"].includes(typeof value))\n return undefined;\n if (typeof value === \"number\")\n return Number.isFinite(value) ? undefined : path;\n if (typeof value !== \"object\" || ancestors.includes(value)) return path;\n const isArray = Array.isArray(value);\n const prototypes = isArray ? [Array.prototype] : [Object.prototype, null];\n if (!prototypes.includes(Object.getPrototypeOf(value))) return path;\n const keys = isArray\n ? Array.from(\n { length: Object.getOwnPropertyDescriptor(value, \"length\")?.value },\n (_, index) => String(index),\n )\n : Reflect.ownKeys(value);\n for (const key of keys) {\n if (typeof key === \"symbol\") return path;\n const at = `${path}[${JSON.stringify(key)}]`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n key === \"__proto__\" ||\n !descriptor?.enumerable ||\n !(\"value\" in descriptor)\n )\n return at;\n const found = nonJsonPath(descriptor.value, at, [...ancestors, value]);\n if (found !== undefined) return found;\n }\n // Every index is an own data property by now, so any other key than `length`\n // is one `JSON.stringify` would drop or call.\n return isArray && Reflect.ownKeys(value).length !== keys.length + 1\n ? path\n : undefined;\n};\nconst json = (value: unknown): Result.Result<unknown, string> => {\n const path = nonJsonPath(value);\n return path === undefined\n ? Result.succeed(JSON.parse(JSON.stringify(value)))\n : Result.fail(`Expected JSON data at ${path}`);\n};\nexport type Registry = Map<\n string,\n {\n section: ManifestSection.Any;\n data: { format: number; functions: Record<string, unknown> };\n }\n>;\nconst hasFormat = (format: number) =>\n Schema.is(Schema.Struct({ format: Schema.Literal(format) }));\ntype Summarized = {\n readonly section: ManifestSection.Any;\n readonly data: { readonly format: number };\n};\n\nexport const collect = (\n leaves: ReadonlyArray<\n Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">\n >,\n) =>\n Result.gen(function* () {\n const registry: Registry = new Map();\n const visit = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ): Result.Result<void, InvalidDeclarationError> =>\n Result.gen(function* () {\n for (const spec of Object.values(group.functions)) {\n const functionPath = `${path}:${spec.name}`;\n for (const { key, section } of spec.manifestSections ?? []) {\n const invalid = (reason: string) =>\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `Manifest section \"${key}\" (${functionPath}): ${reason}`,\n });\n if (reserved.has(key))\n return yield* Result.fail(invalid(\"shadows a built-in key.\"));\n const existing = registry.get(key);\n if (\n existing !== undefined &&\n (existing.section.owner !== section.owner ||\n existing.section.format !== section.format)\n )\n return yield* Result.fail(\n invalid(\n `conflicts between ${existing.section.owner} (format ${existing.section.format}) and ${section.owner} (format ${section.format}).`,\n ),\n );\n const entry = existing ?? {\n section,\n data: {\n format: section.format,\n functions: Object.create(null) as Record<string, unknown>,\n },\n };\n registry.set(key, entry);\n const description = yield* Result.try({\n try: () =>\n section.describe({\n path: functionPath,\n spec,\n middleware: [\n ...group.middlewareSpecs,\n ...spec.middlewareSpecs,\n ],\n }),\n catch: (cause) => invalid(String(cause)),\n });\n entry.data.functions[functionPath] = yield* Result.mapError(\n json(description),\n (reason) => invalid(`could not describe as JSON: ${reason}`),\n );\n }\n }\n for (const [name, child] of Object.entries(group.groups))\n yield* visit(child, `${path}/${name}`, source);\n });\n for (const leaf of leaves)\n yield* visit(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n return registry;\n });\n\n/**\n * Replace the data of each section that has `summarize` with what it returns\n * from its matched modules and its functions' descriptions.\n */\nexport const summarize = (\n registry: Registry,\n modules: ReadonlyMap<string, ManifestSection.GenerateInput[\"modules\"]>,\n) =>\n Result.gen(function* () {\n const summarized = new Map<string, Summarized>(registry);\n for (const [key, { section, data }] of registry) {\n if (section.summarize === undefined) continue;\n const input = {\n modules: modules.get(key) ?? [],\n functions: data.functions,\n };\n const invalid = (reason: string) =>\n new InvalidManifestSectionError({ sectionKey: key, reason });\n const summary = yield* Result.try({\n try: () => section.summarize?.(input),\n catch: (cause) => invalid(`summarize failed: ${String(cause)}`),\n });\n const parsed = yield* Result.mapError(json(summary), (reason) =>\n invalid(`could not summarize as JSON: ${reason}`),\n );\n if (!hasFormat(section.format)(parsed))\n return yield* Result.fail(\n invalid(`summarize must return data with format ${section.format}.`),\n );\n summarized.set(key, { section, data: parsed });\n }\n return summarized;\n });\n\nexport const check = (\n registry: ReadonlyMap<string, Summarized>,\n previous: Readonly<Record<string, unknown>>,\n) => {\n const errors: InvalidManifestSectionError[] = [];\n const notes: string[] = [];\n for (const [key, { section, data }] of registry) {\n try {\n const checked = section.check?.(data, previous[key]);\n if (checked === undefined) continue;\n notes.push(...checked.notes);\n if (checked.errors.length > 0)\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: [...new Set(checked.errors)].join(\"\\n\"),\n }),\n );\n } catch (cause) {\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `check failed: ${String(cause)}`,\n }),\n );\n }\n }\n for (const [key, value] of Object.entries(previous)) {\n if (\n !reserved.has(key) &&\n !registry.has(key) &&\n Predicate.isObjectOrArray(value) &&\n \"functions\" in value &&\n Predicate.isObjectOrArray(value.functions)\n )\n notes.push(\n `Manifest section \"${key}\" no longer has participants. Previous functions: ${Object.keys(value.functions).join(\", \")}.`,\n );\n }\n return { errors, notes };\n};\n"],"mappings":";;;;;AAUA,MAAM,WAAW,IAAI,IACnB,uDAAuD,MAAM,GAAG,CAClE;AACA,MAAa,YAAY,aACvB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,IAAI,GAAG,CAAC,CAC/D;AAIF,MAAM,eACJ,OACA,OAAO,KACP,YAAmC,CAAC,MACb;CACvB,IAAI,UAAU,QAAQ,CAAC,UAAU,SAAS,CAAC,CAAC,SAAS,OAAO,KAAK,GAC/D,OAAO,KAAA;CACT,IAAI,OAAO,UAAU,UACnB,OAAO,OAAO,SAAS,KAAK,IAAI,KAAA,IAAY;CAC9C,IAAI,OAAO,UAAU,YAAY,UAAU,SAAS,KAAK,GAAG,OAAO;CACnE,MAAM,UAAU,MAAM,QAAQ,KAAK;CAEnC,IAAI,EADe,UAAU,CAAC,MAAM,SAAS,IAAI,CAAC,OAAO,WAAW,IAAI,EAAA,CACxD,SAAS,OAAO,eAAe,KAAK,CAAC,GAAG,OAAO;CAC/D,MAAM,OAAO,UACT,MAAM,KACJ,EAAE,QAAQ,OAAO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KACjB,UAAU,gBAAgB,KAAK,KAC/B,eAAe,SACf,UAAU,gBAAgB,MAAM,SAAS,GAEzC,MAAM,KACJ,qBAAqB,IAAI,oDAAoD,OAAO,KAAK,MAAM,SAAS,CAAC,CAAC,KAAK,IAAI,EAAE,EACvH;CAEJ,OAAO;EAAE;EAAQ;CAAM;AACzB"}
1
+ {"version":3,"file":"ManifestSections.mjs","names":[],"sources":["../src/ManifestSections.ts"],"sourcesContent":["import type { GroupSpec, ManifestSection } from \"@confect/core\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport {\n InvalidDeclarationError,\n InvalidManifestSectionError,\n} from \"./CodegenError.js\";\n\nconst reserved = new Set(\n \"name env http digest __proto__ constructor prototype\".split(\" \"),\n);\nexport const sections = (manifest: Readonly<Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(manifest).filter(([key]) => !reserved.has(key)),\n );\n// Read only property descriptors, through static functions, so no getter,\n// `toJSON` or other method of the input runs before the check and nothing\n// `JSON.stringify` would call, skip or convert passes.\nconst nonJsonPath = (\n value: unknown,\n path = \"$\",\n ancestors: ReadonlyArray<object> = [],\n): string | undefined => {\n if (value === null || [\"string\", \"boolean\"].includes(typeof value))\n return undefined;\n if (typeof value === \"number\")\n return Number.isFinite(value) ? undefined : path;\n if (typeof value !== \"object\" || ancestors.includes(value)) return path;\n const isArray = Array.isArray(value);\n const prototypes = isArray ? [Array.prototype] : [Object.prototype, null];\n if (!prototypes.includes(Object.getPrototypeOf(value))) return path;\n const keys = isArray\n ? Array.from(\n { length: Object.getOwnPropertyDescriptor(value, \"length\")?.value },\n (_, index) => String(index),\n )\n : Reflect.ownKeys(value);\n for (const key of keys) {\n if (typeof key === \"symbol\") return path;\n const at = `${path}[${JSON.stringify(key)}]`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n key === \"__proto__\" ||\n !descriptor?.enumerable ||\n !(\"value\" in descriptor)\n )\n return at;\n const found = nonJsonPath(descriptor.value, at, [...ancestors, value]);\n if (found !== undefined) return found;\n }\n // Every index is an own data property by now, so any other key than `length`\n // is one `JSON.stringify` would drop or call.\n return isArray && Reflect.ownKeys(value).length !== keys.length + 1\n ? path\n : undefined;\n};\nconst json = (value: unknown): Result.Result<unknown, string> => {\n const path = nonJsonPath(value);\n return path === undefined\n ? Result.succeed(JSON.parse(JSON.stringify(value)))\n : Result.fail(`Expected JSON data at ${path}`);\n};\nexport type Registry = Map<\n string,\n {\n section: ManifestSection.Any;\n data: { format: number; functions: Record<string, unknown> };\n sources: Record<string, string>;\n }\n>;\nconst hasFormat = (format: number) =>\n Schema.is(Schema.Struct({ format: Schema.Literal(format) }));\ntype Summarized = {\n readonly section: ManifestSection.Any;\n readonly data: { readonly format: number };\n};\n\nexport const collect = (\n leaves: ReadonlyArray<\n Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">\n >,\n) =>\n Result.gen(function* () {\n const registry: Registry = new Map();\n const visit = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ): Result.Result<void, InvalidDeclarationError> =>\n Result.gen(function* () {\n for (const spec of Object.values(group.functions)) {\n const functionPath = `${path}:${spec.name}`;\n for (const { key, section } of spec.manifestSections ?? []) {\n const invalid = (reason: string) =>\n new InvalidDeclarationError({\n declarationPath: `confect/${source}`,\n reason: `Manifest section \"${key}\" (${functionPath}): ${reason}`,\n });\n if (reserved.has(key))\n return yield* Result.fail(invalid(\"shadows a built-in key.\"));\n const existing = registry.get(key);\n if (\n existing !== undefined &&\n (existing.section.owner !== section.owner ||\n existing.section.format !== section.format)\n )\n return yield* Result.fail(\n invalid(\n `conflicts between ${existing.section.owner} (format ${existing.section.format}) and ${section.owner} (format ${section.format}).`,\n ),\n );\n const entry = existing ?? {\n section,\n data: {\n format: section.format,\n functions: Object.create(null) as Record<string, unknown>,\n },\n sources: Object.create(null) as Record<string, string>,\n };\n registry.set(key, entry);\n const description = yield* Result.try({\n try: () =>\n section.describe({\n path: functionPath,\n spec,\n middleware: [\n ...group.middlewareSpecs,\n ...spec.middlewareSpecs,\n ],\n }),\n catch: (cause) => invalid(String(cause)),\n });\n entry.data.functions[functionPath] = yield* Result.mapError(\n json(description),\n (reason) => invalid(`could not describe as JSON: ${reason}`),\n );\n entry.sources[functionPath] = source;\n }\n }\n for (const [name, child] of Object.entries(group.groups))\n yield* visit(child, `${path}/${name}`, source);\n });\n for (const leaf of leaves)\n yield* visit(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n return registry;\n });\n\n/**\n * Replace the data of each section that has `summarize` with what it returns\n * from its matched modules, its functions' descriptions and their spec files.\n */\nexport const summarize = (\n registry: Registry,\n modules: ReadonlyMap<string, ManifestSection.GenerateInput[\"modules\"]>,\n) =>\n Result.gen(function* () {\n const summarized = new Map<string, Summarized>(registry);\n for (const [key, { section, data, sources }] of registry) {\n if (section.summarize === undefined) continue;\n const input = {\n modules: modules.get(key) ?? [],\n functions: data.functions,\n sources,\n };\n const invalid = (reason: string) =>\n new InvalidManifestSectionError({ sectionKey: key, reason });\n const summary = yield* Result.try({\n try: () => section.summarize?.(input),\n catch: (cause) => invalid(`summarize failed: ${String(cause)}`),\n });\n const parsed = yield* Result.mapError(json(summary), (reason) =>\n invalid(`could not summarize as JSON: ${reason}`),\n );\n if (!hasFormat(section.format)(parsed))\n return yield* Result.fail(\n invalid(`summarize must return data with format ${section.format}.`),\n );\n summarized.set(key, { section, data: parsed });\n }\n return summarized;\n });\n\nexport const check = (\n registry: ReadonlyMap<string, Summarized>,\n previous: Readonly<Record<string, unknown>>,\n) => {\n const errors: InvalidManifestSectionError[] = [];\n const notes: string[] = [];\n for (const [key, { section, data }] of registry) {\n try {\n const checked = section.check?.(data, previous[key]);\n if (checked === undefined) continue;\n notes.push(...checked.notes);\n if (checked.errors.length > 0)\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: [...new Set(checked.errors)].join(\"\\n\"),\n }),\n );\n } catch (cause) {\n errors.push(\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `check failed: ${String(cause)}`,\n }),\n );\n }\n }\n for (const [key, value] of Object.entries(previous)) {\n if (\n !reserved.has(key) &&\n !registry.has(key) &&\n Predicate.isObjectOrArray(value) &&\n \"functions\" in value &&\n Predicate.isObjectOrArray(value.functions)\n )\n notes.push(\n `Manifest section \"${key}\" no longer has participants. Previous functions: ${Object.keys(value.functions).join(\", \")}.`,\n );\n }\n return { errors, notes };\n};\n"],"mappings":";;;;;AAUA,MAAM,WAAW,IAAI,IACnB,uDAAuD,MAAM,GAAG,CAClE;AACA,MAAa,YAAY,aACvB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,IAAI,GAAG,CAAC,CAC/D;AAIF,MAAM,eACJ,OACA,OAAO,KACP,YAAmC,CAAC,MACb;CACvB,IAAI,UAAU,QAAQ,CAAC,UAAU,SAAS,CAAC,CAAC,SAAS,OAAO,KAAK,GAC/D,OAAO,KAAA;CACT,IAAI,OAAO,UAAU,UACnB,OAAO,OAAO,SAAS,KAAK,IAAI,KAAA,IAAY;CAC9C,IAAI,OAAO,UAAU,YAAY,UAAU,SAAS,KAAK,GAAG,OAAO;CACnE,MAAM,UAAU,MAAM,QAAQ,KAAK;CAEnC,IAAI,EADe,UAAU,CAAC,MAAM,SAAS,IAAI,CAAC,OAAO,WAAW,IAAI,EAAA,CACxD,SAAS,OAAO,eAAe,KAAK,CAAC,GAAG,OAAO;CAC/D,MAAM,OAAO,UACT,MAAM,KACJ,EAAE,QAAQ,OAAO,yBAAyB,OAAO,QAAQ,CAAC,EAAE,MAAM,IACjE,GAAG,UAAU,OAAO,KAAK,CAC5B,IACA,QAAQ,QAAQ,KAAK;CACzB,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,QAAQ,UAAU,OAAO;EACpC,MAAM,KAAK,GAAG,KAAK,GA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,CAAC,CAAC,KAAK,IAAI,EAAE,EACvH;CAEJ,OAAO;EAAE;EAAQ;CAAM;AACzB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gaganref/confect-cli",
3
- "version": "10.3.1-fork.71",
3
+ "version": "10.3.1-fork.73",
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.71",
13
- "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.71",
12
+ "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.73",
13
+ "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.73",
14
14
  "@effect/platform-node-shared": ">=4.0.4 <4.1.0",
15
15
  "effect": ">=4.0.4 <4.1.0"
16
16
  },