@gaganref/confect-cli 10.6.0-fork.11 → 10.6.0-fork.12

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.
@@ -45,7 +45,7 @@ const getEntrypoints = Effect.gen(function* () {
45
45
  });
46
46
  });
47
47
  const tokenize = (source, modulePath, path) => {
48
- const token = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[$A-Z_a-z][$\w]*|[{}()[\].,:;=]/y;
48
+ const token = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[$A-Z_a-z][$\w]*|=>|[{}()[\].,:;=<>]/y;
49
49
  const tokens = [];
50
50
  while (token.lastIndex < source.length) {
51
51
  const match = token.exec(source);
@@ -91,9 +91,20 @@ const assertOwnedEntrypoints = Effect.gen(function* () {
91
91
  runtimeImportPath: yield* importFromConvex("runtime.ts")
92
92
  })
93
93
  ];
94
- const optional = /* @__PURE__ */ new Map([["http.ts", Array.flatMap(httpTemplates, (template) => [template, legacyRouter(template)])], ["crons.ts", [yield* crons({ cronsImportPath: yield* importFromConvex("crons.ts") })]]]);
94
+ const optional = /* @__PURE__ */ new Map([["http.ts", Array.flatMap(httpTemplates, (template) => [template, legacyRouter(template)])]]);
95
95
  const written2 = yield* written;
96
- const sectionImports = new Set(Array.map(written2, (file) => quote(path.join(confect, "_generated", path.basename(file, ".ts")))));
96
+ const sectionImports = new Map(Array.map(written2, (file) => [quote(path.join(confect, "_generated", path.basename(file, ".ts"))), file]));
97
+ const cronsShapes = Effect.fnUntraced(function* (tokens) {
98
+ const wrapped = Array.flatMap(tokens, (token, index) => {
99
+ const file = sectionImports.get(token);
100
+ return tokens[index - 1] === "from" && file !== void 0 ? [file] : [];
101
+ });
102
+ if (new Set(wrapped).size !== wrapped.length) return [];
103
+ return [yield* crons({
104
+ cronsImportPath: yield* importFromConvex("crons.ts"),
105
+ sectionImportPaths: yield* Effect.forEach(wrapped, (file) => importFromConvex(`_generated/${file}`))
106
+ })];
107
+ });
97
108
  const withoutSectionImports = (tokens) => tokens[0] === "import" && sectionImports.has(tokens[1] ?? "") ? withoutSectionImports(tokens.slice(tokens[2] === ";" ? 3 : 2)) : tokens;
98
109
  const refused = [];
99
110
  for (const relative of yield* getEntrypoints) {
@@ -102,7 +113,7 @@ const assertOwnedEntrypoints = Effect.gen(function* () {
102
113
  if (relative === DEPLOY_MODULE && isGenerated(contents, [])) continue;
103
114
  const tokens = tokenize(contents, absolute, path);
104
115
  if (tokens !== void 0) {
105
- const shapes = optional.get(relative);
116
+ const shapes = relative === "crons.ts" ? yield* cronsShapes(tokens) : optional.get(relative);
106
117
  if (shapes !== void 0 && Array.some(shapes, (template) => matchesShape(relative === "http.ts" ? withoutSectionImports(tokens) : tokens, tokenize(template, absolute, path)))) continue;
107
118
  if (path.extname(relative) === ".ts") {
108
119
  const names = Array.flatMap(tokens, (token, index) => token === "export" && tokens[index + 1] === "const" ? [tokens[index + 2]] : []);
@@ -1 +1 @@
1
- {"version":3,"file":"FunctionModule.mjs","names":["templates.http","templates.declaredHttp","templates.crons","SectionFiles.written","Declaration.isGenerated","GroupPath.fromGroupModulePath","GroupPath.modulePath","modulePath","GenerationSnapshot.plan","GenerationSnapshot.functionPaths"],"sources":["../src/FunctionModule.ts"],"sourcesContent":["import * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as String from \"effect/String\";\nimport { UnownedConvexEntrypointError } from \"./CodegenError.js\";\nimport * as Declaration from \"./Declaration.js\";\nimport * as SectionFiles from \"./SectionFiles.js\";\nimport * as templates from \"./templates.js\";\nimport * as GenerationSnapshot from \"./GenerationSnapshot.js\";\nimport * as GroupPath from \"./GroupPath.js\";\nimport * as GroupPaths from \"./GroupPaths.js\";\nimport { CodeBlockWriter } from \"./CodeBlockWriter.js\";\nimport { logFileAdded, logFileModified, logFileRemoved } from \"./log.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport {\n removePathIfExists,\n toModuleImportPath,\n toPosixPath,\n} from \"./utils.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as Option from \"effect/Option\";\nimport { quote } from \"./Json.js\";\n\nconst RESERVED_CONVEX_TS_FILE_NAMES = new Set([\n \"schema.ts\",\n \"http.ts\",\n \"crons.ts\",\n \"auth.config.ts\",\n \"convex.config.ts\",\n]);\n\n// Only the root module is codegen's; a nested group may take the name.\nconst DEPLOY_MODULE = \"confectDeploy.ts\";\n\n// Keep ownership and removal aligned with Convex's bundler entryPoints filter.\nconst getEntrypoints = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convex = yield* ConvexDirectory.get;\n const files = yield* fs.readDirectory(convex, { recursive: true });\n const components = pipe(\n files,\n Array.filter(\n (file) =>\n path.basename(file) === \"convex.config.ts\" &&\n path.dirname(file) !== \".\",\n ),\n Array.map((file) => path.dirname(file) + path.sep),\n );\n return Array.filter(files, (file) => {\n const base = path.basename(file);\n return (\n !pipe(file, String.startsWith(\"_generated\" + path.sep)) &&\n !Array.some(components, (component) =>\n pipe(file, String.startsWith(component)),\n ) &&\n /\\.(?:js|mjs|cjs|ts|tsx|mts|cts|jsx)$/.test(base) &&\n !pipe(base, String.startsWith(\".\")) &&\n !pipe(base, String.startsWith(\"#\")) &&\n pipe(\n base,\n String.match(/\\./g),\n Option.match({ onNone: () => 0, onSome: (dots) => dots.length }),\n ) === 1 &&\n base !== \"schema.ts\" &&\n base !== \"schema.js\" &&\n !pipe(file, String.includes(\" \"))\n );\n });\n});\n\nconst tokenize = (\n source: string,\n modulePath: string,\n path: Path.Path,\n): string[] | undefined => {\n const token =\n /\\s+|\\/\\/[^\\r\\n]*|\\/\\*[\\s\\S]*?\\*\\/|\"(?:\\\\.|[^\"\\\\\\r\\n])*\"|'(?:\\\\.|[^'\\\\\\r\\n])*'|[$A-Z_a-z][$\\w]*|[{}()[\\].,:;=]/y;\n const tokens: string[] = [];\n while (token.lastIndex < source.length) {\n const match = token.exec(source);\n if (match === null) return undefined;\n const value = match[0];\n if (/^\\s|^\\//.test(value)) continue;\n if (\n pipe(value, String.startsWith('\"')) ||\n pipe(value, String.startsWith(\"'\"))\n ) {\n const literal = pipe(value, String.slice(1, -1));\n tokens.push(\n quote(\n pipe(literal, String.startsWith(\".\"))\n ? path.resolve(\n path.dirname(modulePath),\n pipe(literal, String.replace(/\\.js$/, \"\")),\n )\n : literal,\n ),\n );\n } else tokens.push(value);\n }\n return tokens;\n};\n\nconst matchesShape = (\n actual: readonly string[],\n expected: readonly string[],\n) => {\n let index = 0;\n for (const token of expected) {\n if (token === \";\" && actual[index] !== \";\") continue;\n if (actual[index] === \",\" && (token === \"}\" || token === \")\")) index++;\n if (actual[index++] !== token) return false;\n }\n return index === actual.length;\n};\n\n// Before the schema-first HttpRouter.make, codegen emitted forSchema; codegen\n// owns that output so it can rewrite it.\nconst legacyRouter = String.replace(\n \"HttpRouter.make(schema, http.routes, \",\n \"HttpRouter.forSchema(schema)(http.routes, \",\n);\n\n/**\n * @internal\n */\nexport const assertOwnedEntrypoints = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convex = yield* ConvexDirectory.get;\n const confect = yield* ConfectDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n const importFromConvex = (file: string) =>\n toModuleImportPath(path.relative(convex, path.join(confect, file)));\n const httpTemplates = [\n yield* templates.http({\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n }),\n yield* templates.declaredHttp({\n schemaImportPath: yield* importFromConvex(\"_generated/schema.ts\"),\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n }),\n yield* templates.declaredHttp({\n schemaImportPath: yield* importFromConvex(\"_generated/schema.ts\"),\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n runtimeImportPath: yield* importFromConvex(\"runtime.ts\"),\n }),\n ];\n const optional = new Map([\n [\n \"http.ts\",\n Array.flatMap(httpTemplates, (template) => [\n template,\n legacyRouter(template),\n ]),\n ],\n [\n \"crons.ts\",\n [\n yield* templates.crons({\n cronsImportPath: yield* importFromConvex(\"crons.ts\"),\n }),\n ],\n ],\n ]);\n const written2 = yield* SectionFiles.written;\n // The declared HTTP router first imports each file a manifest section wrote.\n const sectionImports = new Set(\n Array.map(written2, (file) =>\n quote(path.join(confect, \"_generated\", path.basename(file, \".ts\"))),\n ),\n );\n const withoutSectionImports = (\n tokens: ReadonlyArray<string>,\n ): ReadonlyArray<string> =>\n tokens[0] === \"import\" && sectionImports.has(tokens[1] ?? \"\")\n ? withoutSectionImports(tokens.slice(tokens[2] === \";\" ? 3 : 2))\n : tokens;\n const refused: string[] = [];\n for (const relative of yield* getEntrypoints) {\n const absolute = path.join(convex, relative);\n const contents = yield* fs.readFileString(absolute);\n if (relative === DEPLOY_MODULE && Declaration.isGenerated(contents, []))\n continue;\n const tokens = tokenize(contents, absolute, path);\n if (tokens !== undefined) {\n const shapes = optional.get(relative);\n if (\n shapes !== undefined &&\n Array.some(shapes, (template) =>\n matchesShape(\n relative === \"http.ts\" ? withoutSectionImports(tokens) : tokens,\n tokenize(template, absolute, path)!,\n ),\n )\n )\n continue;\n if (path.extname(relative) === \".ts\") {\n const names = Array.flatMap(tokens, (token, index) =>\n token === \"export\" && tokens[index + 1] === \"const\"\n ? [tokens[index + 2]!]\n : [],\n );\n const group = yield* GroupPath.fromGroupModulePath(relative);\n const reusesContext = names.includes(\"experimental_reuseContext\");\n const functionNames = Array.filter(\n names,\n (name) => name !== \"experimental_reuseContext\",\n );\n const template = yield* render({\n functionNames,\n registeredFunctionsImportPath:\n yield* registeredFunctionsImportPathForGroup(group, absolute),\n useNode: tokens[0] === '\"use node\"',\n experimental_reuseContext: reusesContext,\n });\n if (\n functionNames.length > 0 &&\n new Set(functionNames).size === functionNames.length &&\n matchesShape(tokens, tokenize(template, absolute, path)!)\n )\n continue;\n }\n }\n refused.push(toPosixPath(path, path.relative(projectRoot, absolute)));\n }\n if (refused.length > 0)\n return yield* UnownedConvexEntrypointError.make({\n filePaths: refused.sort(),\n });\n});\n\nexport const render = ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: Parameters<typeof renderEffect>[0]) =>\n renderEffect({\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n experimental_reuseContext,\n });\n\nconst renderEffect = Effect.fnUntraced(function* ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: {\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n experimental_reuseContext?: boolean;\n}) {\n const cbw = new CodeBlockWriter({ indentNumberOfSpaces: 2 });\n\n if (useNode) {\n yield* cbw.writeLine(`\"use node\";`);\n yield* cbw.blankLine();\n }\n\n yield* cbw.writeLine(\n `import registeredFunctions from \"${registeredFunctionsImportPath}\";`,\n );\n yield* cbw.newLine();\n if (experimental_reuseContext) {\n yield* cbw.writeLine(\"export const experimental_reuseContext = true;\");\n yield* cbw.newLine();\n }\n yield* Effect.forEach(functionNames, (name) =>\n cbw.writeLine(`export const ${name} = registeredFunctions.${name};`),\n );\n\n return yield* cbw.toString();\n});\n\n/**\n * @internal\n */\nexport const generateGroupModule = ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: Parameters<typeof generateGroupModuleEffect>[0]) =>\n generateGroupModuleEffect({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n experimental_reuseContext,\n });\n\nconst generateGroupModuleEffect = Effect.fnUntraced(function* ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: {\n groupPath: GroupPath.GroupPath;\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n experimental_reuseContext?: boolean;\n}) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n const directoryPath = path.dirname(modulePath);\n if (!(yield* fs.exists(directoryPath))) {\n yield* fs.makeDirectory(directoryPath, { recursive: true });\n }\n\n const functionsContentsString = yield* render({\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n experimental_reuseContext,\n });\n\n if (!(yield* fs.exists(modulePath))) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Added\" as const;\n }\n const existing = yield* fs.readFileString(modulePath);\n if (existing !== functionsContentsString) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Modified\" as const;\n }\n return \"Unchanged\" as const;\n});\n\n/**\n * Compute the module import specifier (relative to `modulePath`) for a group's\n * registry file under `confect/_generated/registeredFunctions/`. The registry\n * path mirrors the group's path one-to-one (see\n * `registeredFunctionsRelativePath` in `LeafModule.ts`) for both Convex and\n * Node groups.\n *\n * @internal\n */\nexport const registeredFunctionsImportPathForGroup = Effect.fnUntraced(\n function* (groupPath: GroupPath.GroupPath, modulePath: string) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const registeredFunctionsPath =\n path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n ...groupPath.pathSegments,\n ) + \".ts\";\n\n return yield* toModuleImportPath(\n path.relative(path.dirname(modulePath), registeredFunctionsPath),\n );\n },\n);\n\nconst logGroupPaths = Effect.fnUntraced(function* <R>(\n groupPaths: GroupPaths.GroupPaths,\n logFn: (fullPath: string) => Effect.Effect<void, never, R>,\n): Effect.fn.Return<void, never, R | Path.Path | ConvexDirectory> {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.forEach(\n groupPaths,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n const relativeModulePath = yield* GroupPath.modulePath(gp);\n yield* logFn(path.join(convexDirectory, relativeModulePath));\n }),\n );\n});\n\n/**\n * @internal\n */\nexport const generateFunctions = Effect.fnUntraced(function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n) {\n const groupPathsFromFs = yield* getGroupPathsFromFs;\n yield* applyFunctionPlan(GenerationSnapshot.plan(snapshot, groupPathsFromFs));\n return GenerationSnapshot.functionPaths(snapshot);\n});\n\n/**\n * @internal\n */\nexport const applyFunctionPlan = Effect.fnUntraced(function* (\n plan: GenerationSnapshot.ModulePlan,\n) {\n const removed = GroupPaths.GroupPaths.make(\n HashSet.fromIterable(plan.removed),\n );\n yield* removeGroups(removed);\n yield* logGroupPaths(removed, logFileRemoved);\n yield* writeGroups(plan.changed);\n});\n\nconst getGroupPathsFromFs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const allConvexPaths = yield* getEntrypoints;\n const groupPathArray = yield* pipe(\n allConvexPaths,\n Array.filter(\n (convexPath) =>\n path.extname(convexPath) === \".ts\" &&\n !RESERVED_CONVEX_TS_FILE_NAMES.has(path.basename(convexPath)) &&\n convexPath !== DEPLOY_MODULE,\n ),\n Effect.forEach((groupModulePath) =>\n GroupPath.fromGroupModulePath(groupModulePath),\n ),\n );\n return GroupPaths.GroupPaths.make(HashSet.fromIterable(groupPathArray));\n});\n\n/**\n * @internal\n */\nexport const removeGroups = Effect.fnUntraced(function* (\n groupPaths: GroupPaths.GroupPaths,\n) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.all(\n HashSet.map(groupPaths, (groupPath) =>\n Effect.gen(function* () {\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n yield* Effect.logDebug(`Removing group '${relativeModulePath}'...`);\n\n yield* removePathIfExists(modulePath);\n yield* Effect.logDebug(`Group '${relativeModulePath}' removed`);\n }),\n ),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * @internal\n */\nexport const writeGroups = (\n groups: ReadonlyArray<GenerationSnapshot.GroupSummary>,\n) =>\n Effect.forEach(\n groups,\n Effect.fnUntraced(function* (group: GenerationSnapshot.GroupSummary) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const relativeModulePath = yield* GroupPath.modulePath(group.path);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n const registeredFunctionsImportPath =\n yield* registeredFunctionsImportPathForGroup(group.path, modulePath);\n const change = yield* generateGroupModule({\n groupPath: group.path,\n functionNames: group.functionNames,\n registeredFunctionsImportPath,\n useNode: group.runtime === \"Node\",\n experimental_reuseContext: group.experimental_reuseContext === true,\n });\n yield* Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(modulePath)),\n Match.when(\"Modified\", () => logFileModified(modulePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n );\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,gDAAgC,IAAI,IAAI;CAC5C;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,gBAAgB;AAGtB,MAAM,iBAAiB,OAAO,IAAI,aAAa;CAC7C,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,SAAS,OAAO,gBAAgB;CACtC,MAAM,QAAQ,OAAO,GAAG,cAAc,QAAQ,EAAE,WAAW,KAAK,CAAC;CACjE,MAAM,aAAa,KACjB,OACA,MAAM,QACH,SACC,KAAK,SAAS,IAAI,MAAM,sBACxB,KAAK,QAAQ,IAAI,MAAM,GAC3B,GACA,MAAM,KAAK,SAAS,KAAK,QAAQ,IAAI,IAAI,KAAK,GAAG,CACnD;CACA,OAAO,MAAM,OAAO,QAAQ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jE,CAAC;CACD,OAAO,MAAM,MAAM,MAAM,CAAC,CAAC,KACzB,MAAM,KAAK,eAAe,aAAaA,YAAU,CAAC,GAClD,MAAM,KAAK,kBAAkB,gBAAgBA,YAAU,CAAC,GACxD,MAAM,KAAK,mBAAmB,OAAO,IAAI,GACzC,MAAM,UACR;AACF,CAAC,CACH"}
1
+ {"version":3,"file":"FunctionModule.mjs","names":["templates.http","templates.declaredHttp","SectionFiles.written","templates.crons","Declaration.isGenerated","GroupPath.fromGroupModulePath","GroupPath.modulePath","modulePath","GenerationSnapshot.plan","GenerationSnapshot.functionPaths"],"sources":["../src/FunctionModule.ts"],"sourcesContent":["import * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as String from \"effect/String\";\nimport { UnownedConvexEntrypointError } from \"./CodegenError.js\";\nimport * as Declaration from \"./Declaration.js\";\nimport * as SectionFiles from \"./SectionFiles.js\";\nimport * as templates from \"./templates.js\";\nimport * as GenerationSnapshot from \"./GenerationSnapshot.js\";\nimport * as GroupPath from \"./GroupPath.js\";\nimport * as GroupPaths from \"./GroupPaths.js\";\nimport { CodeBlockWriter } from \"./CodeBlockWriter.js\";\nimport { logFileAdded, logFileModified, logFileRemoved } from \"./log.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport {\n removePathIfExists,\n toModuleImportPath,\n toPosixPath,\n} from \"./utils.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as Option from \"effect/Option\";\nimport { quote } from \"./Json.js\";\n\nconst RESERVED_CONVEX_TS_FILE_NAMES = new Set([\n \"schema.ts\",\n \"http.ts\",\n \"crons.ts\",\n \"auth.config.ts\",\n \"convex.config.ts\",\n]);\n\n// Only the root module is codegen's; a nested group may take the name.\nconst DEPLOY_MODULE = \"confectDeploy.ts\";\n\n// Keep ownership and removal aligned with Convex's bundler entryPoints filter.\nconst getEntrypoints = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convex = yield* ConvexDirectory.get;\n const files = yield* fs.readDirectory(convex, { recursive: true });\n const components = pipe(\n files,\n Array.filter(\n (file) =>\n path.basename(file) === \"convex.config.ts\" &&\n path.dirname(file) !== \".\",\n ),\n Array.map((file) => path.dirname(file) + path.sep),\n );\n return Array.filter(files, (file) => {\n const base = path.basename(file);\n return (\n !pipe(file, String.startsWith(\"_generated\" + path.sep)) &&\n !Array.some(components, (component) =>\n pipe(file, String.startsWith(component)),\n ) &&\n /\\.(?:js|mjs|cjs|ts|tsx|mts|cts|jsx)$/.test(base) &&\n !pipe(base, String.startsWith(\".\")) &&\n !pipe(base, String.startsWith(\"#\")) &&\n pipe(\n base,\n String.match(/\\./g),\n Option.match({ onNone: () => 0, onSome: (dots) => dots.length }),\n ) === 1 &&\n base !== \"schema.ts\" &&\n base !== \"schema.js\" &&\n !pipe(file, String.includes(\" \"))\n );\n });\n});\n\nconst tokenize = (\n source: string,\n modulePath: string,\n path: Path.Path,\n): string[] | undefined => {\n const token =\n /\\s+|\\/\\/[^\\r\\n]*|\\/\\*[\\s\\S]*?\\*\\/|\"(?:\\\\.|[^\"\\\\\\r\\n])*\"|'(?:\\\\.|[^'\\\\\\r\\n])*'|[$A-Z_a-z][$\\w]*|=>|[{}()[\\].,:;=<>]/y;\n const tokens: string[] = [];\n while (token.lastIndex < source.length) {\n const match = token.exec(source);\n if (match === null) return undefined;\n const value = match[0];\n if (/^\\s|^\\//.test(value)) continue;\n if (\n pipe(value, String.startsWith('\"')) ||\n pipe(value, String.startsWith(\"'\"))\n ) {\n const literal = pipe(value, String.slice(1, -1));\n tokens.push(\n quote(\n pipe(literal, String.startsWith(\".\"))\n ? path.resolve(\n path.dirname(modulePath),\n pipe(literal, String.replace(/\\.js$/, \"\")),\n )\n : literal,\n ),\n );\n } else tokens.push(value);\n }\n return tokens;\n};\n\nconst matchesShape = (\n actual: readonly string[],\n expected: readonly string[],\n) => {\n let index = 0;\n for (const token of expected) {\n if (token === \";\" && actual[index] !== \";\") continue;\n if (actual[index] === \",\" && (token === \"}\" || token === \")\")) index++;\n if (actual[index++] !== token) return false;\n }\n return index === actual.length;\n};\n\n// Before the schema-first HttpRouter.make, codegen emitted forSchema; codegen\n// owns that output so it can rewrite it.\nconst legacyRouter = String.replace(\n \"HttpRouter.make(schema, http.routes, \",\n \"HttpRouter.forSchema(schema)(http.routes, \",\n);\n\n/**\n * @internal\n */\nexport const assertOwnedEntrypoints = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convex = yield* ConvexDirectory.get;\n const confect = yield* ConfectDirectory.get;\n const projectRoot = yield* ProjectRoot.get;\n const importFromConvex = (file: string) =>\n toModuleImportPath(path.relative(convex, path.join(confect, file)));\n const httpTemplates = [\n yield* templates.http({\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n }),\n yield* templates.declaredHttp({\n schemaImportPath: yield* importFromConvex(\"_generated/schema.ts\"),\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n }),\n yield* templates.declaredHttp({\n schemaImportPath: yield* importFromConvex(\"_generated/schema.ts\"),\n httpImportPath: yield* importFromConvex(\"http.ts\"),\n runtimeImportPath: yield* importFromConvex(\"runtime.ts\"),\n }),\n ];\n const optional = new Map([\n [\n \"http.ts\",\n Array.flatMap(httpTemplates, (template) => [\n template,\n legacyRouter(template),\n ]),\n ],\n ]);\n const written2 = yield* SectionFiles.written;\n // The declared HTTP router first imports each file a manifest section wrote.\n const sectionImports = new Map(\n Array.map(written2, (file) => [\n quote(path.join(confect, \"_generated\", path.basename(file, \".ts\"))),\n file,\n ]),\n );\n // This check only keeps codegen from overwriting hand-written code, and later\n // in the same run codegen writes `convex/crons.ts` with exactly this run's\n // wrappers. So the crons template holds nothing to lose when it wraps\n // distinct files a section wrote, in any order, even ones that no longer\n // wrap. The same-run rewrite holds for declared backends; an undeclared\n // backend without `confect/crons.ts` keeps a leftover entry, as before.\n const cronsShapes = Effect.fnUntraced(function* (\n tokens: ReadonlyArray<string>,\n ) {\n const wrapped = Array.flatMap(tokens, (token, index) => {\n const file = sectionImports.get(token);\n return tokens[index - 1] === \"from\" && file !== undefined ? [file] : [];\n });\n if (new Set(wrapped).size !== wrapped.length) return [];\n return [\n yield* templates.crons({\n cronsImportPath: yield* importFromConvex(\"crons.ts\"),\n sectionImportPaths: yield* Effect.forEach(wrapped, (file) =>\n importFromConvex(`_generated/${file}`),\n ),\n }),\n ];\n });\n const withoutSectionImports = (\n tokens: ReadonlyArray<string>,\n ): ReadonlyArray<string> =>\n tokens[0] === \"import\" && sectionImports.has(tokens[1] ?? \"\")\n ? withoutSectionImports(tokens.slice(tokens[2] === \";\" ? 3 : 2))\n : tokens;\n const refused: string[] = [];\n for (const relative of yield* getEntrypoints) {\n const absolute = path.join(convex, relative);\n const contents = yield* fs.readFileString(absolute);\n if (relative === DEPLOY_MODULE && Declaration.isGenerated(contents, []))\n continue;\n const tokens = tokenize(contents, absolute, path);\n if (tokens !== undefined) {\n const shapes =\n relative === \"crons.ts\"\n ? yield* cronsShapes(tokens)\n : optional.get(relative);\n if (\n shapes !== undefined &&\n Array.some(shapes, (template) =>\n matchesShape(\n relative === \"http.ts\" ? withoutSectionImports(tokens) : tokens,\n tokenize(template, absolute, path)!,\n ),\n )\n )\n continue;\n if (path.extname(relative) === \".ts\") {\n const names = Array.flatMap(tokens, (token, index) =>\n token === \"export\" && tokens[index + 1] === \"const\"\n ? [tokens[index + 2]!]\n : [],\n );\n const group = yield* GroupPath.fromGroupModulePath(relative);\n const reusesContext = names.includes(\"experimental_reuseContext\");\n const functionNames = Array.filter(\n names,\n (name) => name !== \"experimental_reuseContext\",\n );\n const template = yield* render({\n functionNames,\n registeredFunctionsImportPath:\n yield* registeredFunctionsImportPathForGroup(group, absolute),\n useNode: tokens[0] === '\"use node\"',\n experimental_reuseContext: reusesContext,\n });\n if (\n functionNames.length > 0 &&\n new Set(functionNames).size === functionNames.length &&\n matchesShape(tokens, tokenize(template, absolute, path)!)\n )\n continue;\n }\n }\n refused.push(toPosixPath(path, path.relative(projectRoot, absolute)));\n }\n if (refused.length > 0)\n return yield* UnownedConvexEntrypointError.make({\n filePaths: refused.sort(),\n });\n});\n\nexport const render = ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: Parameters<typeof renderEffect>[0]) =>\n renderEffect({\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n experimental_reuseContext,\n });\n\nconst renderEffect = Effect.fnUntraced(function* ({\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: {\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n experimental_reuseContext?: boolean;\n}) {\n const cbw = new CodeBlockWriter({ indentNumberOfSpaces: 2 });\n\n if (useNode) {\n yield* cbw.writeLine(`\"use node\";`);\n yield* cbw.blankLine();\n }\n\n yield* cbw.writeLine(\n `import registeredFunctions from \"${registeredFunctionsImportPath}\";`,\n );\n yield* cbw.newLine();\n if (experimental_reuseContext) {\n yield* cbw.writeLine(\"export const experimental_reuseContext = true;\");\n yield* cbw.newLine();\n }\n yield* Effect.forEach(functionNames, (name) =>\n cbw.writeLine(`export const ${name} = registeredFunctions.${name};`),\n );\n\n return yield* cbw.toString();\n});\n\n/**\n * @internal\n */\nexport const generateGroupModule = ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: Parameters<typeof generateGroupModuleEffect>[0]) =>\n generateGroupModuleEffect({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n experimental_reuseContext,\n });\n\nconst generateGroupModuleEffect = Effect.fnUntraced(function* ({\n groupPath,\n functionNames,\n registeredFunctionsImportPath,\n useNode = false,\n experimental_reuseContext = false,\n}: {\n groupPath: GroupPath.GroupPath;\n functionNames: ReadonlyArray<string>;\n registeredFunctionsImportPath: string;\n useNode?: boolean;\n experimental_reuseContext?: boolean;\n}) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n const directoryPath = path.dirname(modulePath);\n if (!(yield* fs.exists(directoryPath))) {\n yield* fs.makeDirectory(directoryPath, { recursive: true });\n }\n\n const functionsContentsString = yield* render({\n functionNames,\n registeredFunctionsImportPath,\n useNode,\n experimental_reuseContext,\n });\n\n if (!(yield* fs.exists(modulePath))) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Added\" as const;\n }\n const existing = yield* fs.readFileString(modulePath);\n if (existing !== functionsContentsString) {\n yield* fs.writeFileString(modulePath, functionsContentsString);\n return \"Modified\" as const;\n }\n return \"Unchanged\" as const;\n});\n\n/**\n * Compute the module import specifier (relative to `modulePath`) for a group's\n * registry file under `confect/_generated/registeredFunctions/`. The registry\n * path mirrors the group's path one-to-one (see\n * `registeredFunctionsRelativePath` in `LeafModule.ts`) for both Convex and\n * Node groups.\n *\n * @internal\n */\nexport const registeredFunctionsImportPathForGroup = Effect.fnUntraced(\n function* (groupPath: GroupPath.GroupPath, modulePath: string) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n\n const registeredFunctionsPath =\n path.join(\n confectDirectory,\n \"_generated\",\n \"registeredFunctions\",\n ...groupPath.pathSegments,\n ) + \".ts\";\n\n return yield* toModuleImportPath(\n path.relative(path.dirname(modulePath), registeredFunctionsPath),\n );\n },\n);\n\nconst logGroupPaths = Effect.fnUntraced(function* <R>(\n groupPaths: GroupPaths.GroupPaths,\n logFn: (fullPath: string) => Effect.Effect<void, never, R>,\n): Effect.fn.Return<void, never, R | Path.Path | ConvexDirectory> {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.forEach(\n groupPaths,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n const relativeModulePath = yield* GroupPath.modulePath(gp);\n yield* logFn(path.join(convexDirectory, relativeModulePath));\n }),\n );\n});\n\n/**\n * @internal\n */\nexport const generateFunctions = Effect.fnUntraced(function* (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n) {\n const groupPathsFromFs = yield* getGroupPathsFromFs;\n yield* applyFunctionPlan(GenerationSnapshot.plan(snapshot, groupPathsFromFs));\n return GenerationSnapshot.functionPaths(snapshot);\n});\n\n/**\n * @internal\n */\nexport const applyFunctionPlan = Effect.fnUntraced(function* (\n plan: GenerationSnapshot.ModulePlan,\n) {\n const removed = GroupPaths.GroupPaths.make(\n HashSet.fromIterable(plan.removed),\n );\n yield* removeGroups(removed);\n yield* logGroupPaths(removed, logFileRemoved);\n yield* writeGroups(plan.changed);\n});\n\nconst getGroupPathsFromFs = Effect.gen(function* () {\n const path = yield* Path.Path;\n const allConvexPaths = yield* getEntrypoints;\n const groupPathArray = yield* pipe(\n allConvexPaths,\n Array.filter(\n (convexPath) =>\n path.extname(convexPath) === \".ts\" &&\n !RESERVED_CONVEX_TS_FILE_NAMES.has(path.basename(convexPath)) &&\n convexPath !== DEPLOY_MODULE,\n ),\n Effect.forEach((groupModulePath) =>\n GroupPath.fromGroupModulePath(groupModulePath),\n ),\n );\n return GroupPaths.GroupPaths.make(HashSet.fromIterable(groupPathArray));\n});\n\n/**\n * @internal\n */\nexport const removeGroups = Effect.fnUntraced(function* (\n groupPaths: GroupPaths.GroupPaths,\n) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* Effect.all(\n HashSet.map(groupPaths, (groupPath) =>\n Effect.gen(function* () {\n const relativeModulePath = yield* GroupPath.modulePath(groupPath);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n\n yield* Effect.logDebug(`Removing group '${relativeModulePath}'...`);\n\n yield* removePathIfExists(modulePath);\n yield* Effect.logDebug(`Group '${relativeModulePath}' removed`);\n }),\n ),\n { concurrency: \"unbounded\" },\n );\n});\n\n/**\n * @internal\n */\nexport const writeGroups = (\n groups: ReadonlyArray<GenerationSnapshot.GroupSummary>,\n) =>\n Effect.forEach(\n groups,\n Effect.fnUntraced(function* (group: GenerationSnapshot.GroupSummary) {\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const relativeModulePath = yield* GroupPath.modulePath(group.path);\n const modulePath = path.join(convexDirectory, relativeModulePath);\n const registeredFunctionsImportPath =\n yield* registeredFunctionsImportPathForGroup(group.path, modulePath);\n const change = yield* generateGroupModule({\n groupPath: group.path,\n functionNames: group.functionNames,\n registeredFunctionsImportPath,\n useNode: group.runtime === \"Node\",\n experimental_reuseContext: group.experimental_reuseContext === true,\n });\n yield* Match.value(change).pipe(\n Match.when(\"Added\", () => logFileAdded(modulePath)),\n Match.when(\"Modified\", () => logFileModified(modulePath)),\n Match.when(\"Unchanged\", () => Effect.void),\n Match.exhaustive,\n );\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,gDAAgC,IAAI,IAAI;CAC5C;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,gBAAgB;AAGtB,MAAM,iBAAiB,OAAO,IAAI,aAAa;CAC7C,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,SAAS,OAAO,gBAAgB;CACtC,MAAM,QAAQ,OAAO,GAAG,cAAc,QAAQ,EAAE,WAAW,KAAK,CAAC;CACjE,MAAM,aAAa,KACjB,OACA,MAAM,QACH,SACC,KAAK,SAAS,IAAI,MAAM,sBACxB,KAAK,QAAQ,IAAI,MAAM,GAC3B,GACA,MAAM,KAAK,SAAS,KAAK,QAAQ,IAAI,IAAI,KAAK,GAAG,CACnD;CACA,OAAO,MAAM,OAAO,QAAQ,SAAS;EACnC,MAA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MAAa,eACX,WAEA,OAAO,QACL,QACA,OAAO,WAAW,WAAW,OAAwC;CACnE,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,kBAAkB,OAAO,gBAAgB;CAC/C,MAAM,qBAAqB,OAAOD,WAAqB,MAAM,IAAI;CACjE,MAAMC,eAAa,KAAK,KAAK,iBAAiB,kBAAkB;CAChE,MAAM,gCACJ,OAAO,sCAAsC,MAAM,MAAMA,YAAU;CACrE,MAAM,SAAS,OAAO,oBAAoB;EACxC,WAAW,MAAM;EACjB,eAAe,MAAM;EACrB;EACA,SAAS,MAAM,YAAY;EAC3B,2BAA2B,MAAM,8BAA8B;CACjE,CAAC;CACD,OAAO,MAAM,MAAM,MAAM,CAAC,CAAC,KACzB,MAAM,KAAK,eAAe,aAAaA,YAAU,CAAC,GAClD,MAAM,KAAK,kBAAkB,gBAAgBA,YAAU,CAAC,GACxD,MAAM,KAAK,mBAAmB,OAAO,IAAI,GACzC,MAAM,UACR;AACF,CAAC,CACH"}
@@ -178,7 +178,8 @@ const inputs = Effect.map(Effect.all([record(INPUTS), record(VERIFY_INPUTS)]), (
178
178
  * after logging the rest. The record of section inputs is written either way,
179
179
  * keeping the previous inputs after a failure, so `confect dev` sees the fix.
180
180
  * Returns the claimed file names, whether they differ from the section files
181
- * that existed before, and the modules each section key matched.
181
+ * that existed before, the modules each section key matched, and the files of
182
+ * the sections that wrap crons, in the order `App.make` declares them.
182
183
  *
183
184
  * @internal
184
185
  */
@@ -216,6 +217,7 @@ const sync = Effect.fnUntraced(function* (backend, leaves, mounts) {
216
217
  return {
217
218
  modules: new Map(Arr.map(rendered, ({ key, modules }) => [key, modules])),
218
219
  files: names,
220
+ crons: Option.isNone(backend) ? [] : Arr.flatMap(backend.value.sections, ({ section: { generate } }) => generate?.wrapsCrons === true ? [generate.file] : []),
219
221
  changed: names.length !== existing.length || Arr.some(names, (file) => !existing.includes(file))
220
222
  };
221
223
  });
@@ -1 +1 @@
1
- {"version":3,"file":"SectionFiles.mjs","names":["Bundler.bundle","ConvexConfig.componentConfigPlugin"],"sources":["../src/SectionFiles.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport type * as esbuild from \"esbuild\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidManifestSectionError,\n logCodegenError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport * as ConvexConfig from \"./ConvexConfig.js\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport { logFileRemoved } from \"./log.js\";\nimport {\n removePathIfExists,\n toPosixPath,\n writeFileStringAndLog,\n} from \"./utils.js\";\nimport * as Str from \"effect/String\";\nimport { pipe } from \"effect/Function\";\nimport * as Arr from \"effect/Array\";\nimport * as Record from \"effect/Record\";\nimport { quote } from \"./Json.js\";\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\n/**\n * The files codegen writes directly in `confect/_generated`, current and\n * legacy, which no section may claim.\n */\nexport const builtIn: ReadonlySet<string> = new Set(\n Arr.map(\n pipe(\n `spec schema convexSchema id components component refs docs services manifest\n auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions\n nodeRegisteredFunctions`,\n Str.split(/\\s+/),\n ),\n (name) => `${name}.ts`,\n ),\n);\n\nconst PREFIX = \"// Generated by `confect codegen` from the manifest section \";\nconst header = (key: string) => `${PREFIX}${quote(key)}. Do not edit.`;\nconst Sources = Schema.String.pipe(Schema.Array, Schema.fromJsonString);\nconst encodeSources = (sources: ReadonlyArray<string>) =>\n Schema.encodeEffect(Sources)(sources).pipe(Effect.orDie);\nconst decodeSources = Schema.decodeUnknownOption(Sources);\nconst INPUTS = \"sectionInputs.json\";\nconst VERIFY_INPUTS = \"verifyInputs.json\";\n\ninterface Claim {\n readonly key: string;\n readonly generate: ManifestSection.Generate;\n}\n\n/**\n * A declared backend: the target codegen generates and the sections its\n * `App.make` names.\n */\nexport interface Backend {\n readonly target: ManifestSection.Target;\n readonly sections: ReadonlyArray<ManifestSection.Entry>;\n}\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (spec: FunctionSpec.AnyWithProps, path: string, source: string) => void,\n) => {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => {\n for (const spec of Record.values(group.functions))\n each(spec, `${path}:${spec.name}`, source);\n for (const [name, child] of Record.toEntries(group.groups))\n walk(child, `${path}/${name}`, source);\n };\n for (const leaf of leaves)\n walk(leaf.spec, Arr.join(leaf.pathSegments, \"/\"), leaf.relativePath);\n};\n\n/**\n * One claim per declared section that generates a file, ordered by file. A name\n * that is built in, not a `.ts` file directly in `_generated`, or claimed by\n * two keys is refused.\n */\nexport const claims = (sections: ReadonlyArray<ManifestSection.Entry>) =>\n Result.gen(function* () {\n const byKey = new Map<string, ManifestSection.Generate>();\n for (const { key, section } of sections)\n if (section.generate !== undefined) byKey.set(key, section.generate);\n const byFile = new Map<string, string>();\n for (const [key, { file }] of byKey) {\n const other = byFile.get(file);\n const refusal = builtIn.has(file)\n ? `claims confect/_generated/${file}, which codegen writes itself.`\n : !/^[\\w-]+\\.ts$/.test(file)\n ? `claims ${quote(file)}; name a .ts file directly inside confect/_generated.`\n : other !== undefined\n ? `claims confect/_generated/${file}, which the manifest section ${quote(other)} also claims.`\n : undefined;\n if (refusal !== undefined)\n return yield* Result.fail(\n InvalidManifestSectionError.make({\n sectionKey: key,\n reason: refusal,\n }),\n );\n byFile.set(file, key);\n }\n return Arr.map([...byKey], ([key, generate]) => ({ key, generate })).sort(\n (a, b) => pipe(a.generate.file, Str.localeCompare(b.generate.file)),\n );\n });\n\nconst sourceFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const directory = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n return pipe(\n directory,\n Arr.map((file) => toPosixPath(path, file)),\n Arr.filter(\n (file) =>\n pipe(file, Str.endsWith(\".ts\")) &&\n !pipe(file, Str.endsWith(\".d.ts\")) &&\n !pipe(file, Str.split(\"/\")).includes(\"_generated\"),\n ),\n ).sort();\n});\n\n/**\n * Bundle each matched `confect/` file and return its exports, adding it and\n * every first-party file it imports to `watched`.\n */\nconst load = Effect.fnUntraced(function* (\n matched: ReadonlyArray<string>,\n watched: Set<string>,\n plugins: ReadonlyArray<esbuild.Plugin> = [],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n for (const file of matched) watched.add(file);\n return yield* Effect.forEach(matched, (relativePath) => {\n const entry = path.join(confectDirectory, relativePath);\n // Inputs are recorded once esbuild finishes, before the module runs, so a\n // module that throws on load still has its imports watched. `confect dev`\n // sees changes only under `confect/`, and every run rewrites `_generated`,\n // so watching it would loop.\n const recordInputs: esbuild.Plugin = {\n name: \"confect:section-inputs\",\n setup: (build) =>\n build.onEnd(({ metafile }) => {\n for (const loaded of Record.keys(metafile?.inputs ?? {})) {\n // A plugin's own namespace, such as the component config\n // wrapper, is not a file.\n if (/^[^/\\\\]+:/.test(loaded) && !path.isAbsolute(loaded)) continue;\n const file = toPosixPath(\n path,\n path.relative(\n confectDirectory,\n path.resolve(path.dirname(entry), loaded),\n ),\n );\n if (\n !pipe(file, Str.startsWith(\"../\")) &&\n !pipe(file, Str.startsWith(\"_generated/\"))\n )\n watched.add(file);\n }\n }),\n };\n return Bundler.bundle(entry, { plugins: [...plugins, recordInputs] }).pipe(\n Effect.mapBoth({\n onFailure: (error) =>\n fromBundlerError(`confect/${relativePath}`, error),\n onSuccess: ({ module }) => ({ relativePath, exports: module }),\n }),\n );\n });\n});\n\n/**\n * Fail with the first of a section's refusals after logging the rest.\n */\nconst refuse = Effect.fnUntraced(function* (\n key: string,\n reasons: ReadonlyArray<string>,\n) {\n const [error, ...more] = Arr.map(reasons, (reason) =>\n InvalidManifestSectionError.make({ sectionKey: key, reason }),\n );\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n});\n\nconst render = Effect.fnUntraced(function* (\n { key, generate }: Claim,\n target: ManifestSection.Target,\n input: Pick<ManifestSection.GenerateInput, \"functions\" | \"mounts\" | \"files\">,\n watched: Set<string>,\n) {\n const confectDirectory = yield* ConfectDirectory.get;\n const failed = (cause: unknown) =>\n InvalidManifestSectionError.make({\n sectionKey: key,\n reason: `generate failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => Arr.filter(input.files, (file) => generate.match(file)),\n catch: failed,\n });\n const modules = yield* load(matched, watched);\n const { contents, errors } = yield* Effect.try({\n try: () => generate.render({ ...input, modules, target, confectDirectory }),\n catch: failed,\n });\n yield* refuse(key, errors);\n const sources = yield* encodeSources(matched);\n return {\n modules,\n contents: Arr.join([header(key), `// Sources: ${sources}`, contents], \"\\n\"),\n };\n});\n\n/**\n * The files in `confect/_generated` a section wrote, which carry its header.\n *\n * @internal\n */\nexport const written = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n if (!(yield* fs.exists(generated))) return [];\n const directory = yield* fs.readDirectory(generated);\n return yield* Effect.filter(\n Arr.filter(directory, (file) => pipe(file, Str.endsWith(\".ts\"))),\n (file) =>\n fs\n .readFileString(path.join(generated, file))\n .pipe(Effect.map((contents) => pipe(contents, Str.startsWith(PREFIX)))),\n );\n});\n\nconst record = Effect.fnUntraced(function* (name: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const file = path.join(confectDirectory, \"_generated\", name);\n const none: ReadonlyArray<string> = [];\n if (!(yield* fs.exists(file))) return none;\n const fileContents = yield* fs.readFileString(file);\n return Option.getOrElse(decodeSources(fileContents), () => none);\n});\n\n/**\n * The `confect/` files the declared sections' `generate` and `verify` matched\n * and the `confect/` files those import, as recorded by the last codegen run\n * that loaded them.\n *\n * @internal\n */\nexport const inputs = Effect.map(\n Effect.all([record(INPUTS), record(VERIFY_INPUTS)]),\n ([rendered, verified]) => [...new Set([...rendered, ...verified])].sort(),\n);\n\n/**\n * Write each claimed file into `confect/_generated` once every section the\n * declared backend names has rendered for its target; an undeclared backend\n * renders none. Every section renders before codegen fails with the first error\n * after logging the rest. The record of section inputs is written either way,\n * keeping the previous inputs after a failure, so `confect dev` sees the fix.\n * Returns the claimed file names, whether they differ from the section files\n * that existed before, and the modules each section key matched.\n *\n * @internal\n */\nexport const sync = Effect.fnUntraced(function* (\n backend: Option.Option<Backend>,\n leaves: ReadonlyArray<Leaf>,\n mounts: ManifestSection.GenerateInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const claimed = Option.isSome(backend)\n ? yield* Effect.map(\n Effect.fromResult(claims(backend.value.sections)),\n Arr.map((claim) => ({ claim, target: backend.value.target })),\n )\n : [];\n const functions: Array<{ path: string; source: string }> = [];\n visit(leaves, (_, functionPath, source) =>\n functions.push({ path: functionPath, source }),\n );\n const files = claimed.length === 0 ? [] : yield* sourceFiles;\n const watched = new Set<string>();\n const [rendered, failures] = yield* Effect.partition(\n claimed,\n ({ claim, target }) =>\n render(claim, target, { functions, mounts, files }, watched).pipe(\n Effect.map((output) => ({ ...claim, ...output })),\n ),\n );\n if (failures.length > 0)\n for (const file of yield* record(INPUTS)) watched.add(file);\n yield* claimed.length === 0\n ? removePathIfExists(path.join(generated, INPUTS))\n : encodeSources([...watched].sort()).pipe(\n Effect.flatMap((sources) =>\n writeFileStringAndLog(path.join(generated, INPUTS), sources),\n ),\n );\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n const existing = yield* written;\n for (const { generate, contents } of rendered)\n yield* writeFileStringAndLog(path.join(generated, generate.file), contents);\n const names = Arr.map(rendered, ({ generate }) => generate.file);\n return {\n modules: new Map(Arr.map(rendered, ({ key, modules }) => [key, modules])),\n files: names,\n changed:\n names.length !== existing.length ||\n Arr.some(names, (file) => !existing.includes(file)),\n };\n});\n\n/**\n * Run each declared section's `verify` once every `_generated` file exists:\n * bundle the `confect/` files its `match` selects as codegen bundles a\n * declaration, and hand their exports, the mounts and the target to its\n * `check`. Every section checks before codegen fails with the first refusal\n * after logging the rest. The files each loaded are recorded as section inputs,\n * keeping the previous ones after a failure, so `confect dev` checks again when\n * one changes.\n *\n * @internal\n */\nexport const verify = Effect.fnUntraced(function* (\n backend: Option.Option<Backend>,\n mounts: ManifestSection.VerifyInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const recorded = path.join(confectDirectory, \"_generated\", VERIFY_INPUTS);\n const checks = Option.match(backend, {\n onNone: () => [],\n onSome: ({ sections }) =>\n Arr.flatMap(sections, ({ key, section }) =>\n section.generate?.verify === undefined\n ? []\n : [{ key, verifier: section.generate.verify }],\n ),\n });\n if (Option.isNone(backend) || checks.length === 0)\n return yield* removePathIfExists(recorded);\n const { target } = backend.value;\n const files = yield* sourceFiles;\n const watched = new Set<string>();\n const [, failures] = yield* Effect.partition(checks, ({ key, verifier }) =>\n Effect.gen(function* () {\n const failed = (cause: unknown) =>\n InvalidManifestSectionError.make({\n sectionKey: key,\n reason: `verify failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => Arr.filter(files, (file) => verifier.match(file)),\n catch: failed,\n });\n const modules = yield* load(matched, watched, [\n ConvexConfig.componentConfigPlugin(path),\n ]);\n const tryValue = yield* Effect.try({\n try: () => verifier.check({ modules, mounts, target }),\n catch: failed,\n });\n yield* refuse(key, tryValue);\n }),\n );\n if (failures.length > 0)\n for (const file of yield* record(VERIFY_INPUTS)) watched.add(file);\n const sources = yield* encodeSources([...watched].sort());\n yield* writeFileStringAndLog(recorded, sources);\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n});\n\n/**\n * Remove each file a section wrote that is not in `files`. Codegen runs this\n * after it rewrites the registration files and the HTTP router, so a run that\n * fails earlier leaves no import of a removed file.\n *\n * @internal\n */\nexport const removeUnclaimed = Effect.fnUntraced(function* (\n files: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n for (const file of yield* written)\n if (!files.includes(file)) {\n yield* removePathIfExists(path.join(generated, file));\n yield* logFileRemoved(path.join(generated, file));\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,UAA+B,IAAI,IAC9C,IAAI,IACF,KACE;;4BAGA,IAAI,MAAM,KAAK,CACjB,IACC,SAAS,GAAG,KAAK,IACpB,CACF;AAEA,MAAM,SAAS;AACf,MAAM,UAAU,QAAgB,GAAG,SAAS,MAAM,GAAG,EAAE;AACvD,MAAM,UAAU,OAAO,OAAO,KAAK,OAAO,OAAO,OAAO,cAAc;AACtE,MAAM,iBAAiB,YACrB,OAAO,aAAa,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,OAAO,KAAK;AACzD,MAAM,gBAAgB,OAAO,oBAAoB,OAAO;AACxD,MAAM,SAAS;AACf,MAAM,gBAAgB;AAgBtB,MAAM,SACJ,QACA,SACG;CACH,MAAM,QACJ,OACA,MACA,WACG;EACH,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,SAAS,GAC9C,KAAK,MAAM,GAAG,KAAK,GAAG,KAAK,QAAQ,MAAM;EAC3C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,UAAU,MAAM,MAAM,GACvD,KAAK,OAAO,GAAG,KAAK,GAAG,QAAQ,MAAM;CACzC;CACA,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AsB,UAAU,OAAO;CAC9C,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,KAAK,MAAM,SAAS,MAAM,OAAO,gBAAgB,KAAK;CACtD,IAAI,UAAU,KAAA,GAAW,OAAO,OAAO;AACzC,CAAC;;;;;;;;AASD,MAAa,kBAAkB,OAAO,WAAW,WAC/C,OACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,mBAAmB,OAAO,iBAAiB;CACjD,MAAM,YAAY,KAAK,KAAK,kBAAkB,YAAY;CAC1D,KAAK,MAAM,QAAQ,OAAO,SACxB,IAAI,CAAC,MAAM,SAAS,IAAI,GAAG;EACzB,OAAO,mBAAmB,KAAK,KAAK,WAAW,IAAI,CAAC;EACpD,OAAO,eAAe,KAAK,KAAK,WAAW,IAAI,CAAC;CAClD;AACJ,CAAC"}
1
+ {"version":3,"file":"SectionFiles.mjs","names":["Bundler.bundle","ConvexConfig.componentConfigPlugin"],"sources":["../src/SectionFiles.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport type * as esbuild from \"esbuild\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidManifestSectionError,\n logCodegenError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport * as ConvexConfig from \"./ConvexConfig.js\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport { logFileRemoved } from \"./log.js\";\nimport {\n removePathIfExists,\n toPosixPath,\n writeFileStringAndLog,\n} from \"./utils.js\";\nimport * as Str from \"effect/String\";\nimport { pipe } from \"effect/Function\";\nimport * as Arr from \"effect/Array\";\nimport * as Record from \"effect/Record\";\nimport { quote } from \"./Json.js\";\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\n/**\n * The files codegen writes directly in `confect/_generated`, current and\n * legacy, which no section may claim.\n */\nexport const builtIn: ReadonlySet<string> = new Set(\n Arr.map(\n pipe(\n `spec schema convexSchema id components component refs docs services manifest\n auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions\n nodeRegisteredFunctions`,\n Str.split(/\\s+/),\n ),\n (name) => `${name}.ts`,\n ),\n);\n\nconst PREFIX = \"// Generated by `confect codegen` from the manifest section \";\nconst header = (key: string) => `${PREFIX}${quote(key)}. Do not edit.`;\nconst Sources = Schema.String.pipe(Schema.Array, Schema.fromJsonString);\nconst encodeSources = (sources: ReadonlyArray<string>) =>\n Schema.encodeEffect(Sources)(sources).pipe(Effect.orDie);\nconst decodeSources = Schema.decodeUnknownOption(Sources);\nconst INPUTS = \"sectionInputs.json\";\nconst VERIFY_INPUTS = \"verifyInputs.json\";\n\ninterface Claim {\n readonly key: string;\n readonly generate: ManifestSection.Generate;\n}\n\n/**\n * A declared backend: the target codegen generates and the sections its\n * `App.make` names.\n */\nexport interface Backend {\n readonly target: ManifestSection.Target;\n readonly sections: ReadonlyArray<ManifestSection.Entry>;\n}\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (spec: FunctionSpec.AnyWithProps, path: string, source: string) => void,\n) => {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => {\n for (const spec of Record.values(group.functions))\n each(spec, `${path}:${spec.name}`, source);\n for (const [name, child] of Record.toEntries(group.groups))\n walk(child, `${path}/${name}`, source);\n };\n for (const leaf of leaves)\n walk(leaf.spec, Arr.join(leaf.pathSegments, \"/\"), leaf.relativePath);\n};\n\n/**\n * One claim per declared section that generates a file, ordered by file. A name\n * that is built in, not a `.ts` file directly in `_generated`, or claimed by\n * two keys is refused.\n */\nexport const claims = (sections: ReadonlyArray<ManifestSection.Entry>) =>\n Result.gen(function* () {\n const byKey = new Map<string, ManifestSection.Generate>();\n for (const { key, section } of sections)\n if (section.generate !== undefined) byKey.set(key, section.generate);\n const byFile = new Map<string, string>();\n for (const [key, { file }] of byKey) {\n const other = byFile.get(file);\n const refusal = builtIn.has(file)\n ? `claims confect/_generated/${file}, which codegen writes itself.`\n : !/^[\\w-]+\\.ts$/.test(file)\n ? `claims ${quote(file)}; name a .ts file directly inside confect/_generated.`\n : other !== undefined\n ? `claims confect/_generated/${file}, which the manifest section ${quote(other)} also claims.`\n : undefined;\n if (refusal !== undefined)\n return yield* Result.fail(\n InvalidManifestSectionError.make({\n sectionKey: key,\n reason: refusal,\n }),\n );\n byFile.set(file, key);\n }\n return Arr.map([...byKey], ([key, generate]) => ({ key, generate })).sort(\n (a, b) => pipe(a.generate.file, Str.localeCompare(b.generate.file)),\n );\n });\n\nconst sourceFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const directory = yield* fs.readDirectory(confectDirectory, {\n recursive: true,\n });\n return pipe(\n directory,\n Arr.map((file) => toPosixPath(path, file)),\n Arr.filter(\n (file) =>\n pipe(file, Str.endsWith(\".ts\")) &&\n !pipe(file, Str.endsWith(\".d.ts\")) &&\n !pipe(file, Str.split(\"/\")).includes(\"_generated\"),\n ),\n ).sort();\n});\n\n/**\n * Bundle each matched `confect/` file and return its exports, adding it and\n * every first-party file it imports to `watched`.\n */\nconst load = Effect.fnUntraced(function* (\n matched: ReadonlyArray<string>,\n watched: Set<string>,\n plugins: ReadonlyArray<esbuild.Plugin> = [],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n for (const file of matched) watched.add(file);\n return yield* Effect.forEach(matched, (relativePath) => {\n const entry = path.join(confectDirectory, relativePath);\n // Inputs are recorded once esbuild finishes, before the module runs, so a\n // module that throws on load still has its imports watched. `confect dev`\n // sees changes only under `confect/`, and every run rewrites `_generated`,\n // so watching it would loop.\n const recordInputs: esbuild.Plugin = {\n name: \"confect:section-inputs\",\n setup: (build) =>\n build.onEnd(({ metafile }) => {\n for (const loaded of Record.keys(metafile?.inputs ?? {})) {\n // A plugin's own namespace, such as the component config\n // wrapper, is not a file.\n if (/^[^/\\\\]+:/.test(loaded) && !path.isAbsolute(loaded)) continue;\n const file = toPosixPath(\n path,\n path.relative(\n confectDirectory,\n path.resolve(path.dirname(entry), loaded),\n ),\n );\n if (\n !pipe(file, Str.startsWith(\"../\")) &&\n !pipe(file, Str.startsWith(\"_generated/\"))\n )\n watched.add(file);\n }\n }),\n };\n return Bundler.bundle(entry, { plugins: [...plugins, recordInputs] }).pipe(\n Effect.mapBoth({\n onFailure: (error) =>\n fromBundlerError(`confect/${relativePath}`, error),\n onSuccess: ({ module }) => ({ relativePath, exports: module }),\n }),\n );\n });\n});\n\n/**\n * Fail with the first of a section's refusals after logging the rest.\n */\nconst refuse = Effect.fnUntraced(function* (\n key: string,\n reasons: ReadonlyArray<string>,\n) {\n const [error, ...more] = Arr.map(reasons, (reason) =>\n InvalidManifestSectionError.make({ sectionKey: key, reason }),\n );\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n});\n\nconst render = Effect.fnUntraced(function* (\n { key, generate }: Claim,\n target: ManifestSection.Target,\n input: Pick<ManifestSection.GenerateInput, \"functions\" | \"mounts\" | \"files\">,\n watched: Set<string>,\n) {\n const confectDirectory = yield* ConfectDirectory.get;\n const failed = (cause: unknown) =>\n InvalidManifestSectionError.make({\n sectionKey: key,\n reason: `generate failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => Arr.filter(input.files, (file) => generate.match(file)),\n catch: failed,\n });\n const modules = yield* load(matched, watched);\n const { contents, errors } = yield* Effect.try({\n try: () => generate.render({ ...input, modules, target, confectDirectory }),\n catch: failed,\n });\n yield* refuse(key, errors);\n const sources = yield* encodeSources(matched);\n return {\n modules,\n contents: Arr.join([header(key), `// Sources: ${sources}`, contents], \"\\n\"),\n };\n});\n\n/**\n * The files in `confect/_generated` a section wrote, which carry its header.\n *\n * @internal\n */\nexport const written = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n if (!(yield* fs.exists(generated))) return [];\n const directory = yield* fs.readDirectory(generated);\n return yield* Effect.filter(\n Arr.filter(directory, (file) => pipe(file, Str.endsWith(\".ts\"))),\n (file) =>\n fs\n .readFileString(path.join(generated, file))\n .pipe(Effect.map((contents) => pipe(contents, Str.startsWith(PREFIX)))),\n );\n});\n\nconst record = Effect.fnUntraced(function* (name: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const file = path.join(confectDirectory, \"_generated\", name);\n const none: ReadonlyArray<string> = [];\n if (!(yield* fs.exists(file))) return none;\n const fileContents = yield* fs.readFileString(file);\n return Option.getOrElse(decodeSources(fileContents), () => none);\n});\n\n/**\n * The `confect/` files the declared sections' `generate` and `verify` matched\n * and the `confect/` files those import, as recorded by the last codegen run\n * that loaded them.\n *\n * @internal\n */\nexport const inputs = Effect.map(\n Effect.all([record(INPUTS), record(VERIFY_INPUTS)]),\n ([rendered, verified]) => [...new Set([...rendered, ...verified])].sort(),\n);\n\n/**\n * Write each claimed file into `confect/_generated` once every section the\n * declared backend names has rendered for its target; an undeclared backend\n * renders none. Every section renders before codegen fails with the first error\n * after logging the rest. The record of section inputs is written either way,\n * keeping the previous inputs after a failure, so `confect dev` sees the fix.\n * Returns the claimed file names, whether they differ from the section files\n * that existed before, the modules each section key matched, and the files of\n * the sections that wrap crons, in the order `App.make` declares them.\n *\n * @internal\n */\nexport const sync = Effect.fnUntraced(function* (\n backend: Option.Option<Backend>,\n leaves: ReadonlyArray<Leaf>,\n mounts: ManifestSection.GenerateInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n const claimed = Option.isSome(backend)\n ? yield* Effect.map(\n Effect.fromResult(claims(backend.value.sections)),\n Arr.map((claim) => ({ claim, target: backend.value.target })),\n )\n : [];\n const functions: Array<{ path: string; source: string }> = [];\n visit(leaves, (_, functionPath, source) =>\n functions.push({ path: functionPath, source }),\n );\n const files = claimed.length === 0 ? [] : yield* sourceFiles;\n const watched = new Set<string>();\n const [rendered, failures] = yield* Effect.partition(\n claimed,\n ({ claim, target }) =>\n render(claim, target, { functions, mounts, files }, watched).pipe(\n Effect.map((output) => ({ ...claim, ...output })),\n ),\n );\n if (failures.length > 0)\n for (const file of yield* record(INPUTS)) watched.add(file);\n yield* claimed.length === 0\n ? removePathIfExists(path.join(generated, INPUTS))\n : encodeSources([...watched].sort()).pipe(\n Effect.flatMap((sources) =>\n writeFileStringAndLog(path.join(generated, INPUTS), sources),\n ),\n );\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n const existing = yield* written;\n for (const { generate, contents } of rendered)\n yield* writeFileStringAndLog(path.join(generated, generate.file), contents);\n const names = Arr.map(rendered, ({ generate }) => generate.file);\n return {\n modules: new Map(Arr.map(rendered, ({ key, modules }) => [key, modules])),\n files: names,\n crons: Option.isNone(backend)\n ? []\n : Arr.flatMap(backend.value.sections, ({ section: { generate } }) =>\n generate?.wrapsCrons === true ? [generate.file] : [],\n ),\n changed:\n names.length !== existing.length ||\n Arr.some(names, (file) => !existing.includes(file)),\n };\n});\n\n/**\n * Run each declared section's `verify` once every `_generated` file exists:\n * bundle the `confect/` files its `match` selects as codegen bundles a\n * declaration, and hand their exports, the mounts and the target to its\n * `check`. Every section checks before codegen fails with the first refusal\n * after logging the rest. The files each loaded are recorded as section inputs,\n * keeping the previous ones after a failure, so `confect dev` checks again when\n * one changes.\n *\n * @internal\n */\nexport const verify = Effect.fnUntraced(function* (\n backend: Option.Option<Backend>,\n mounts: ManifestSection.VerifyInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const recorded = path.join(confectDirectory, \"_generated\", VERIFY_INPUTS);\n const checks = Option.match(backend, {\n onNone: () => [],\n onSome: ({ sections }) =>\n Arr.flatMap(sections, ({ key, section }) =>\n section.generate?.verify === undefined\n ? []\n : [{ key, verifier: section.generate.verify }],\n ),\n });\n if (Option.isNone(backend) || checks.length === 0)\n return yield* removePathIfExists(recorded);\n const { target } = backend.value;\n const files = yield* sourceFiles;\n const watched = new Set<string>();\n const [, failures] = yield* Effect.partition(checks, ({ key, verifier }) =>\n Effect.gen(function* () {\n const failed = (cause: unknown) =>\n InvalidManifestSectionError.make({\n sectionKey: key,\n reason: `verify failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => Arr.filter(files, (file) => verifier.match(file)),\n catch: failed,\n });\n const modules = yield* load(matched, watched, [\n ConvexConfig.componentConfigPlugin(path),\n ]);\n const tryValue = yield* Effect.try({\n try: () => verifier.check({ modules, mounts, target }),\n catch: failed,\n });\n yield* refuse(key, tryValue);\n }),\n );\n if (failures.length > 0)\n for (const file of yield* record(VERIFY_INPUTS)) watched.add(file);\n const sources = yield* encodeSources([...watched].sort());\n yield* writeFileStringAndLog(recorded, sources);\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n});\n\n/**\n * Remove each file a section wrote that is not in `files`. Codegen runs this\n * after it rewrites the registration files and the HTTP router, so a run that\n * fails earlier leaves no import of a removed file.\n *\n * @internal\n */\nexport const removeUnclaimed = Effect.fnUntraced(function* (\n files: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const generated = path.join(confectDirectory, \"_generated\");\n for (const file of yield* written)\n if (!files.includes(file)) {\n yield* removePathIfExists(path.join(generated, file));\n yield* logFileRemoved(path.join(generated, file));\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,UAA+B,IAAI,IAC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ACzB,OAAO,mBAAmB,KAAK,KAAK,WAAW,IAAI,CAAC;EACpD,OAAO,eAAe,KAAK,KAAK,WAAW,IAAI,CAAC;CAClD;AACJ,CAAC"}
@@ -60,12 +60,12 @@ const add = (pending, entries, forceFull = false) => {
60
60
  };
61
61
  };
62
62
  /**
63
- * Full generation writes a declared backend's `convex/http.ts` and
63
+ * Full generation writes a declared backend's `convex/http.ts`, `crons.ts` and
64
64
  * `auth.config.ts` and rejects a component's `auth.ts`, so those edits need it
65
65
  * instead of the optional-file writers.
66
66
  */
67
67
  const forBackend = (pending, backend) => {
68
- const generated = HashSet.filter(pending.optional, (file) => Match.value(file).pipe(Match.when("Http", () => backend.declared), Match.when("Auth", () => backend.declared || backend.component), Match.when("Crons", () => false), Match.exhaustive));
68
+ const generated = HashSet.filter(pending.optional, (file) => Match.value(file).pipe(Match.when("Http", () => backend.declared), Match.when("Auth", () => backend.declared || backend.component), Match.when("Crons", () => backend.declared), Match.exhaustive));
69
69
  if (HashSet.isEmpty(generated)) return pending;
70
70
  return {
71
71
  work: Work.Full(),
@@ -1 +1 @@
1
- {"version":3,"file":"SyncState.mjs","names":[],"sources":["../src/SyncState.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport type { Declaration, Kind, OptionalFile } from \"./EntryPoint.js\";\nimport type { ImplModulePath } from \"./ImplModulePath.js\";\nimport type { GenerationSnapshot } from \"./GenerationSnapshot.js\";\n\nexport type Work = Data.TaggedEnum<{\n None: {};\n Reconcile: {};\n Full: {};\n Impls: { readonly paths: Array.NonEmptyReadonlyArray<ImplModulePath> };\n Declarations: {\n readonly entries: Array.NonEmptyReadonlyArray<Declaration>;\n readonly paths: ReadonlyArray<ImplModulePath>;\n };\n}>;\nexport const Work = Data.taggedEnum<Work>();\n\nexport interface Pending {\n readonly work: Work;\n readonly optional: HashSet.HashSet<OptionalFile>;\n}\n\nexport const empty: Pending = { work: Work.None(), optional: HashSet.empty() };\nexport const isDirty = (pending: Pending): boolean =>\n !Work.$is(\"None\")(pending.work) || !HashSet.isEmpty(pending.optional);\nexport const full = (pending: Pending): Pending => ({\n ...pending,\n work: Work.Full(),\n});\n\nexport const reconcile = (pending: Pending): Pending => ({\n ...pending,\n work: Work.$is(\"None\")(pending.work) ? Work.Reconcile() : pending.work,\n});\n\nexport const add = (\n pending: Pending,\n entries: ReadonlyArray<Kind>,\n forceFull: boolean = false,\n): Pending => {\n const next = Array.reduce(\n entries,\n {\n needsFull: forceFull || Work.$is(\"Full\")(pending.work),\n paths: Work.$match(pending.work, {\n None: () => HashSet.empty<ImplModulePath>(),\n Reconcile: () => HashSet.empty<ImplModulePath>(),\n Full: () => HashSet.empty<ImplModulePath>(),\n Impls: ({ paths }) => HashSet.fromIterable(paths),\n Declarations: ({ paths }) => HashSet.fromIterable(paths),\n }),\n declarations: Work.$match(pending.work, {\n None: () => HashMap.empty<string, Declaration>(),\n Reconcile: () => HashMap.empty<string, Declaration>(),\n Full: () => HashMap.empty<string, Declaration>(),\n Impls: () => HashMap.empty<string, Declaration>(),\n Declarations: ({ entries: declarations }) =>\n HashMap.fromIterable(\n Array.map(\n declarations,\n (entry) =>\n [`${entry._tag}:${entry.relativePath}`, entry] as const,\n ),\n ),\n }),\n optional: pending.optional,\n },\n (state, entry) =>\n Match.value(entry).pipe(\n Match.tag(\"Impl\", ({ relativePath }) => ({\n ...state,\n paths: HashSet.add(state.paths, relativePath),\n })),\n Match.tag(\"Http\", \"Crons\", \"Auth\", ({ _tag }) => ({\n ...state,\n optional: HashSet.add(state.optional, _tag),\n })),\n Match.tag(\"Spec\", \"Table\", (declaration) => ({\n ...state,\n declarations: HashMap.set(\n state.declarations,\n `${declaration._tag}:${declaration.relativePath}`,\n declaration,\n ),\n })),\n Match.tag(\"Config\", \"Env\", \"App\", \"Callbacks\", \"Runtime\", () => ({\n ...state,\n needsFull: true,\n })),\n Match.exhaustive,\n ),\n );\n const impls = Array.fromIterable(next.paths);\n const declarations = next.declarations.pipe(\n HashMap.values,\n Array.fromIterable,\n );\n return {\n work: next.needsFull\n ? Work.Full()\n : Array.isReadonlyArrayNonEmpty(declarations)\n ? Work.Declarations({ entries: declarations, paths: impls })\n : Array.isReadonlyArrayNonEmpty(impls)\n ? Work.Impls({ paths: impls })\n : Work.$is(\"Reconcile\")(pending.work)\n ? Work.Reconcile()\n : Work.None(),\n optional: next.optional,\n };\n};\n\nexport interface Backend {\n readonly declared: boolean;\n readonly component: boolean;\n}\n\n/**\n * Full generation writes a declared backend's `convex/http.ts` and\n * `auth.config.ts` and rejects a component's `auth.ts`, so those edits need it\n * instead of the optional-file writers.\n */\nexport const forBackend = (pending: Pending, backend: Backend): Pending => {\n const generated = HashSet.filter(pending.optional, (file) =>\n Match.value(file).pipe(\n Match.when(\"Http\", () => backend.declared),\n Match.when(\"Auth\", () => backend.declared || backend.component),\n Match.when(\"Crons\", () => false),\n Match.exhaustive,\n ),\n );\n if (HashSet.isEmpty(generated)) return pending;\n return {\n work: Work.Full(),\n optional: backend.declared\n ? HashSet.difference(pending.optional, generated)\n : pending.optional,\n };\n};\n\nexport type Phase = Data.TaggedEnum<{\n Bootstrapping: {};\n NeedsFullSync: {};\n Incremental: {\n readonly failedImpls: HashSet.HashSet<ImplModulePath>;\n readonly snapshot: GenerationSnapshot;\n };\n}>;\nexport const Phase = Data.taggedEnum<Phase>();\n\nexport type Outcome = Data.TaggedEnum<{\n Succeeded: { readonly snapshot: GenerationSnapshot };\n GenerationFailed: {};\n ReconciliationFailed: {};\n ValidationFailed: {\n readonly snapshot: GenerationSnapshot;\n readonly paths: Array.NonEmptyReadonlyArray<ImplModulePath>;\n };\n}>;\nexport const Outcome = Data.taggedEnum<Outcome>();\n\nexport const transition = (outcome: Outcome): Phase =>\n Outcome.$match(outcome, {\n Succeeded: ({ snapshot }) =>\n Phase.Incremental({\n snapshot,\n failedImpls: HashSet.empty(),\n }),\n GenerationFailed: () => Phase.NeedsFullSync(),\n ReconciliationFailed: () => Phase.NeedsFullSync(),\n ValidationFailed: ({ snapshot, paths }) =>\n Phase.Incremental({\n snapshot,\n failedImpls: HashSet.fromIterable(paths),\n }),\n });\n\nexport const shouldRetry = (phase: Phase, outcome: Outcome): boolean =>\n Phase.$is(\"Bootstrapping\")(phase) && Outcome.$is(\"GenerationFailed\")(outcome);\n\nexport const needsDeploymentNotification = (phase: Phase): boolean =>\n Phase.$match(phase, {\n Bootstrapping: () => true,\n NeedsFullSync: () => true,\n Incremental: ({ failedImpls }) => !HashSet.isEmpty(failedImpls),\n });\n\nexport const implsToValidate = (\n phase: Phase,\n pending: Pending,\n): ReadonlyArray<ImplModulePath> =>\n Array.fromIterable(\n HashSet.union(\n Phase.$match(phase, {\n Bootstrapping: () => HashSet.empty<ImplModulePath>(),\n NeedsFullSync: () => HashSet.empty<ImplModulePath>(),\n Incremental: ({ failedImpls }) => failedImpls,\n }),\n Work.$match(pending.work, {\n None: () => HashSet.empty<ImplModulePath>(),\n Reconcile: () => HashSet.empty<ImplModulePath>(),\n Full: () => HashSet.empty<ImplModulePath>(),\n Impls: ({ paths }) => HashSet.fromIterable(paths),\n Declarations: ({ paths }) => HashSet.fromIterable(paths),\n }),\n ),\n );\n\nexport type Operation = Data.TaggedEnum<{\n Generate: {};\n Validate: {\n readonly snapshot: GenerationSnapshot;\n readonly paths: ReadonlyArray<ImplModulePath>;\n };\n Update: {\n readonly snapshot: GenerationSnapshot;\n readonly declarations: Array.NonEmptyReadonlyArray<Declaration>;\n readonly paths: ReadonlyArray<ImplModulePath>;\n };\n}>;\nexport const Operation = Data.taggedEnum<Operation>();\n\nexport const plan = (phase: Phase, pending: Pending): Operation =>\n Phase.$match(phase, {\n Bootstrapping: () => Operation.Generate(),\n NeedsFullSync: () => Operation.Generate(),\n Incremental: (ready) =>\n Match.value(pending.work).pipe(\n Match.tag(\"Full\", () => Operation.Generate()),\n Match.tag(\"None\", \"Reconcile\", \"Impls\", () =>\n Operation.Validate({\n snapshot: ready.snapshot,\n paths: implsToValidate(ready, pending),\n }),\n ),\n Match.tag(\"Declarations\", ({ entries }) =>\n Operation.Update({\n snapshot: ready.snapshot,\n declarations: entries,\n paths: implsToValidate(ready, pending),\n }),\n ),\n Match.exhaustive,\n ),\n });\n"],"mappings":";;;;;;AAmBA,MAAa,OAAO,KAAK,WAAiB;AAO1C,MAAa,QAAiB;CAAE,MAAM,KAAK,KAAK;CAAG,UAAU,QAAQ,MAAM;AAAE;AAC7E,MAAa,WAAW,YACtB,CAAC,KAAK,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,KAAK,CAAC,QAAQ,QAAQ,QAAQ,QAAQ;AACtE,MAAa,QAAQ,aAA+B;CAClD,GAAG;CACH,MAAM,KAAK,KAAK;AAClB;AAEA,MAAa,aAAa,aAA+B;CACvD,GAAG;CACH,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI,IAAI,KAAK,UAAU,IAAI,QAAQ;AACpE;AAEA,MAAa,OACX,SACA,SACA,YAAqB,UACT;CACZ,MAAM,OAAO,MAAM,OACjB,SACA;EACE,WAAW,aAAa,KAAK,IAAI,MAAM,CAAC,CAAC,QAAQ,IAAI;EACrD,OAAO,KAAK,OAAO,QAAQ,MAAM;GAC/B,YAAY,QAAQ,MAAsB;GAC1C,iBAAiB,QAAQ,MAAsB;GAC/C,YAAY,QAAQ,MAAsB;GAC1C,QAAQ,EAAE,YAAY,QAAQ,aAAa,KAAK;GAChD,eAAe,EAAE,YAAY,QAAQ,aAAa,KAAK;EACzD,CAAC;EACD,cAAc,KAAK,OAAO,QAAQ,MAAM;GACtC,YAAY,QAAQ,MAA2B;GAC/C,iBAAiB,QAAQ,MAA2B;GACpD,YAAY,QAAQ,MAA2B;GAC/C,aAAa,QAAQ,MAA2B;GAChD,eAAe,EAAE,SAAS,mBACxB,QAAQ,aACN,MAAM,IACJ,eACC,UACC,CAAC,GAAG,MAAM,KAA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Ac,YACjC,MAAM,OAAO,OAAO;CAClB,qBAAqB,UAAU,SAAS;CACxC,qBAAqB,UAAU,SAAS;CACxC,cAAc,UACZ,MAAM,MAAM,QAAQ,IAAI,CAAC,CAAC,KACxB,MAAM,IAAI,cAAc,UAAU,SAAS,CAAC,GAC5C,MAAM,IAAI,QAAQ,aAAa,eAC7B,UAAU,SAAS;EACjB,UAAU,MAAM;EAChB,OAAO,gBAAgB,OAAO,OAAO;CACvC,CAAC,CACH,GACA,MAAM,IAAI,iBAAiB,EAAE,cAC3B,UAAU,OAAO;EACf,UAAU,MAAM;EAChB,cAAc;EACd,OAAO,gBAAgB,OAAO,OAAO;CACvC,CAAC,CACH,GACA,MAAM,UACR;AACJ,CAAC"}
1
+ {"version":3,"file":"SyncState.mjs","names":[],"sources":["../src/SyncState.ts"],"sourcesContent":["import * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport type { Declaration, Kind, OptionalFile } from \"./EntryPoint.js\";\nimport type { ImplModulePath } from \"./ImplModulePath.js\";\nimport type { GenerationSnapshot } from \"./GenerationSnapshot.js\";\n\nexport type Work = Data.TaggedEnum<{\n None: {};\n Reconcile: {};\n Full: {};\n Impls: { readonly paths: Array.NonEmptyReadonlyArray<ImplModulePath> };\n Declarations: {\n readonly entries: Array.NonEmptyReadonlyArray<Declaration>;\n readonly paths: ReadonlyArray<ImplModulePath>;\n };\n}>;\nexport const Work = Data.taggedEnum<Work>();\n\nexport interface Pending {\n readonly work: Work;\n readonly optional: HashSet.HashSet<OptionalFile>;\n}\n\nexport const empty: Pending = { work: Work.None(), optional: HashSet.empty() };\nexport const isDirty = (pending: Pending): boolean =>\n !Work.$is(\"None\")(pending.work) || !HashSet.isEmpty(pending.optional);\nexport const full = (pending: Pending): Pending => ({\n ...pending,\n work: Work.Full(),\n});\n\nexport const reconcile = (pending: Pending): Pending => ({\n ...pending,\n work: Work.$is(\"None\")(pending.work) ? Work.Reconcile() : pending.work,\n});\n\nexport const add = (\n pending: Pending,\n entries: ReadonlyArray<Kind>,\n forceFull: boolean = false,\n): Pending => {\n const next = Array.reduce(\n entries,\n {\n needsFull: forceFull || Work.$is(\"Full\")(pending.work),\n paths: Work.$match(pending.work, {\n None: () => HashSet.empty<ImplModulePath>(),\n Reconcile: () => HashSet.empty<ImplModulePath>(),\n Full: () => HashSet.empty<ImplModulePath>(),\n Impls: ({ paths }) => HashSet.fromIterable(paths),\n Declarations: ({ paths }) => HashSet.fromIterable(paths),\n }),\n declarations: Work.$match(pending.work, {\n None: () => HashMap.empty<string, Declaration>(),\n Reconcile: () => HashMap.empty<string, Declaration>(),\n Full: () => HashMap.empty<string, Declaration>(),\n Impls: () => HashMap.empty<string, Declaration>(),\n Declarations: ({ entries: declarations }) =>\n HashMap.fromIterable(\n Array.map(\n declarations,\n (entry) =>\n [`${entry._tag}:${entry.relativePath}`, entry] as const,\n ),\n ),\n }),\n optional: pending.optional,\n },\n (state, entry) =>\n Match.value(entry).pipe(\n Match.tag(\"Impl\", ({ relativePath }) => ({\n ...state,\n paths: HashSet.add(state.paths, relativePath),\n })),\n Match.tag(\"Http\", \"Crons\", \"Auth\", ({ _tag }) => ({\n ...state,\n optional: HashSet.add(state.optional, _tag),\n })),\n Match.tag(\"Spec\", \"Table\", (declaration) => ({\n ...state,\n declarations: HashMap.set(\n state.declarations,\n `${declaration._tag}:${declaration.relativePath}`,\n declaration,\n ),\n })),\n Match.tag(\"Config\", \"Env\", \"App\", \"Callbacks\", \"Runtime\", () => ({\n ...state,\n needsFull: true,\n })),\n Match.exhaustive,\n ),\n );\n const impls = Array.fromIterable(next.paths);\n const declarations = next.declarations.pipe(\n HashMap.values,\n Array.fromIterable,\n );\n return {\n work: next.needsFull\n ? Work.Full()\n : Array.isReadonlyArrayNonEmpty(declarations)\n ? Work.Declarations({ entries: declarations, paths: impls })\n : Array.isReadonlyArrayNonEmpty(impls)\n ? Work.Impls({ paths: impls })\n : Work.$is(\"Reconcile\")(pending.work)\n ? Work.Reconcile()\n : Work.None(),\n optional: next.optional,\n };\n};\n\nexport interface Backend {\n readonly declared: boolean;\n readonly component: boolean;\n}\n\n/**\n * Full generation writes a declared backend's `convex/http.ts`, `crons.ts` and\n * `auth.config.ts` and rejects a component's `auth.ts`, so those edits need it\n * instead of the optional-file writers.\n */\nexport const forBackend = (pending: Pending, backend: Backend): Pending => {\n const generated = HashSet.filter(pending.optional, (file) =>\n Match.value(file).pipe(\n Match.when(\"Http\", () => backend.declared),\n Match.when(\"Auth\", () => backend.declared || backend.component),\n Match.when(\"Crons\", () => backend.declared),\n Match.exhaustive,\n ),\n );\n if (HashSet.isEmpty(generated)) return pending;\n return {\n work: Work.Full(),\n optional: backend.declared\n ? HashSet.difference(pending.optional, generated)\n : pending.optional,\n };\n};\n\nexport type Phase = Data.TaggedEnum<{\n Bootstrapping: {};\n NeedsFullSync: {};\n Incremental: {\n readonly failedImpls: HashSet.HashSet<ImplModulePath>;\n readonly snapshot: GenerationSnapshot;\n };\n}>;\nexport const Phase = Data.taggedEnum<Phase>();\n\nexport type Outcome = Data.TaggedEnum<{\n Succeeded: { readonly snapshot: GenerationSnapshot };\n GenerationFailed: {};\n ReconciliationFailed: {};\n ValidationFailed: {\n readonly snapshot: GenerationSnapshot;\n readonly paths: Array.NonEmptyReadonlyArray<ImplModulePath>;\n };\n}>;\nexport const Outcome = Data.taggedEnum<Outcome>();\n\nexport const transition = (outcome: Outcome): Phase =>\n Outcome.$match(outcome, {\n Succeeded: ({ snapshot }) =>\n Phase.Incremental({\n snapshot,\n failedImpls: HashSet.empty(),\n }),\n GenerationFailed: () => Phase.NeedsFullSync(),\n ReconciliationFailed: () => Phase.NeedsFullSync(),\n ValidationFailed: ({ snapshot, paths }) =>\n Phase.Incremental({\n snapshot,\n failedImpls: HashSet.fromIterable(paths),\n }),\n });\n\nexport const shouldRetry = (phase: Phase, outcome: Outcome): boolean =>\n Phase.$is(\"Bootstrapping\")(phase) && Outcome.$is(\"GenerationFailed\")(outcome);\n\nexport const needsDeploymentNotification = (phase: Phase): boolean =>\n Phase.$match(phase, {\n Bootstrapping: () => true,\n NeedsFullSync: () => true,\n Incremental: ({ failedImpls }) => !HashSet.isEmpty(failedImpls),\n });\n\nexport const implsToValidate = (\n phase: Phase,\n pending: Pending,\n): ReadonlyArray<ImplModulePath> =>\n Array.fromIterable(\n HashSet.union(\n Phase.$match(phase, {\n Bootstrapping: () => HashSet.empty<ImplModulePath>(),\n NeedsFullSync: () => HashSet.empty<ImplModulePath>(),\n Incremental: ({ failedImpls }) => failedImpls,\n }),\n Work.$match(pending.work, {\n None: () => HashSet.empty<ImplModulePath>(),\n Reconcile: () => HashSet.empty<ImplModulePath>(),\n Full: () => HashSet.empty<ImplModulePath>(),\n Impls: ({ paths }) => HashSet.fromIterable(paths),\n Declarations: ({ paths }) => HashSet.fromIterable(paths),\n }),\n ),\n );\n\nexport type Operation = Data.TaggedEnum<{\n Generate: {};\n Validate: {\n readonly snapshot: GenerationSnapshot;\n readonly paths: ReadonlyArray<ImplModulePath>;\n };\n Update: {\n readonly snapshot: GenerationSnapshot;\n readonly declarations: Array.NonEmptyReadonlyArray<Declaration>;\n readonly paths: ReadonlyArray<ImplModulePath>;\n };\n}>;\nexport const Operation = Data.taggedEnum<Operation>();\n\nexport const plan = (phase: Phase, pending: Pending): Operation =>\n Phase.$match(phase, {\n Bootstrapping: () => Operation.Generate(),\n NeedsFullSync: () => Operation.Generate(),\n Incremental: (ready) =>\n Match.value(pending.work).pipe(\n Match.tag(\"Full\", () => Operation.Generate()),\n Match.tag(\"None\", \"Reconcile\", \"Impls\", () =>\n Operation.Validate({\n snapshot: ready.snapshot,\n paths: implsToValidate(ready, pending),\n }),\n ),\n Match.tag(\"Declarations\", ({ entries }) =>\n Operation.Update({\n snapshot: ready.snapshot,\n declarations: entries,\n paths: implsToValidate(ready, pending),\n }),\n ),\n Match.exhaustive,\n ),\n });\n"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AAQ,aAAa,eAC7B,UAAU,SAAS;EACjB,UAAU,MAAM;EAChB,OAAO,gBAAgB,OAAO,OAAO;CACvC,CAAC,CACH,GACA,MAAM,IAAI,iBAAiB,EAAE,cAC3B,UAAU,OAAO;EACf,UAAU,MAAM;EAChB,cAAc;EACd,OAAO,gBAAgB,OAAO,OAAO;CACvC,CAAC,CACH,GACA,MAAM,UACR;AACJ,CAAC"}
@@ -121,7 +121,7 @@ const generateWithSnapshot = Effect.gen(function* () {
121
121
  onNone: () => generateHttp,
122
122
  onSome: (app) => syncDeclaredHttp(app, sections.files)
123
123
  })),
124
- logGenerated(generateCrons),
124
+ logGenerated(Option.isNone(declared) ? generateCrons() : syncDeclaredCrons(sections.crons)),
125
125
  Option.isNone(declared) ? logGenerated(generateAuthConfig) : Effect.succeedNone
126
126
  ], { concurrency: "unbounded" });
127
127
  yield* removeUnclaimed(sections.files);
@@ -172,6 +172,7 @@ const updateDeclarations = Effect.fn("Cli.updateDeclarations")(function* (snapsh
172
172
  yield* validateAllImpls(leaves, required);
173
173
  yield* generateGroupRegisteredFunctions(sections.changed ? all : leaves, required, sections.files);
174
174
  if (sections.changed && Option.isSome(declared)) yield* logGenerated(syncDeclaredHttp(declared.value, sections.files));
175
+ if (Option.isSome(declared)) yield* logGenerated(generateCrons(sections.crons));
175
176
  yield* removeUnclaimed(sections.files);
176
177
  yield* applyFunctionPlan(diff(snapshot, next));
177
178
  yield* verify(backend, mounts);
@@ -582,6 +583,23 @@ const provisionalComponents = Effect.gen(function* () {
582
583
  const components2 = yield* components({ components: [] });
583
584
  yield* writeFileStringAndLog(registry, components2);
584
585
  });
586
+ /**
587
+ * Write a declared backend's `convex/crons.ts`, or remove it once
588
+ * `confect/crons.ts` is gone. Its edits run full generation, so
589
+ * `assertOwnedEntrypoints` has proved an existing file is codegen's.
590
+ */
591
+ const syncDeclaredCrons = Effect.fnUntraced(function* (sectionFiles) {
592
+ const written = yield* generateCrons(sectionFiles);
593
+ const fs = yield* FileSystem.FileSystem;
594
+ const path = yield* Path.Path;
595
+ const convexDirectory = yield* ConvexDirectory.get;
596
+ const convexCrons = path.join(convexDirectory, "crons.ts");
597
+ if (Option.isNone(written) && (yield* fs.exists(convexCrons))) {
598
+ yield* fs.remove(convexCrons);
599
+ yield* logFileRemoved(convexCrons);
600
+ }
601
+ return written;
602
+ });
585
603
  const logGenerated = (effect) => effect.pipe(Effect.tap(Option.match({
586
604
  onNone: () => Effect.void,
587
605
  onSome: ({ change, convexFilePath }) => Match.value(change).pipe(Match.when("Added", () => logFileAdded(convexFilePath)), Match.when("Modified", () => logFileModified(convexFilePath)), Match.when("Unchanged", () => Effect.void), Match.exhaustive)