@gaganref/confect-cli 10.3.1-fork.6 → 10.3.1-fork.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Bundler.mjs +22 -1
- package/dist/Bundler.mjs.map +1 -1
- package/dist/CodegenError.mjs +16 -1
- package/dist/CodegenError.mjs.map +1 -1
- package/dist/Declaration.mjs +84 -18
- package/dist/Declaration.mjs.map +1 -1
- package/dist/EntryPoint.mjs +2 -0
- package/dist/EntryPoint.mjs.map +1 -1
- package/dist/Evaluation.mjs +39 -13
- package/dist/Evaluation.mjs.map +1 -1
- package/dist/EvaluationWorker.mjs +13 -1
- package/dist/EvaluationWorker.mjs.map +1 -1
- package/dist/FunctionModule.mjs +94 -13
- package/dist/FunctionModule.mjs.map +1 -1
- package/dist/LeafModule.mjs +28 -16
- package/dist/LeafModule.mjs.map +1 -1
- package/dist/ManifestSections.mjs +122 -0
- package/dist/ManifestSections.mjs.map +1 -0
- package/dist/SectionFiles.mjs +191 -0
- package/dist/SectionFiles.mjs.map +1 -0
- package/dist/SyncState.mjs +1 -1
- package/dist/SyncState.mjs.map +1 -1
- package/dist/Watcher.mjs +60 -56
- package/dist/Watcher.mjs.map +1 -1
- package/dist/confect/codegen.mjs +107 -54
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +71 -16
- package/dist/confect/declaration.mjs.map +1 -1
- package/dist/confect/dev.mjs +9 -4
- package/dist/confect/dev.mjs.map +1 -1
- package/dist/templates.mjs +52 -33
- package/dist/templates.mjs.map +1 -1
- package/package.json +6 -5
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { fromBundlerError } from "./BuildError.mjs";
|
|
2
|
+
import { logFileRemoved } from "./log.mjs";
|
|
3
|
+
import { bundle } from "./Bundler.mjs";
|
|
4
|
+
import { InvalidManifestSectionError, logCodegenError } from "./CodegenError.mjs";
|
|
5
|
+
import { ConfectDirectory } from "./ConfectDirectory.mjs";
|
|
6
|
+
import { removePathIfExists, toPosixPath, writeFileStringAndLog } from "./utils.mjs";
|
|
7
|
+
import * as Effect from "effect/Effect";
|
|
8
|
+
import * as FileSystem from "effect/FileSystem";
|
|
9
|
+
import * as Path from "effect/Path";
|
|
10
|
+
import * as Result from "effect/Result";
|
|
11
|
+
import * as Option from "effect/Option";
|
|
12
|
+
import * as Schema from "effect/Schema";
|
|
13
|
+
//#region src/SectionFiles.ts
|
|
14
|
+
/**
|
|
15
|
+
* The files codegen writes directly in `confect/_generated`, current and
|
|
16
|
+
* legacy, which no section may claim.
|
|
17
|
+
*/
|
|
18
|
+
const builtIn = new Set(`spec schema convexSchema id components component refs docs services manifest
|
|
19
|
+
auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions
|
|
20
|
+
nodeRegisteredFunctions`.split(/\s+/).map((name) => `${name}.ts`));
|
|
21
|
+
const PREFIX = "// Generated by `confect codegen` from the manifest section ";
|
|
22
|
+
const header = (key) => `${PREFIX}${JSON.stringify(key)}. Do not edit.`;
|
|
23
|
+
const Sources = Schema.fromJsonString(Schema.Array(Schema.String));
|
|
24
|
+
const encodeSources = Schema.encodeSync(Sources);
|
|
25
|
+
const decodeSources = Schema.decodeUnknownOption(Sources);
|
|
26
|
+
const INPUTS = "sectionInputs.json";
|
|
27
|
+
const visit = (leaves, each) => {
|
|
28
|
+
const walk = (group, path, source) => {
|
|
29
|
+
for (const spec of Object.values(group.functions)) each(spec, `${path}:${spec.name}`, source);
|
|
30
|
+
for (const [name, child] of Object.entries(group.groups)) walk(child, `${path}/${name}`, source);
|
|
31
|
+
};
|
|
32
|
+
for (const leaf of leaves) walk(leaf.spec, leaf.pathSegments.join("/"), leaf.relativePath);
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* One claim per section key that generates a file, ordered by file. A name that
|
|
36
|
+
* is built in, not a `.ts` file directly in `_generated`, or claimed by two
|
|
37
|
+
* keys is refused.
|
|
38
|
+
*/
|
|
39
|
+
const claims = (leaves) => Result.gen(function* () {
|
|
40
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
41
|
+
visit(leaves, (spec) => {
|
|
42
|
+
for (const { key, section } of spec.manifestSections ?? []) if (section.generate !== void 0 && !byKey.has(key)) byKey.set(key, section.generate);
|
|
43
|
+
});
|
|
44
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
45
|
+
for (const [key, { file }] of byKey) {
|
|
46
|
+
const other = byFile.get(file);
|
|
47
|
+
const refusal = builtIn.has(file) ? `claims confect/_generated/${file}, which codegen writes itself.` : !/^[\w-]+\.ts$/.test(file) ? `claims ${JSON.stringify(file)}; name a .ts file directly inside confect/_generated.` : other !== void 0 ? `claims confect/_generated/${file}, which the manifest section ${JSON.stringify(other)} also claims.` : void 0;
|
|
48
|
+
if (refusal !== void 0) return yield* Result.fail(new InvalidManifestSectionError({
|
|
49
|
+
sectionKey: key,
|
|
50
|
+
reason: refusal
|
|
51
|
+
}));
|
|
52
|
+
byFile.set(file, key);
|
|
53
|
+
}
|
|
54
|
+
return [...byKey].map(([key, generate]) => ({
|
|
55
|
+
key,
|
|
56
|
+
generate
|
|
57
|
+
})).sort((a, b) => a.generate.file.localeCompare(b.generate.file));
|
|
58
|
+
});
|
|
59
|
+
const sourceFiles = Effect.gen(function* () {
|
|
60
|
+
const fs = yield* FileSystem.FileSystem;
|
|
61
|
+
const path = yield* Path.Path;
|
|
62
|
+
const confectDirectory = yield* ConfectDirectory.get;
|
|
63
|
+
return (yield* fs.readDirectory(confectDirectory, { recursive: true })).map((file) => toPosixPath(path, file)).filter((file) => file.endsWith(".ts") && !file.endsWith(".d.ts") && !file.split("/").includes("_generated")).sort();
|
|
64
|
+
});
|
|
65
|
+
const render = Effect.fnUntraced(function* ({ key, generate }, input, files, watched) {
|
|
66
|
+
const path = yield* Path.Path;
|
|
67
|
+
const confectDirectory = yield* ConfectDirectory.get;
|
|
68
|
+
const failed = (cause) => new InvalidManifestSectionError({
|
|
69
|
+
sectionKey: key,
|
|
70
|
+
reason: `generate failed: ${String(cause)}`
|
|
71
|
+
});
|
|
72
|
+
const matched = yield* Effect.try({
|
|
73
|
+
try: () => files.filter((file) => generate.match(file)),
|
|
74
|
+
catch: failed
|
|
75
|
+
});
|
|
76
|
+
for (const file of matched) watched.add(file);
|
|
77
|
+
const modules = yield* Effect.forEach(matched, (relativePath) => {
|
|
78
|
+
const entry = path.join(confectDirectory, relativePath);
|
|
79
|
+
return bundle(entry, { plugins: [{
|
|
80
|
+
name: "confect:section-inputs",
|
|
81
|
+
setup: (build) => build.onEnd(({ metafile }) => {
|
|
82
|
+
for (const loaded of Object.keys(metafile?.inputs ?? {})) {
|
|
83
|
+
const file = toPosixPath(path, path.relative(confectDirectory, path.resolve(path.dirname(entry), loaded)));
|
|
84
|
+
if (!file.startsWith("../") && !file.startsWith("_generated/")) watched.add(file);
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
}] }).pipe(Effect.map(({ module }) => ({
|
|
88
|
+
relativePath,
|
|
89
|
+
exports: module
|
|
90
|
+
})), Effect.mapError((error) => fromBundlerError(`confect/${relativePath}`, error)));
|
|
91
|
+
});
|
|
92
|
+
const { contents, errors } = yield* Effect.try({
|
|
93
|
+
try: () => generate.render({
|
|
94
|
+
...input,
|
|
95
|
+
modules
|
|
96
|
+
}),
|
|
97
|
+
catch: failed
|
|
98
|
+
});
|
|
99
|
+
const [error, ...more] = errors.map((reason) => new InvalidManifestSectionError({
|
|
100
|
+
sectionKey: key,
|
|
101
|
+
reason
|
|
102
|
+
}));
|
|
103
|
+
for (const other of more) yield* logCodegenError(other);
|
|
104
|
+
if (error !== void 0) return yield* error;
|
|
105
|
+
return {
|
|
106
|
+
modules,
|
|
107
|
+
contents: [
|
|
108
|
+
header(key),
|
|
109
|
+
`// Sources: ${encodeSources(matched)}`,
|
|
110
|
+
contents
|
|
111
|
+
].join("\n")
|
|
112
|
+
};
|
|
113
|
+
});
|
|
114
|
+
/**
|
|
115
|
+
* The files in `confect/_generated` a section wrote, which carry its header.
|
|
116
|
+
*/
|
|
117
|
+
const written = Effect.gen(function* () {
|
|
118
|
+
const fs = yield* FileSystem.FileSystem;
|
|
119
|
+
const path = yield* Path.Path;
|
|
120
|
+
const generated = path.join(yield* ConfectDirectory.get, "_generated");
|
|
121
|
+
if (!(yield* fs.exists(generated))) return [];
|
|
122
|
+
return yield* Effect.filter((yield* fs.readDirectory(generated)).filter((file) => file.endsWith(".ts")), (file) => fs.readFileString(path.join(generated, file)).pipe(Effect.map((contents) => contents.startsWith(PREFIX))));
|
|
123
|
+
});
|
|
124
|
+
/**
|
|
125
|
+
* The `confect/` files the generating sections matched and the `confect/` files
|
|
126
|
+
* those import, as recorded by the last codegen run that loaded them.
|
|
127
|
+
*/
|
|
128
|
+
const inputs = Effect.gen(function* () {
|
|
129
|
+
const fs = yield* FileSystem.FileSystem;
|
|
130
|
+
const record = (yield* Path.Path).join(yield* ConfectDirectory.get, "_generated", INPUTS);
|
|
131
|
+
const none = [];
|
|
132
|
+
if (!(yield* fs.exists(record))) return none;
|
|
133
|
+
return Option.getOrElse(decodeSources(yield* fs.readFileString(record)), () => none);
|
|
134
|
+
});
|
|
135
|
+
/**
|
|
136
|
+
* Write each claimed file into `confect/_generated` once every section has
|
|
137
|
+
* rendered. Every section renders before codegen fails with the first error
|
|
138
|
+
* after logging the rest. The record of section inputs is written either way,
|
|
139
|
+
* keeping the previous inputs after a failure, so `confect dev` sees the fix.
|
|
140
|
+
* Returns the claimed file names, whether they differ from the section files
|
|
141
|
+
* that existed before, and the modules each section key matched.
|
|
142
|
+
*/
|
|
143
|
+
const sync = Effect.fnUntraced(function* (leaves, mounts) {
|
|
144
|
+
const path = yield* Path.Path;
|
|
145
|
+
const generated = path.join(yield* ConfectDirectory.get, "_generated");
|
|
146
|
+
const claimed = yield* Effect.fromResult(claims(leaves));
|
|
147
|
+
const functions = [];
|
|
148
|
+
visit(leaves, (_, functionPath, source) => functions.push({
|
|
149
|
+
path: functionPath,
|
|
150
|
+
source
|
|
151
|
+
}));
|
|
152
|
+
const files = claimed.length === 0 ? [] : yield* sourceFiles;
|
|
153
|
+
const watched = /* @__PURE__ */ new Set();
|
|
154
|
+
const [rendered, failures] = yield* Effect.partition(claimed, (claim) => render(claim, {
|
|
155
|
+
functions,
|
|
156
|
+
mounts
|
|
157
|
+
}, files, watched).pipe(Effect.map((output) => ({
|
|
158
|
+
...claim,
|
|
159
|
+
...output
|
|
160
|
+
}))));
|
|
161
|
+
if (failures.length > 0) for (const file of yield* inputs) watched.add(file);
|
|
162
|
+
yield* claimed.length === 0 ? removePathIfExists(path.join(generated, INPUTS)) : writeFileStringAndLog(path.join(generated, INPUTS), encodeSources([...watched].sort()));
|
|
163
|
+
const [error, ...more] = failures;
|
|
164
|
+
for (const other of more) yield* logCodegenError(other);
|
|
165
|
+
if (error !== void 0) return yield* error;
|
|
166
|
+
const existing = yield* written;
|
|
167
|
+
for (const { generate, contents } of rendered) yield* writeFileStringAndLog(path.join(generated, generate.file), contents);
|
|
168
|
+
const names = rendered.map(({ generate }) => generate.file);
|
|
169
|
+
return {
|
|
170
|
+
modules: new Map(rendered.map(({ key, modules }) => [key, modules])),
|
|
171
|
+
files: names,
|
|
172
|
+
changed: names.length !== existing.length || names.some((file) => !existing.includes(file))
|
|
173
|
+
};
|
|
174
|
+
});
|
|
175
|
+
/**
|
|
176
|
+
* Remove each file a section wrote that is not in `files`. Codegen runs this
|
|
177
|
+
* after it rewrites the registration files and the HTTP router, so a run that
|
|
178
|
+
* fails earlier leaves no import of a removed file.
|
|
179
|
+
*/
|
|
180
|
+
const removeUnclaimed = Effect.fnUntraced(function* (files) {
|
|
181
|
+
const path = yield* Path.Path;
|
|
182
|
+
const generated = path.join(yield* ConfectDirectory.get, "_generated");
|
|
183
|
+
for (const file of yield* written) if (!files.includes(file)) {
|
|
184
|
+
yield* removePathIfExists(path.join(generated, file));
|
|
185
|
+
yield* logFileRemoved(path.join(generated, file));
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
//#endregion
|
|
189
|
+
export { builtIn, claims, inputs, removeUnclaimed, sync, written };
|
|
190
|
+
|
|
191
|
+
//# sourceMappingURL=SectionFiles.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SectionFiles.mjs","names":["Bundler.bundle"],"sources":["../src/SectionFiles.ts"],"sourcesContent":["import type { FunctionSpec, GroupSpec, ManifestSection } from \"@confect/core\";\nimport type * as esbuild from \"esbuild\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { fromBundlerError } from \"./BuildError.js\";\nimport * as Bundler from \"./Bundler.js\";\nimport {\n InvalidManifestSectionError,\n logCodegenError,\n} from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport type { LoadedLeafModule } from \"./LeafModule.js\";\nimport { logFileRemoved } from \"./log.js\";\nimport {\n removePathIfExists,\n toPosixPath,\n writeFileStringAndLog,\n} from \"./utils.js\";\n\ntype Leaf = Pick<LoadedLeafModule, \"spec\" | \"pathSegments\" | \"relativePath\">;\n\n/**\n * The files codegen writes directly in `confect/_generated`, current and\n * legacy, which no section may claim.\n */\nexport const builtIn: ReadonlySet<string> = new Set(\n `spec schema convexSchema id components component refs docs services manifest\n auth.providers testing api nodeApi impl nodeImpl nodeSpec registeredFunctions\n nodeRegisteredFunctions`\n .split(/\\s+/)\n .map((name) => `${name}.ts`),\n);\n\nconst PREFIX = \"// Generated by `confect codegen` from the manifest section \";\nconst header = (key: string) => `${PREFIX}${JSON.stringify(key)}. Do not edit.`;\nconst Sources = Schema.fromJsonString(Schema.Array(Schema.String));\nconst encodeSources = Schema.encodeSync(Sources);\nconst decodeSources = Schema.decodeUnknownOption(Sources);\nconst INPUTS = \"sectionInputs.json\";\n\ninterface Claim {\n readonly key: string;\n readonly generate: ManifestSection.Generate;\n}\n\nconst visit = (\n leaves: ReadonlyArray<Leaf>,\n each: (spec: FunctionSpec.AnyWithProps, path: string, source: string) => void,\n) => {\n const walk = (\n group: GroupSpec.AnyWithProps,\n path: string,\n source: string,\n ) => {\n for (const spec of Object.values(group.functions))\n each(spec, `${path}:${spec.name}`, source);\n for (const [name, child] of Object.entries(group.groups))\n walk(child, `${path}/${name}`, source);\n };\n for (const leaf of leaves)\n walk(leaf.spec, leaf.pathSegments.join(\"/\"), leaf.relativePath);\n};\n\n/**\n * One claim per section key that generates a file, ordered by file. A name that\n * is built in, not a `.ts` file directly in `_generated`, or claimed by two\n * keys is refused.\n */\nexport const claims = (leaves: ReadonlyArray<Leaf>) =>\n Result.gen(function* () {\n const byKey = new Map<string, ManifestSection.Generate>();\n visit(leaves, (spec) => {\n for (const { key, section } of spec.manifestSections ?? [])\n if (section.generate !== undefined && !byKey.has(key))\n byKey.set(key, section.generate);\n });\n const byFile = new Map<string, string>();\n for (const [key, { file }] of byKey) {\n const other = byFile.get(file);\n const refusal = builtIn.has(file)\n ? `claims confect/_generated/${file}, which codegen writes itself.`\n : !/^[\\w-]+\\.ts$/.test(file)\n ? `claims ${JSON.stringify(file)}; name a .ts file directly inside confect/_generated.`\n : other !== undefined\n ? `claims confect/_generated/${file}, which the manifest section ${JSON.stringify(other)} also claims.`\n : undefined;\n if (refusal !== undefined)\n return yield* Result.fail(\n new InvalidManifestSectionError({ sectionKey: key, reason: refusal }),\n );\n byFile.set(file, key);\n }\n return [...byKey]\n .map(([key, generate]) => ({ key, generate }))\n .sort((a, b) => a.generate.file.localeCompare(b.generate.file));\n });\n\nconst sourceFiles = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n return (yield* fs.readDirectory(confectDirectory, { recursive: true }))\n .map((file) => toPosixPath(path, file))\n .filter(\n (file) =>\n file.endsWith(\".ts\") &&\n !file.endsWith(\".d.ts\") &&\n !file.split(\"/\").includes(\"_generated\"),\n )\n .sort();\n});\n\nconst render = Effect.fnUntraced(function* (\n { key, generate }: Claim,\n input: Omit<ManifestSection.GenerateInput, \"modules\">,\n files: ReadonlyArray<string>,\n watched: Set<string>,\n) {\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const failed = (cause: unknown) =>\n new InvalidManifestSectionError({\n sectionKey: key,\n reason: `generate failed: ${String(cause)}`,\n });\n const matched = yield* Effect.try({\n try: () => files.filter((file) => generate.match(file)),\n catch: failed,\n });\n for (const file of matched) watched.add(file);\n const modules = yield* Effect.forEach(matched, (relativePath) => {\n const entry = path.join(confectDirectory, relativePath);\n // Inputs are recorded once esbuild finishes, before the module runs, so a\n // module that throws on load still has its imports watched. `confect dev`\n // sees changes only under `confect/`, and every run rewrites `_generated`,\n // so watching it would loop.\n const recordInputs: esbuild.Plugin = {\n name: \"confect:section-inputs\",\n setup: (build) =>\n build.onEnd(({ metafile }) => {\n for (const loaded of Object.keys(metafile?.inputs ?? {})) {\n const file = toPosixPath(\n path,\n path.relative(\n confectDirectory,\n path.resolve(path.dirname(entry), loaded),\n ),\n );\n if (!file.startsWith(\"../\") && !file.startsWith(\"_generated/\"))\n watched.add(file);\n }\n }),\n };\n return Bundler.bundle(entry, { plugins: [recordInputs] }).pipe(\n Effect.map(({ module }) => ({ relativePath, exports: module })),\n Effect.mapError((error) =>\n fromBundlerError(`confect/${relativePath}`, error),\n ),\n );\n });\n const { contents, errors } = yield* Effect.try({\n try: () => generate.render({ ...input, modules }),\n catch: failed,\n });\n const [error, ...more] = errors.map(\n (reason) => new InvalidManifestSectionError({ sectionKey: key, reason }),\n );\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n return {\n modules,\n contents: [\n header(key),\n `// Sources: ${encodeSources(matched)}`,\n contents,\n ].join(\"\\n\"),\n };\n});\n\n/**\n * The files in `confect/_generated` a section wrote, which carry its header.\n */\nexport const written = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n if (!(yield* fs.exists(generated))) return [];\n return yield* Effect.filter(\n (yield* fs.readDirectory(generated)).filter((file) => file.endsWith(\".ts\")),\n (file) =>\n fs\n .readFileString(path.join(generated, file))\n .pipe(Effect.map((contents) => contents.startsWith(PREFIX))),\n );\n});\n\n/**\n * The `confect/` files the generating sections matched and the `confect/` files\n * those import, as recorded by the last codegen run that loaded them.\n */\nexport const inputs = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const record = path.join(yield* ConfectDirectory.get, \"_generated\", INPUTS);\n const none: ReadonlyArray<string> = [];\n if (!(yield* fs.exists(record))) return none;\n return Option.getOrElse(\n decodeSources(yield* fs.readFileString(record)),\n () => none,\n );\n});\n\n/**\n * Write each claimed file into `confect/_generated` once every section has\n * rendered. Every section renders before codegen fails with the first error\n * after logging the rest. The record of section inputs is written either way,\n * keeping the previous inputs after a failure, so `confect dev` sees the fix.\n * Returns the claimed file names, whether they differ from the section files\n * that existed before, and the modules each section key matched.\n */\nexport const sync = Effect.fnUntraced(function* (\n leaves: ReadonlyArray<Leaf>,\n mounts: ManifestSection.GenerateInput[\"mounts\"],\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n const claimed = yield* Effect.fromResult(claims(leaves));\n const functions: Array<{ path: string; source: string }> = [];\n visit(leaves, (_, functionPath, source) =>\n functions.push({ path: functionPath, source }),\n );\n const files = claimed.length === 0 ? [] : yield* sourceFiles;\n const watched = new Set<string>();\n const [rendered, failures] = yield* Effect.partition(claimed, (claim) =>\n render(claim, { functions, mounts }, files, watched).pipe(\n Effect.map((output) => ({ ...claim, ...output })),\n ),\n );\n if (failures.length > 0) for (const file of yield* inputs) watched.add(file);\n yield* claimed.length === 0\n ? removePathIfExists(path.join(generated, INPUTS))\n : writeFileStringAndLog(\n path.join(generated, INPUTS),\n encodeSources([...watched].sort()),\n );\n const [error, ...more] = failures;\n for (const other of more) yield* logCodegenError(other);\n if (error !== undefined) return yield* error;\n const existing = yield* written;\n for (const { generate, contents } of rendered)\n yield* writeFileStringAndLog(path.join(generated, generate.file), contents);\n const names = rendered.map(({ generate }) => generate.file);\n return {\n modules: new Map(rendered.map(({ key, modules }) => [key, modules])),\n files: names,\n changed:\n names.length !== existing.length ||\n names.some((file) => !existing.includes(file)),\n };\n});\n\n/**\n * Remove each file a section wrote that is not in `files`. Codegen runs this\n * after it rewrites the registration files and the HTTP router, so a run that\n * fails earlier leaves no import of a removed file.\n */\nexport const removeUnclaimed = Effect.fnUntraced(function* (\n files: ReadonlyArray<string>,\n) {\n const path = yield* Path.Path;\n const generated = path.join(yield* ConfectDirectory.get, \"_generated\");\n for (const file of yield* written)\n if (!files.includes(file)) {\n yield* removePathIfExists(path.join(generated, file));\n yield* logFileRemoved(path.join(generated, file));\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAa,UAA+B,IAAI,IAC9C;;2BAGG,MAAM,KAAK,CAAC,CACZ,KAAK,SAAS,GAAG,KAAK,IAAI,CAC/B;AAEA,MAAM,SAAS;AACf,MAAM,UAAU,QAAgB,GAAG,SAAS,KAAK,UAAU,GAAG,EAAE;AAChE,MAAM,UAAU,OAAO,eAAe,OAAO,MAAM,OAAO,MAAM,CAAC;AACjE,MAAM,gBAAgB,OAAO,WAAW,OAAO;AAC/C,MAAM,gBAAgB,OAAO,oBAAoB,OAAO;AACxD,MAAM,SAAS;AAOf,MAAM,SACJ,QACA,SACG;CACH,MAAM,QACJ,OACA,MACA,WACG;EACH,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,SAAS,GAC9C,KAAK,MAAM,GAAG,KAAK,GAAG,KAAK,QAAQ,MAAM;EAC3C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,MAAM,MAAM,GACrD,KAAK,OAAO,GAAG,KAAK,GAAG,QAAQ,MAAM;CACzC;CACA,KAAK,MAAM,QAA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E,MAAM,WAAW,SAAS,UAC1B,MAAM,MAAM,SAAS,CAAC,SAAS,SAAS,IAAI,CAAC;CACjD;AACF,CAAC;;;;;;AAOD,MAAa,kBAAkB,OAAO,WAAW,WAC/C,OACA;CACA,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,YAAY,KAAK,KAAK,OAAO,iBAAiB,KAAK,YAAY;CACrE,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"}
|
package/dist/SyncState.mjs
CHANGED
|
@@ -45,7 +45,7 @@ const add = (pending, entries, forceFull = false) => {
|
|
|
45
45
|
})), Match.tag("Spec", "Table", (declaration) => ({
|
|
46
46
|
...state,
|
|
47
47
|
declarations: HashMap.set(state.declarations, `${declaration._tag}:${declaration.relativePath}`, declaration)
|
|
48
|
-
})), Match.tag("Config", "Env", "App", "Callbacks", () => ({
|
|
48
|
+
})), Match.tag("Config", "Env", "App", "Callbacks", "Runtime", () => ({
|
|
49
49
|
...state,
|
|
50
50
|
needsFull: true
|
|
51
51
|
})), Match.exhaustive));
|
package/dist/SyncState.mjs.map
CHANGED
|
@@ -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 = 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 declarations.map(\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\", () => ({\n ...state,\n needsFull: true,\n })),\n Match.exhaustive,\n ),\n );\n const impls = Array.fromIterable(next.paths);\n const declarations = Array.fromIterable(HashMap.values(next.declarations));\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,YAAY,UACA;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,YAA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K;CAChD,eAAe,EAAE,YAAY,QAAQ,aAAa,KAAK;AACzD,CAAC,CACH,CACF;AAcF,MAAa,YAAY,KAAK,WAAsB;AAEpD,MAAa,QAAQ,OAAc,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 = 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 declarations.map(\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 = Array.fromIterable(HashMap.values(next.declarations));\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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AI,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"}
|
package/dist/Watcher.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { bundleWorkspacePlugin } from "./Bundler.mjs";
|
|
|
3
3
|
import { ConvexDirectory } from "./ConvexDirectory.mjs";
|
|
4
4
|
import { ConfectDirectory } from "./ConfectDirectory.mjs";
|
|
5
5
|
import "./ConvexConfig.mjs";
|
|
6
|
+
import { inputs } from "./SectionFiles.mjs";
|
|
6
7
|
import { Kind, discover, isOptional, parse } from "./EntryPoint.mjs";
|
|
7
8
|
import { add, empty, full, reconcile } from "./SyncState.mjs";
|
|
8
9
|
import { Change, Failure, Outcome, State, captureBarrier, complete, diagnostics, diff, emptyCapture, endRequest, getCompletion, initialProgress, isFresh, joinedWithoutCompletion, makeRequestId, observe, parse as parse$1, request, start, verifyInputs } from "./WatchBuild.mjs";
|
|
@@ -18,6 +19,7 @@ import * as HashSet from "effect/HashSet";
|
|
|
18
19
|
import * as Match from "effect/Match";
|
|
19
20
|
import * as Option from "effect/Option";
|
|
20
21
|
import { externalPlugin, loadTsConfig, tsconfigPathsToRegExp } from "bundle-require";
|
|
22
|
+
import * as Context from "effect/Context";
|
|
21
23
|
import * as HashMap from "effect/HashMap";
|
|
22
24
|
import * as Ref from "effect/Ref";
|
|
23
25
|
import * as Scope from "effect/Scope";
|
|
@@ -26,8 +28,8 @@ import * as esbuild from "esbuild";
|
|
|
26
28
|
import * as Order from "effect/Order";
|
|
27
29
|
import * as Data from "effect/Data";
|
|
28
30
|
import * as Schedule from "effect/Schedule";
|
|
29
|
-
import * as Clock from "effect/Clock";
|
|
30
31
|
import * as Duration from "effect/Duration";
|
|
32
|
+
import * as Clock from "effect/Clock";
|
|
31
33
|
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
|
|
32
34
|
import * as Crypto from "effect/Crypto";
|
|
33
35
|
import * as Hex from "effect/encoding/Hex";
|
|
@@ -37,7 +39,7 @@ import * as Queue from "effect/Queue";
|
|
|
37
39
|
import * as Semaphore from "effect/Semaphore";
|
|
38
40
|
import * as Stream from "effect/Stream";
|
|
39
41
|
//#region src/Watcher.ts
|
|
40
|
-
const
|
|
42
|
+
const CoalesceQuiescence = Context.Reference("@confect/cli/Watcher/CoalesceQuiescence", { defaultValue: () => Duration.millis(50) });
|
|
41
43
|
const COALESCE_MAX_WAIT = Duration.seconds(5);
|
|
42
44
|
const WatcherLifecycle = Data.taggedEnum();
|
|
43
45
|
const RefreshOutcome = Data.taggedEnum();
|
|
@@ -61,6 +63,7 @@ var OperationError = class extends Schema.TaggedError()("WatcherOperationError",
|
|
|
61
63
|
const ReportedBuildFailure = Schema.Struct({ errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })) });
|
|
62
64
|
const parseFailure = Schema.decodeUnknownOption(ReportedBuildFailure);
|
|
63
65
|
const make = Effect.fnUntraced(function* () {
|
|
66
|
+
const quiescence = yield* CoalesceQuiescence;
|
|
64
67
|
const signal = yield* Queue.sliding(1);
|
|
65
68
|
const pendingRef = yield* Ref.make(empty);
|
|
66
69
|
const restartQueue = yield* Queue.sliding(1);
|
|
@@ -88,7 +91,7 @@ const make = Effect.fnUntraced(function* () {
|
|
|
88
91
|
duringRestore: Effect.flatten(Ref.get(duringRestoreRef)),
|
|
89
92
|
discardRestoreEchoes: refresh(state).pipe(Effect.ignore, Effect.andThen(Ref.set(pendingRef, empty))),
|
|
90
93
|
refresh: refresh(state),
|
|
91
|
-
next: Queue.take(signal).pipe(Effect.andThen(drainUntilQuiescent(signal,
|
|
94
|
+
next: Queue.take(signal).pipe(Effect.andThen(drainUntilQuiescent(signal, quiescence, COALESCE_MAX_WAIT)), Effect.andThen(state.topology.takePending), Effect.onInterrupt(() => Queue.offer(signal, void 0))),
|
|
92
95
|
pending: Ref.get(pendingRef),
|
|
93
96
|
requestRetry: Ref.update(pendingRef, full).pipe(Effect.andThen(Queue.offer(signal, void 0)), Effect.asVoid),
|
|
94
97
|
diagnostics: Ref.get(state.observation).pipe(Effect.map(diagnostics))
|
|
@@ -98,7 +101,8 @@ const drainUntilQuiescent = Effect.fnUntraced(function* (signal, quiescence, max
|
|
|
98
101
|
const start = yield* Clock.currentTimeMillis;
|
|
99
102
|
const maxMillis = Duration.toMillis(maxWait);
|
|
100
103
|
const loop = Effect.gen(function* () {
|
|
101
|
-
yield*
|
|
104
|
+
const elapsed = (yield* Clock.currentTimeMillis) - start;
|
|
105
|
+
yield* Effect.sleep(Duration.millis(Math.min(Duration.toMillis(quiescence), Math.max(0, maxMillis - elapsed))));
|
|
102
106
|
if ((yield* Queue.clear(signal)).length === 0) return;
|
|
103
107
|
if ((yield* Clock.currentTimeMillis) - start < maxMillis) yield* loop;
|
|
104
108
|
});
|
|
@@ -193,6 +197,7 @@ const entryPointsWatcher = Effect.fnUntraced(function* (signal, pendingRef, rest
|
|
|
193
197
|
Empty: () => completedInitial,
|
|
194
198
|
Active: ({ initial: activeInitial }) => Effect.succeed(activeInitial)
|
|
195
199
|
});
|
|
200
|
+
yield* refreshCurrent(current).pipe(Effect.catchTag("WatcherOperationError", () => Ref.update(pendingRef, full)));
|
|
196
201
|
yield* watcher.topology.reconcile(revision, initial);
|
|
197
202
|
return;
|
|
198
203
|
}
|
|
@@ -263,59 +268,57 @@ const entryPointsWatcher = Effect.fnUntraced(function* (signal, pendingRef, rest
|
|
|
263
268
|
yield* sync;
|
|
264
269
|
return yield* Effect.forever(Queue.take(restartQueue).pipe(Effect.andThen(sync)));
|
|
265
270
|
}, Effect.provide(NodeCrypto.layer));
|
|
266
|
-
const
|
|
267
|
-
return yield*
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
const
|
|
292
|
-
if (
|
|
293
|
-
const rejected = parseFailure(built.failure.cause);
|
|
294
|
-
if (Option.isNone(rejected)) return yield* built.failure;
|
|
295
|
-
if (joinedWithoutCompletion(currentProgress)) return Option.none();
|
|
296
|
-
if (Option.isNone(completed) || !Outcome.$is("Failed")(completed.value.outcome)) return yield* new OperationError({
|
|
297
|
-
operation: "rebuild",
|
|
298
|
-
cause: rejected.value.errors
|
|
299
|
-
});
|
|
300
|
-
}
|
|
271
|
+
const refreshCurrent = Effect.fnUntraced(function* (current) {
|
|
272
|
+
return yield* WatcherLifecycle.$match(current, {
|
|
273
|
+
Empty: () => Effect.succeed(RefreshOutcome.Empty()),
|
|
274
|
+
Uninitialized: () => Effect.fail(new OperationError({
|
|
275
|
+
operation: "refresh",
|
|
276
|
+
cause: "The dependency watcher is not initialized"
|
|
277
|
+
})),
|
|
278
|
+
Active: ({ context, identifyRequest, progress, verifyInputs }) => Effect.gen(function* () {
|
|
279
|
+
const runSync = Effect.runSyncWith(yield* Effect.context());
|
|
280
|
+
const barrier = captureBarrier(yield* Ref.get(progress));
|
|
281
|
+
const completed = yield* Effect.gen(function* () {
|
|
282
|
+
const built = yield* Effect.tryPromise({
|
|
283
|
+
try: () => {
|
|
284
|
+
const promise = context.rebuild();
|
|
285
|
+
runSync(Ref.update(progress, (currentProgress) => request(currentProgress, identifyRequest(promise))));
|
|
286
|
+
return promise;
|
|
287
|
+
},
|
|
288
|
+
catch: (cause) => new OperationError({
|
|
289
|
+
operation: "rebuild",
|
|
290
|
+
cause
|
|
291
|
+
})
|
|
292
|
+
}).pipe(Effect.result);
|
|
293
|
+
const currentProgress = yield* Ref.get(progress);
|
|
294
|
+
const completed = getCompletion(currentProgress);
|
|
295
|
+
if (Result.isFailure(built)) {
|
|
296
|
+
const rejected = parseFailure(built.failure.cause);
|
|
297
|
+
if (Option.isNone(rejected)) return yield* built.failure;
|
|
301
298
|
if (joinedWithoutCompletion(currentProgress)) return Option.none();
|
|
302
|
-
|
|
299
|
+
if (Option.isNone(completed) || !Outcome.$is("Failed")(completed.value.outcome)) return yield* new OperationError({
|
|
303
300
|
operation: "rebuild",
|
|
304
|
-
cause:
|
|
305
|
-
})
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
301
|
+
cause: rejected.value.errors
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
if (joinedWithoutCompletion(currentProgress)) return Option.none();
|
|
305
|
+
const observed = yield* Effect.fromOption(completed).pipe(Effect.mapError(() => new OperationError({
|
|
306
|
+
operation: "rebuild",
|
|
307
|
+
cause: "esbuild completed without a build observation"
|
|
308
|
+
})));
|
|
309
|
+
if (isFresh(barrier, observed) && Outcome.$is("Succeeded")(observed.outcome)) {
|
|
310
|
+
if (!(yield* verifyInputs(observed.outcome.snapshot).pipe(Effect.mapError(({ cause }) => new OperationError({
|
|
311
|
+
operation: "refresh",
|
|
312
|
+
cause
|
|
313
|
+
}))))) return Option.none();
|
|
314
|
+
}
|
|
315
|
+
return Option.some(observed);
|
|
316
|
+
}).pipe(Effect.ensuring(Ref.update(progress, endRequest))).pipe(Effect.repeat({ while: (observed) => Option.isNone(observed) || !isFresh(barrier, observed.value) }), Effect.flatMap((observed) => Effect.fromOption(observed).pipe(Effect.orDie)));
|
|
317
|
+
return RefreshOutcome.Observed({ outcome: completed.outcome });
|
|
318
|
+
})
|
|
319
|
+
});
|
|
318
320
|
});
|
|
321
|
+
const refresh = (watcher) => watcher.lock.withPermit(Ref.get(watcher.lifecycle).pipe(Effect.flatMap(refreshCurrent)));
|
|
319
322
|
const confectStructureWatcher = Effect.fnUntraced(function* (signal, pendingRef, restart, restartEntry) {
|
|
320
323
|
const fs = yield* FileSystem.FileSystem;
|
|
321
324
|
const path = yield* Path.Path;
|
|
@@ -370,9 +373,10 @@ const handleConfectChange = ({ relativePath, eventTag, signal, pendingRef, resta
|
|
|
370
373
|
const entry = parse(relativePath);
|
|
371
374
|
if (Option.isSome(entry)) return isLifecycleChange ? restartEntry(entry.value) : Effect.void;
|
|
372
375
|
if (relativePath === "schema.ts") return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);
|
|
373
|
-
|
|
376
|
+
const source = relativePath.split(/[/\\]/).join("/");
|
|
377
|
+
return Match.value(eventTag).pipe(Match.when("Create", () => flipDirtyAndSignal(pendingRef, signal, restart, false)), Match.whenOr("Update", "Remove", () => inputs.pipe(Effect.map((inputs) => inputs.includes(source)), Effect.orElseSucceed(() => false), Effect.flatMap((listed) => listed ? flipDirtyAndSignal(pendingRef, signal, restart, false) : Effect.void))), Match.exhaustive);
|
|
374
378
|
};
|
|
375
379
|
//#endregion
|
|
376
|
-
export { OperationError, isRefreshSuccessful, make, parseFailure };
|
|
380
|
+
export { CoalesceQuiescence, OperationError, isRefreshSuccessful, make, parseFailure };
|
|
377
381
|
|
|
378
382
|
//# sourceMappingURL=Watcher.mjs.map
|