@gaganref/confect-cli 10.3.1-fork.96 → 10.6.0-fork.1
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/CHANGELOG.md +78 -0
- package/dist/Ansi.mjs +1 -2
- package/dist/BuildError.mjs +5 -5
- package/dist/BuildError.mjs.map +1 -1
- package/dist/Bundler.mjs +103 -76
- package/dist/Bundler.mjs.map +1 -1
- package/dist/CodeBlockWriter.mjs +1 -2
- package/dist/CodegenError.mjs +27 -17
- package/dist/CodegenError.mjs.map +1 -1
- package/dist/ConfectDirectory.mjs +8 -3
- package/dist/ConfectDirectory.mjs.map +1 -1
- package/dist/ConvexConfig.mjs +23 -15
- package/dist/ConvexConfig.mjs.map +1 -1
- package/dist/ConvexDirectory.mjs +6 -4
- package/dist/ConvexDirectory.mjs.map +1 -1
- package/dist/Declaration.mjs +92 -56
- package/dist/Declaration.mjs.map +1 -1
- package/dist/DirectoryOptions.mjs +13 -8
- package/dist/DirectoryOptions.mjs.map +1 -1
- package/dist/DocName.mjs +1 -2
- package/dist/EntryPoint.mjs +17 -15
- package/dist/EntryPoint.mjs.map +1 -1
- package/dist/Evaluation.mjs +24 -13
- package/dist/Evaluation.mjs.map +1 -1
- package/dist/EvaluationWorker.mjs +5 -6
- package/dist/EvaluationWorker.mjs.map +1 -1
- package/dist/FunctionModule.mjs +85 -47
- package/dist/FunctionModule.mjs.map +1 -1
- package/dist/FunctionPath.mjs +1 -2
- package/dist/FunctionPath.mjs.map +1 -1
- package/dist/FunctionPaths.mjs +2 -3
- package/dist/GenerationSnapshot.mjs +30 -22
- package/dist/GenerationSnapshot.mjs.map +1 -1
- package/dist/GroupPath.mjs +6 -3
- package/dist/GroupPath.mjs.map +1 -1
- package/dist/GroupPaths.mjs +1 -2
- package/dist/ImplModulePath.mjs +1 -2
- package/dist/Json.mjs +13 -0
- package/dist/Json.mjs.map +1 -0
- package/dist/LeafModule.mjs +121 -41
- package/dist/LeafModule.mjs.map +1 -1
- package/dist/ManifestSections.mjs +23 -19
- package/dist/ManifestSections.mjs.map +1 -1
- package/dist/PackageSelfReference.mjs +32 -0
- package/dist/PackageSelfReference.mjs.map +1 -0
- package/dist/ProjectRoot.mjs +11 -3
- package/dist/ProjectRoot.mjs.map +1 -1
- package/dist/RelativeModulePath.mjs +1 -2
- package/dist/Remove.mjs +2 -3
- package/dist/Remove.mjs.map +1 -1
- package/dist/RestoreWatcher.mjs +1 -2
- package/dist/Rollback.mjs +7 -6
- package/dist/Rollback.mjs.map +1 -1
- package/dist/SectionFiles.mjs +77 -48
- package/dist/SectionFiles.mjs.map +1 -1
- package/dist/SnapshotError.mjs +3 -3
- package/dist/SnapshotError.mjs.map +1 -1
- package/dist/SpecAssemblyNode.mjs +1 -2
- package/dist/SpecModulePath.mjs +4 -4
- package/dist/SpecModulePath.mjs.map +1 -1
- package/dist/SyncState.mjs +3 -4
- package/dist/SyncState.mjs.map +1 -1
- package/dist/TableModule.mjs +18 -10
- package/dist/TableModule.mjs.map +1 -1
- package/dist/TableModulePath.mjs +3 -3
- package/dist/TableModulePath.mjs.map +1 -1
- package/dist/TypeScriptConfig.mjs +135 -0
- package/dist/TypeScriptConfig.mjs.map +1 -0
- package/dist/WatchBuild.mjs +107 -32
- package/dist/WatchBuild.mjs.map +1 -1
- package/dist/WatchGraph.mjs +4 -4
- package/dist/WatchGraph.mjs.map +1 -1
- package/dist/WatchTopology.mjs +5 -4
- package/dist/WatchTopology.mjs.map +1 -1
- package/dist/Watcher.mjs +179 -108
- package/dist/Watcher.mjs.map +1 -1
- package/dist/cliApp.mjs +5 -3
- package/dist/cliApp.mjs.map +1 -1
- package/dist/confect/codegen.mjs +95 -53
- package/dist/confect/codegen.mjs.map +1 -1
- package/dist/confect/declaration.mjs +76 -42
- package/dist/confect/declaration.mjs.map +1 -1
- package/dist/confect/dev.mjs +18 -12
- package/dist/confect/dev.mjs.map +1 -1
- package/dist/confect.mjs +4 -2
- package/dist/confect.mjs.map +1 -1
- package/dist/index.mjs +1 -2
- package/dist/log.mjs +13 -5
- package/dist/log.mjs.map +1 -1
- package/dist/package.json.mjs +5 -0
- package/dist/package.json.mjs.map +1 -0
- package/dist/templates.mjs +34 -22
- package/dist/templates.mjs.map +1 -1
- package/dist/utils.mjs +36 -5
- package/dist/utils.mjs.map +1 -1
- package/package.json +10 -10
- package/dist/package.mjs +0 -6
- package/dist/package.mjs.map +0 -1
package/dist/Watcher.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Watcher.mjs","names":["SyncState.empty","WatchTopology.make","RestoreWatcher.make","SyncState.full","WatchBuild.diagnostics","Bundler.bundleWorkspacePlugin","WatchBuild.start","WatchBuild.emptyCapture","WatchBuild.parse","WatchBuild.observe","WatchBuild.diff","SyncState.add","SyncState.reconcile","WatchBuild.complete","EntryPoint.discover","EntryPoint.isOptional","WatchBuild.initialProgress","WatchBuild.makeRequestId","WatchBuild.verifyInputs","WatchBuild.captureBarrier","WatchBuild.request","WatchBuild.getCompletion","WatchBuild.joinedWithoutCompletion","WatchBuild.isFresh","WatchBuild.endRequest","EntryPoint.parse"],"sources":["../src/Watcher.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as NodeCrypto from \"@effect/platform-node/NodeCrypto\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Hex from \"effect/encoding/Hex\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Stream from \"effect/Stream\";\nimport {\n externalPlugin,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport * as esbuild from \"esbuild\";\nimport * as Bundler from \"./Bundler.js\";\nimport * as WatchBuild from \"./WatchBuild.js\";\nimport * as WatchTopology from \"./WatchTopology.js\";\nimport * as SyncState from \"./SyncState.js\";\nimport type { Pending } from \"./SyncState.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport type { EntryPoint as Entry } from \"./EntryPoint.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as RestoreWatcher from \"./RestoreWatcher.js\";\nimport * as SectionFiles from \"./SectionFiles.js\";\n\nexport const CoalesceQuiescence = Context.Reference<Duration.Duration>(\n \"@confect/cli/Watcher/CoalesceQuiescence\",\n { defaultValue: () => Duration.millis(50) },\n);\n\n// Upper bound on `drainUntilQuiescent` so a pathological infinite\n// signal stream can't pin the sync loop forever.\nconst COALESCE_MAX_WAIT = Duration.seconds(5);\n\ntype WatcherLifecycle = Data.TaggedEnum<{\n Uninitialized: {};\n Empty: {};\n Active: {\n readonly initial: Deferred.Deferred<void>;\n readonly key: string;\n readonly scope: Scope.Closeable;\n readonly entries: Array.NonEmptyReadonlyArray<Entry>;\n readonly context: esbuild.BuildContext;\n readonly identifyRequest: (\n promise: Promise<esbuild.BuildResult>,\n ) => WatchBuild.RequestId;\n readonly progress: Ref.Ref<WatchBuild.Progress>;\n readonly verifyInputs: (\n snapshot: WatchBuild.Snapshot,\n ) => ReturnType<typeof WatchBuild.verifyInputs>;\n };\n}>;\nconst WatcherLifecycle = Data.taggedEnum<WatcherLifecycle>();\n\ninterface State {\n readonly lifecycle: Ref.Ref<WatcherLifecycle>;\n readonly observation: Ref.Ref<WatchBuild.State>;\n readonly lock: Semaphore.Semaphore;\n readonly topology: WatchTopology.WatchTopology;\n // Whether the last discovery found `confect/app.ts`.\n readonly declared: Ref.Ref<boolean>;\n}\n\ntype RefreshOutcome = Data.TaggedEnum<{\n Empty: {};\n Observed: { readonly outcome: WatchBuild.Outcome };\n}>;\nconst RefreshOutcome = Data.taggedEnum<RefreshOutcome>();\n\nexport const isRefreshSuccessful = (outcome: RefreshOutcome): boolean =>\n RefreshOutcome.$match(outcome, {\n Empty: () => true,\n Observed: ({ outcome: observed }) =>\n WatchBuild.Outcome.$match(observed, {\n Succeeded: () => true,\n Failed: () => false,\n }),\n });\n\nexport class OperationError extends Schema.TaggedError<OperationError>()(\n \"WatcherOperationError\",\n {\n operation: Schema.Literals([\n \"create\",\n \"watch\",\n \"rebuild\",\n \"dispose\",\n \"refresh\",\n ]),\n cause: Schema.Unknown,\n },\n) {}\n\nconst ReportedBuildFailure = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })),\n});\nexport const parseFailure = Schema.decodeUnknownOption(ReportedBuildFailure);\n\nexport const make = Effect.fnUntraced(function* () {\n const quiescence = yield* CoalesceQuiescence;\n const signal = yield* Queue.sliding<void>(1);\n const pendingRef = yield* Ref.make<Pending>(SyncState.empty);\n const restartQueue = yield* Queue.sliding<void>(1);\n const state: State = {\n lifecycle: yield* Ref.make<WatcherLifecycle>(\n WatcherLifecycle.Uninitialized(),\n ),\n observation: yield* Ref.make<WatchBuild.State>(WatchBuild.State.Initial()),\n lock: yield* Semaphore.make(1),\n topology: yield* WatchTopology.make(pendingRef),\n declared: yield* Ref.make(false),\n };\n const restartWith = (invalidation: Effect.Effect<void>) =>\n invalidation.pipe(\n Effect.andThen(Queue.offer(restartQueue, undefined)),\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n const restart = restartWith(state.topology.invalidate);\n const restartEntry = (entry: EntryPoint.Kind) =>\n restartWith(state.topology.invalidateEntry(entry));\n const duringRestoreRef = yield* Ref.make<\n Effect.Effect<void, never, Scope.Scope>\n >(Effect.void);\n return {\n run: Effect.gen(function* () {\n const structure = yield* RestoreWatcher.make(\n confectStructureWatcher(signal, pendingRef, restart, restartEntry),\n );\n yield* Ref.set(duringRestoreRef, structure.duringRestore);\n yield* Effect.all(\n [\n Effect.scoped(\n entryPointsWatcher(signal, pendingRef, restartQueue, state),\n ),\n structure.failure,\n convexConfigStructureWatcher(restart, state.declared),\n ],\n { concurrency: \"unbounded\" },\n );\n }).pipe(Effect.scoped),\n duringRestore: Effect.flatten(Ref.get(duringRestoreRef)),\n // Restored output makes esbuild rebuild; observe that, then drop the work\n // it queued so the restore does not trigger another generation.\n discardRestoreEchoes: refresh(state).pipe(\n Effect.ignore,\n Effect.andThen(Ref.set(pendingRef, SyncState.empty)),\n ),\n refresh: refresh(state),\n next: Queue.take(signal).pipe(\n Effect.andThen(\n drainUntilQuiescent(signal, quiescence, COALESCE_MAX_WAIT),\n ),\n Effect.andThen(state.topology.takePending),\n Effect.onInterrupt(() => Queue.offer(signal, undefined)),\n ),\n pending: Ref.get(pendingRef),\n requestRetry: Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n Effect.asVoid,\n ),\n diagnostics: Ref.get(state.observation).pipe(\n Effect.map(WatchBuild.diagnostics),\n ),\n } as const;\n});\n\nexport type Watcher = Effect.Success<ReturnType<typeof make>>;\n\nconst drainUntilQuiescent = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n quiescence: Duration.Duration,\n maxWait: Duration.Duration,\n) {\n const start = yield* Clock.currentTimeMillis;\n const maxMillis = Duration.toMillis(maxWait);\n const loop: Effect.Effect<void> = Effect.gen(function* () {\n const elapsed = (yield* Clock.currentTimeMillis) - start;\n yield* Effect.sleep(\n Duration.millis(\n Math.min(\n Duration.toMillis(quiescence),\n Math.max(0, maxMillis - elapsed),\n ),\n ),\n );\n const drained = yield* Queue.clear(signal);\n if (drained.length === 0) return;\n const now = yield* Clock.currentTimeMillis;\n if (now - start < maxMillis) {\n yield* loop;\n }\n });\n yield* loop;\n});\n\nconst esbuildOptions = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n crypto: Crypto.Crypto,\n projectRoot: string,\n generatedDirectory: string,\n entries: ReadonlyArray<Entry>,\n notExternal: ReadonlyArray<RegExp>,\n stateRef: Ref.Ref<WatchBuild.State>,\n captureRef: Ref.Ref<WatchBuild.Capture>,\n progressRef: Ref.Ref<WatchBuild.Progress>,\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n initial: Deferred.Deferred<void>,\n): esbuild.BuildOptions => {\n const encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));\n return {\n absWorkingDir: projectRoot,\n stdin: {\n contents: entries\n .map((entry) => `import ${encodeString(entry.absolutePath)};`)\n .join(\"\\n\"),\n resolveDir: projectRoot,\n sourcefile: \"confect-watch.ts\",\n loader: \"ts\",\n },\n bundle: true,\n write: false,\n metafile: true,\n platform: \"node\",\n format: \"esm\",\n logLevel: \"silent\",\n plugins: [\n Bundler.bundleWorkspacePlugin(path, fs, notExternal),\n externalPlugin({ notExternal: [...notExternal] }),\n {\n name: \"notify-rebuild\",\n setup(build) {\n build.onStart(() =>\n Effect.runPromise(\n Effect.gen(function* () {\n yield* Ref.update(progressRef, WatchBuild.start);\n yield* Ref.set(captureRef, WatchBuild.emptyCapture);\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onLoad({ filter: /.*/ }, (args) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const fingerprint = yield* fs.readFile(args.path).pipe(\n Effect.flatMap((contents) =>\n crypto.digest(\"SHA-256\", contents),\n ),\n Effect.map(Hex.encode),\n Effect.result,\n );\n yield* Ref.update(captureRef, (capture) =>\n Result.isSuccess(fingerprint)\n ? {\n ...capture,\n fingerprints: HashMap.set(\n capture.fingerprints,\n args.path,\n fingerprint.success,\n ),\n }\n : {\n ...capture,\n failures: HashMap.set(\n capture.failures,\n args.path,\n WatchBuild.Failure.InputCaptureFailed({\n file: args.path,\n cause: fingerprint.failure,\n }),\n ),\n },\n );\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onEnd((result) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const { generation } = yield* Ref.get(progressRef);\n const previous = yield* Ref.get(stateRef);\n const outcome = yield* WatchBuild.parse(\n result,\n yield* Ref.get(captureRef),\n (file) => path.resolve(projectRoot, file),\n crypto,\n );\n const current = WatchBuild.observe(previous, outcome);\n yield* Ref.set(stateRef, current);\n const change = WatchBuild.diff(\n previous,\n current,\n generatedDirectory + path.sep,\n );\n yield* Ref.update(pendingRef, (pending) =>\n WatchBuild.Change.$match(change, {\n Full: () => SyncState.add(pending, entries, true),\n Affected: ({ paths }) =>\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n Recovered: ({ paths }) =>\n SyncState.reconcile(\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n ),\n }),\n );\n yield* Queue.offer(signal, undefined);\n yield* Ref.update(progressRef, (progress) =>\n WatchBuild.complete(progress, { generation, outcome }),\n );\n yield* Deferred.succeed(initial, undefined);\n }),\n ),\n );\n },\n },\n ],\n };\n};\n\nconst entryPointsWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restartQueue: Queue.Queue<void>,\n watcher: State,\n) {\n const parentScope = yield* Effect.scope;\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDirectory = path.join(\n yield* fs.realPath(confectDirectory),\n \"_generated\",\n );\n const crypto = yield* Crypto.Crypto;\n const completedInitial = Deferred.make<void>().pipe(\n Effect.tap((initial) => Deferred.succeed(initial, undefined)),\n );\n\n const sync = Effect.gen(function* () {\n const revision = yield* watcher.topology.revision;\n const current = yield* Ref.get(watcher.lifecycle);\n const entries = yield* EntryPoint.discover;\n yield* Ref.set(watcher.declared, entries.some(EntryPoint.Kind.$is(\"App\")));\n const desiredPaths = HashSet.fromIterable(\n entries.map((entry) => entry.absolutePath),\n );\n const key = pipe(\n Array.fromIterable(desiredPaths),\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n const unchanged = WatcherLifecycle.$match(current, {\n Uninitialized: () => false,\n Empty: () => entries.length === 0,\n Active: ({ key: previousKey }) => previousKey === key,\n });\n if (unchanged) {\n const initial = yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => completedInitial,\n Empty: () => completedInitial,\n Active: ({ initial: activeInitial }) => Effect.succeed(activeInitial),\n });\n yield* refreshCurrent(current).pipe(\n Effect.catchTag(\"WatcherOperationError\", () =>\n Ref.update(pendingRef, SyncState.full),\n ),\n );\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => Effect.void,\n Empty: () => Ref.update(pendingRef, SyncState.full),\n Active: ({ entries: previousEntries, scope }) =>\n Effect.gen(function* () {\n const removedOptional = previousEntries.filter(\n (entry) =>\n EntryPoint.isOptional(entry) &&\n !HashSet.has(desiredPaths, entry.absolutePath),\n );\n yield* Ref.update(pendingRef, (pending) =>\n SyncState.add(SyncState.full(pending), removedOptional),\n );\n yield* Scope.close(scope, Exit.void);\n }),\n });\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Uninitialized());\n yield* Ref.set(watcher.observation, WatchBuild.State.Initial());\n if (!Array.isReadonlyArrayNonEmpty(entries)) {\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Empty());\n yield* Ref.update(pendingRef, SyncState.full);\n yield* Queue.offer(signal, undefined);\n const initial = yield* completedInitial;\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n\n const scope = yield* Scope.fork(parentScope, \"sequential\");\n const captureRef = yield* Ref.make(WatchBuild.emptyCapture);\n const progress = yield* Ref.make(WatchBuild.initialProgress);\n const initial = yield* Deferred.make<void>();\n const tsconfig = loadTsConfig(projectRoot);\n const notExternal = tsconfigPathsToRegExp(\n tsconfig?.data.compilerOptions?.paths ?? {},\n );\n const context = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n esbuild.context(\n esbuildOptions(\n path,\n fs,\n crypto,\n projectRoot,\n generatedDirectory,\n entries,\n notExternal,\n watcher.observation,\n captureRef,\n progress,\n signal,\n pendingRef,\n initial,\n ),\n ),\n catch: (cause) => new OperationError({ operation: \"create\", cause }),\n }),\n (ctx) =>\n Effect.tryPromise({\n try: () => ctx.dispose(),\n catch: (cause) => new OperationError({ operation: \"dispose\", cause }),\n }).pipe(Effect.orDie),\n ).pipe(Scope.provide(scope));\n const requestIds = new WeakMap<\n Promise<esbuild.BuildResult>,\n WatchBuild.RequestId\n >();\n yield* Ref.set(\n watcher.lifecycle,\n WatcherLifecycle.Active({\n initial,\n key,\n scope,\n entries,\n context,\n identifyRequest: (promise) => {\n const existing = requestIds.get(promise);\n if (existing !== undefined) return existing;\n const id = WatchBuild.makeRequestId();\n requestIds.set(promise, id);\n return id;\n },\n progress,\n verifyInputs: (snapshot) =>\n WatchBuild.verifyInputs(snapshot, fs, crypto),\n }),\n );\n yield* Effect.tryPromise({\n try: () => context.watch(),\n catch: (cause) => new OperationError({ operation: \"watch\", cause }),\n });\n yield* watcher.topology.reconcile(revision, initial);\n }).pipe(Semaphore.withPermit(watcher.lock));\n\n yield* sync;\n return yield* Effect.forever(\n Queue.take(restartQueue).pipe(Effect.andThen(sync)),\n );\n}, Effect.provide(NodeCrypto.layer));\n\nconst refreshCurrent = Effect.fnUntraced(function* (current: WatcherLifecycle) {\n return yield* WatcherLifecycle.$match(current, {\n Empty: () => Effect.succeed(RefreshOutcome.Empty()),\n Uninitialized: () =>\n Effect.fail(\n new OperationError({\n operation: \"refresh\",\n cause: \"The dependency watcher is not initialized\",\n }),\n ),\n Active: ({ context, identifyRequest, progress, verifyInputs }) =>\n Effect.gen(function* () {\n const runSync = Effect.runSyncWith(yield* Effect.context());\n const barrier = WatchBuild.captureBarrier(yield* Ref.get(progress));\n const rebuild = Effect.gen(function* () {\n const built = yield* Effect.tryPromise({\n try: () => {\n const promise = context.rebuild();\n runSync(\n Ref.update(progress, (currentProgress) =>\n WatchBuild.request(currentProgress, identifyRequest(promise)),\n ),\n );\n return promise;\n },\n catch: (cause) =>\n new OperationError({ operation: \"rebuild\", cause }),\n }).pipe(Effect.result);\n const currentProgress = yield* Ref.get(progress);\n const completed = WatchBuild.getCompletion(currentProgress);\n if (Result.isFailure(built)) {\n const rejected = parseFailure(built.failure.cause);\n if (Option.isNone(rejected)) return yield* built.failure;\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n if (\n Option.isNone(completed) ||\n !WatchBuild.Outcome.$is(\"Failed\")(completed.value.outcome)\n )\n return yield* new OperationError({\n operation: \"rebuild\",\n cause: rejected.value.errors,\n });\n }\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n const observed = yield* Effect.fromOption(completed).pipe(\n Effect.mapError(\n () =>\n new OperationError({\n operation: \"rebuild\",\n cause: \"esbuild completed without a build observation\",\n }),\n ),\n );\n if (\n WatchBuild.isFresh(barrier, observed) &&\n WatchBuild.Outcome.$is(\"Succeeded\")(observed.outcome)\n ) {\n const unchanged = yield* verifyInputs(\n observed.outcome.snapshot,\n ).pipe(\n Effect.mapError(\n ({ cause }) =>\n new OperationError({ operation: \"refresh\", cause }),\n ),\n );\n if (!unchanged) return Option.none<WatchBuild.Completion>();\n }\n return Option.some(observed);\n }).pipe(Effect.ensuring(Ref.update(progress, WatchBuild.endRequest)));\n const completed = yield* rebuild.pipe(\n Effect.repeat({\n while: (observed) =>\n Option.isNone(observed) ||\n !WatchBuild.isFresh(barrier, observed.value),\n }),\n Effect.flatMap((observed) =>\n Effect.fromOption(observed).pipe(Effect.orDie),\n ),\n );\n return RefreshOutcome.Observed({ outcome: completed.outcome });\n }),\n });\n});\n\nconst refresh = (watcher: State) =>\n watcher.lock.withPermit(\n Ref.get(watcher.lifecycle).pipe(Effect.flatMap(refreshCurrent)),\n );\n\nconst confectStructureWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restart: Effect.Effect<unknown>,\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const removedDirectory = Schema.Struct({\n code: Schema.Literal(\"ENOENT\"),\n syscall: Schema.Literal(\"scandir\"),\n path: Schema.String,\n });\n\n yield* pipe(\n fs.watch(confectDirectory, { recursive: true }),\n Stream.runForEach((event) =>\n handleConfectChange({\n relativePath: path.relative(\n confectDirectory,\n path.resolve(confectDirectory, event.path),\n ),\n eventTag: event._tag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n }),\n ),\n Effect.retry({\n schedule: Schedule.spaced(\"10 millis\"),\n while: (error) =>\n Effect.gen(function* () {\n const removed = Schema.decodeUnknownOption(removedDirectory)(\n error.reason.cause,\n );\n if (Option.isNone(removed)) return false;\n const relative = path.relative(confectDirectory, removed.value.path);\n if (\n relative === \"\" ||\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n )\n return false;\n if (\n !(yield* fs\n .exists(confectDirectory)\n .pipe(Effect.orElseSucceed(() => false)))\n ) {\n return false;\n }\n yield* restart;\n return true;\n }),\n }),\n );\n});\n\n/**\n * Non-recursive `fs.watch` on the convex directory, reacting only to\n * `convex.config.ts`. Recursion is deliberately avoided: codegen (Confect's and\n * Convex's) writes into `convex/` and `convex/_generated/` constantly, and\n * reacting to those writes would loop. Create/Remove offers to `restartQueue`\n * so the entry-point watcher set picks up (or drops) the config's esbuild\n * watcher.\n */\nconst convexConfigStructureWatcher = Effect.fnUntraced(function* (\n restart: Effect.Effect<unknown>,\n declared: Ref.Ref<boolean>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* pipe(\n fs.watch(convexDirectory),\n Stream.runForEach((event) =>\n Effect.gen(function* () {\n // A declared backend's config is codegen output; reacting to its\n // writes would rerun codegen for nothing.\n if (\n path.relative(convexDirectory, event.path) !==\n CONVEX_CONFIG_FILENAME ||\n (yield* Ref.get(declared))\n )\n return;\n yield* Match.value(event).pipe(\n Match.tag(\"Update\", () => Effect.void),\n Match.tag(\"Create\", \"Remove\", () => restart),\n Match.exhaustive,\n );\n }),\n ),\n );\n});\n\nconst flipDirtyAndSignal = (\n pendingRef: Ref.Ref<Pending>,\n signal: Queue.Queue<void>,\n restart: Effect.Effect<unknown>,\n isLifecycleChange: boolean,\n) =>\n isLifecycleChange\n ? restart\n : Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n\nconst handleConfectChange = ({\n relativePath,\n eventTag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n}: {\n relativePath: string;\n eventTag: \"Create\" | \"Update\" | \"Remove\";\n signal: Queue.Queue<void>;\n pendingRef: Ref.Ref<Pending>;\n restart: Effect.Effect<unknown>;\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>;\n}) => {\n if (relativePath.split(/[/\\\\]/).includes(\"_generated\")) {\n return Effect.void;\n }\n\n if (!relativePath.endsWith(\".ts\")) {\n return Effect.void;\n }\n\n const isLifecycleChange = Match.value(eventTag).pipe(\n Match.when(\"Update\", () => false),\n Match.whenOr(\"Create\", \"Remove\", () => true),\n Match.exhaustive,\n );\n\n // Sections read the files they match and those files' imports, entry points\n // included. An entry point's own watcher only validates or updates that\n // entry, so an edit to a recorded section input reruns codegen in full.\n const source = relativePath.split(/[/\\\\]/).join(\"/\");\n const regenerateIfInput = SectionFiles.inputs.pipe(\n Effect.map((inputs) => inputs.includes(source)),\n Effect.orElseSucceed(() => false),\n Effect.flatMap((listed) =>\n listed\n ? flipDirtyAndSignal(pendingRef, signal, restart, false)\n : Effect.void,\n ),\n );\n\n const entry = EntryPoint.parse(relativePath);\n if (Option.isSome(entry)) {\n return isLifecycleChange ? restartEntry(entry.value) : regenerateIfInput;\n }\n\n // A stray `confect/schema.ts` (now codegen-owned at\n // `_generated/schema.ts`) shouldn't exist; flagging it here ensures the\n // next codegen pass surfaces the migration error\n // (`LegacySchemaFileError`) instead of silently ignoring the file.\n if (relativePath === \"schema.ts\") {\n return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);\n }\n\n // Any other `.ts` under `confect/` (helpers like `tables/notes.ts`).\n // Updates to such files are handled by the esbuild watcher for whichever\n // entry point imports them—its onEnd flips the right dirty flag.\n // Creates are our safety net: when a previously-missing import is added,\n // esbuild may not have its parent directory on a poll path, so we\n // re-run codegen on Create here. Every manifest section's `render` sees the\n // list of `confect/` files, so a Remove re-runs codegen too. A section's\n // input, whether a file it matched or one that file imports, may have no\n // entry point importing it and is read again only by a full run, even after\n // a refusal.\n return Match.value(eventTag).pipe(\n Match.whenOr(\"Create\", \"Remove\", () =>\n flipDirtyAndSignal(pendingRef, signal, restart, false),\n ),\n Match.when(\"Update\", () => regenerateIfInput),\n Match.exhaustive,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,qBAAqB,QAAQ,UACxC,2CACA,EAAE,oBAAoB,SAAS,OAAO,EAAE,EAAE,CAC5C;AAIA,MAAM,oBAAoB,SAAS,QAAQ,CAAC;AAoB5C,MAAM,mBAAmB,KAAK,WAA6B;AAe3D,MAAM,iBAAiB,KAAK,WAA2B;AAEvD,MAAa,uBAAuB,YAClC,eAAe,OAAO,SAAS;CAC7B,aAAa;CACb,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,CAAC,KAAK,GAAG;CACnD,MAAM,oBAAA,OAAwC,KAC5C,OAAO,KAAK,WAAW,OAAO,SAAS,MAAM,CAAC,GAC9C,OAAO,oBAAoB,KAAK,GAChC,OAAO,SAAS,WACd,SACI,mBAAmB,YAAY,QAAQ,SAAS,KAAK,IACrD,OAAO,IACb,CACF;CAEA,MAAM,QAAQsB,MAAiB,YAAY;CAC3C,IAAI,OAAO,OAAO,KAAK,GACrB,OAAO,oBAAoB,aAAa,MAAM,KAAK,IAAI;CAOzD,IAAI,iBAAiB,aACnB,OAAO,mBAAmB,YAAY,QAAQ,SAAS,iBAAiB;CAa1E,OAAO,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC3B,MAAM,OAAO,UAAU,gBACrB,mBAAmB,YAAY,QAAQ,SAAS,KAAK,CACvD,GACA,MAAM,KAAK,gBAAgB,iBAAiB,GAC5C,MAAM,UACR;AACF"}
|
|
1
|
+
{"version":3,"file":"Watcher.mjs","names":["SyncState.empty","WatchTopology.make","RestoreWatcher.make","SyncState.full","WatchBuild.diagnostics","TypeScriptConfig.buildOptions","Bundler.bundleWorkspacePlugin","WatchBuild.start","WatchBuild.emptyCapture","WatchBuild.parse","WatchBuild.observe","WatchBuild.diff","SyncState.add","SyncState.reconcile","WatchBuild.complete","EntryPoint.discover","EntryPoint.isOptional","TypeScriptConfig.discover","WatchBuild.initialProgress","PackageSelfReference.discover","TypeScriptConfig.aliasPatterns","WatchBuild.makeRequestId","WatchBuild.verifyInputs","WatchBuild.combine","WatchBuild.captureBarrier","WatchBuild.request","WatchBuild.getCompletion","WatchBuild.joinedWithoutCompletion","WatchBuild.isFresh","WatchBuild.endRequest","EntryPoint.parse"],"sources":["../src/Watcher.ts"],"sourcesContent":["import * as String from \"effect/String\";\nimport * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Layer from \"effect/Layer\";\nimport * as Cache from \"effect/Cache\";\nimport * as Duration from \"effect/Duration\";\nimport * as NodeCrypto from \"@effect/platform-node/NodeCrypto\";\nimport * as Digest from \"effect/crypto/Digest\";\nimport * as Hex from \"effect/encoding/Hex\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Stream from \"effect/Stream\";\nimport * as BundleRequire from \"bundle-require\";\nimport * as esbuild from \"esbuild\";\nimport * as Bundler from \"./Bundler.js\";\nimport * as WatchBuild from \"./WatchBuild.js\";\nimport * as WatchTopology from \"./WatchTopology.js\";\nimport * as SyncState from \"./SyncState.js\";\nimport type { Pending } from \"./SyncState.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport type { EntryPoint as Entry } from \"./EntryPoint.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as RestoreWatcher from \"./RestoreWatcher.js\";\nimport * as SectionFiles from \"./SectionFiles.js\";\nimport * as PackageSelfReference from \"./PackageSelfReference.js\";\nimport * as TypeScriptConfig from \"./TypeScriptConfig.js\";\n\nexport const CoalesceQuiescence = Context.Reference<Duration.Duration>(\n \"@confect/cli/Watcher/CoalesceQuiescence\",\n { defaultValue: () => Duration.millis(50) },\n);\n\n// Upper bound on `drainUntilQuiescent` so a pathological infinite\n// signal stream can't pin the sync loop forever.\nconst COALESCE_MAX_WAIT = Duration.seconds(5);\n\ninterface WatchGroup {\n readonly initial: Deferred.Deferred<void>;\n readonly context: esbuild.BuildContext;\n readonly identifyRequest: (\n promise: Promise<esbuild.BuildResult>,\n ) => WatchBuild.RequestId;\n readonly progress: Ref.Ref<WatchBuild.Progress>;\n readonly verifyInputs: (\n snapshot: WatchBuild.Snapshot,\n ) => ReturnType<typeof WatchBuild.verifyInputs>;\n}\n\ninterface ConfiguredEntry {\n readonly entry: Entry;\n readonly config: Option.Option<TypeScriptConfig.TypeScriptConfig>;\n readonly key: string;\n}\n\ntype WatcherLifecycle = Data.TaggedEnum<{\n Uninitialized: {};\n Empty: {};\n Active: {\n readonly initial: Deferred.Deferred<void>;\n readonly key: string;\n readonly scope: Scope.Closeable;\n readonly entries: Array.NonEmptyReadonlyArray<Entry>;\n readonly groups: Array.NonEmptyReadonlyArray<WatchGroup>;\n };\n}>;\nconst WatcherLifecycle = Data.taggedEnum<WatcherLifecycle>();\n\ninterface State {\n readonly lifecycle: Ref.Ref<WatcherLifecycle>;\n readonly observation: Ref.Ref<HashMap.HashMap<string, WatchBuild.State>>;\n readonly lock: Semaphore.Semaphore;\n readonly topology: WatchTopology.WatchTopology;\n // Whether the last discovery found `confect/app.ts`.\n readonly declared: Ref.Ref<boolean>;\n}\n\ntype RefreshOutcome = Data.TaggedEnum<{\n Empty: {};\n Observed: { readonly outcome: WatchBuild.Outcome };\n}>;\nconst RefreshOutcome = Data.taggedEnum<RefreshOutcome>();\n\n/**\n * @internal\n */\nexport const isRefreshSuccessful = (outcome: RefreshOutcome): boolean =>\n RefreshOutcome.$match(outcome, {\n Empty: () => true,\n Observed: ({ outcome: observed }) =>\n WatchBuild.Outcome.$match(observed, {\n Succeeded: () => true,\n Failed: () => false,\n }),\n });\n\nexport class OperationError extends Schema.TaggedError<\n OperationError,\n { readonly brand: unique symbol }\n>()(\"WatcherOperationError\", {\n operation: Schema.Literals([\n \"create\",\n \"watch\",\n \"rebuild\",\n \"dispose\",\n \"refresh\",\n ]),\n cause: Schema.Unknown,\n}) {}\n\nexport const ReportedBuildFailure = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })),\n});\n\n/**\n * @internal\n */\nexport const make = Effect.fnUntraced(function* () {\n const quiescence = yield* CoalesceQuiescence;\n const signal = yield* Queue.sliding<void>(1);\n const pendingRef = yield* Ref.make<Pending>(SyncState.empty);\n const restartQueue = yield* Queue.sliding<void>(1);\n const state: State = {\n lifecycle: yield* Ref.make<WatcherLifecycle>(\n WatcherLifecycle.Uninitialized(),\n ),\n observation: yield* Ref.make(HashMap.empty<string, WatchBuild.State>()),\n lock: yield* Semaphore.make(1),\n topology: yield* WatchTopology.make(pendingRef),\n declared: yield* Ref.make(false),\n };\n const restartWith = (invalidation: Effect.Effect<void>) =>\n invalidation.pipe(\n Effect.andThen(Queue.offer(restartQueue, undefined)),\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n const restart = restartWith(state.topology.invalidate);\n const restartEntry = (entry: EntryPoint.Kind) =>\n restartWith(state.topology.invalidateEntry(entry));\n const duringRestoreRef = yield* Ref.make<\n Effect.Effect<void, never, Scope.Scope>\n >(Effect.void);\n return {\n run: Effect.gen(function* () {\n const structure = yield* RestoreWatcher.make(\n confectStructureWatcher(signal, pendingRef, restart, restartEntry),\n );\n yield* Ref.set(duringRestoreRef, structure.duringRestore);\n yield* Effect.all(\n [\n Effect.scoped(\n entryPointsWatcher(signal, pendingRef, restartQueue, state),\n ),\n structure.failure,\n convexConfigStructureWatcher(restart, state.declared),\n ],\n { concurrency: \"unbounded\" },\n );\n }).pipe(Effect.scoped),\n duringRestore: duringRestoreRef.pipe(Ref.get, Effect.flatten),\n // Restored output makes esbuild rebuild; observe that, then drop the work\n // it queued so the restore does not trigger another generation.\n discardRestoreEchoes: refresh(state).pipe(\n Effect.ignore,\n Effect.andThen(Ref.set(pendingRef, SyncState.empty)),\n ),\n refresh: refresh(state),\n next: Queue.take(signal).pipe(\n Effect.andThen(\n drainUntilQuiescent(signal, quiescence, COALESCE_MAX_WAIT),\n ),\n Effect.andThen(state.topology.takePending),\n Effect.onInterrupt(() => Queue.offer(signal, undefined)),\n ),\n pending: Ref.get(pendingRef),\n requestRetry: Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n Effect.asVoid,\n ),\n diagnostics: Ref.get(state.observation).pipe(\n Effect.map((observations) =>\n Array.reduce(\n HashMap.values(observations),\n {\n errors: [] as ReadonlyArray<esbuild.Message>,\n warnings: [] as ReadonlyArray<esbuild.Message>,\n },\n (combined, observation) => {\n const diagnostic = WatchBuild.diagnostics(observation);\n return {\n errors: [...combined.errors, ...diagnostic.errors],\n warnings: [...combined.warnings, ...diagnostic.warnings],\n };\n },\n ),\n ),\n ),\n } as const;\n});\n\nexport type Watcher = Effect.Success<ReturnType<typeof make>>;\n\nconst drainUntilQuiescent = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n quiescence: Duration.Duration,\n maxWait: Duration.Duration,\n) {\n const start = yield* Clock.currentTimeMillis;\n const maxMillis = Duration.toMillis(maxWait);\n const loop: Effect.Effect<void> = Effect.gen(function* () {\n const elapsed = (yield* Clock.currentTimeMillis) - start;\n yield* Effect.sleep(\n Duration.millis(\n Math.min(\n Duration.toMillis(quiescence),\n Math.max(0, maxMillis - elapsed),\n ),\n ),\n );\n const drained = yield* Queue.clear(signal);\n if (drained.length === 0) return;\n const now = yield* Clock.currentTimeMillis;\n if (now - start < maxMillis) {\n yield* loop;\n }\n });\n yield* loop;\n});\n\nconst esbuildOptions = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n digest: Digest.Digest[\"Service\"],\n projectRoot: string,\n generatedDirectory: string,\n entries: ReadonlyArray<Entry>,\n notExternal: ReadonlyArray<string | RegExp>,\n config: Option.Option<TypeScriptConfig.TypeScriptConfig>,\n stateRef: Ref.Ref<HashMap.HashMap<string, WatchBuild.State>>,\n captureRef: Ref.Ref<WatchBuild.Capture>,\n progressRef: Ref.Ref<WatchBuild.Progress>,\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n initial: Deferred.Deferred<void>,\n): esbuild.BuildOptions => {\n const JsonString = Schema.fromJsonString(Schema.String);\n const groupKey = Option.match(config, {\n onNone: () => \"\",\n onSome: (selected) => selected.path,\n });\n return {\n ...TypeScriptConfig.buildOptions(config),\n absWorkingDir: projectRoot,\n stdin: {\n contents: Array.join(\n Array.map(\n entries,\n (entry) =>\n `import ${Result.getOrThrow(Schema.encodeResult(JsonString)(entry.absolutePath))};`,\n ),\n \"\\n\",\n ),\n resolveDir: projectRoot,\n sourcefile: \"confect-watch.ts\",\n loader: \"ts\",\n },\n bundle: true,\n write: false,\n metafile: true,\n platform: \"node\",\n format: \"esm\",\n logLevel: \"silent\",\n plugins: [\n Bundler.bundleWorkspacePlugin(path, fs, notExternal),\n BundleRequire.externalPlugin({ notExternal: [...notExternal] }),\n {\n name: \"notify-rebuild\",\n setup(build) {\n build.onStart(() =>\n Effect.runPromise(\n Effect.gen(function* () {\n yield* Ref.update(progressRef, WatchBuild.start);\n yield* Ref.set(captureRef, WatchBuild.emptyCapture);\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onLoad({ filter: /.*/ }, (args) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const fingerprint = yield* fs.readFile(args.path).pipe(\n Effect.flatMap((contents) =>\n digest.digest(Digest.sha256, contents),\n ),\n Effect.map(Hex.encode),\n Effect.result,\n );\n yield* Ref.update(captureRef, (capture) =>\n Result.isSuccess(fingerprint)\n ? {\n ...capture,\n fingerprints: HashMap.set(\n capture.fingerprints,\n args.path,\n fingerprint.success,\n ),\n }\n : {\n ...capture,\n failures: HashMap.set(\n capture.failures,\n args.path,\n WatchBuild.Failure.InputCaptureFailed({\n file: args.path,\n cause: fingerprint.failure,\n }),\n ),\n },\n );\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onEnd((result) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const { generation } = yield* Ref.get(progressRef);\n const observations = yield* Ref.get(stateRef);\n const previous = Option.getOrElse(\n HashMap.get(observations, groupKey),\n WatchBuild.State.Initial,\n );\n const capture = yield* Ref.get(captureRef);\n const outcome = yield* WatchBuild.parse(\n result,\n capture,\n (file) => path.resolve(projectRoot, file),\n digest,\n );\n const current = WatchBuild.observe(previous, outcome);\n yield* Ref.update(stateRef, HashMap.set(groupKey, current));\n const change = WatchBuild.diff(\n previous,\n current,\n generatedDirectory + path.sep,\n );\n yield* Ref.update(pendingRef, (pending) =>\n WatchBuild.Change.$match(change, {\n Full: () => SyncState.add(pending, entries, true),\n Affected: ({ paths }) =>\n SyncState.add(\n pending,\n Array.filter(entries, (entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n Recovered: ({ paths }) =>\n SyncState.reconcile(\n SyncState.add(\n pending,\n Array.filter(entries, (entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n ),\n }),\n );\n yield* Queue.offer(signal, undefined);\n yield* Ref.update(progressRef, (progress) =>\n WatchBuild.complete(progress, { generation, outcome }),\n );\n yield* Deferred.succeed(initial, undefined);\n }),\n ),\n );\n },\n },\n ],\n };\n};\n\nconst entryPointsWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restartQueue: Queue.Queue<void>,\n watcher: State,\n) {\n const parentScope = yield* Effect.scope;\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const realConfectDirectory = yield* fs.realPath(confectDirectory);\n const generatedDirectory = path.join(realConfectDirectory, \"_generated\");\n const cryptoContext = yield* Layer.build(NodeCrypto.layerDigest);\n const digest = Context.get(cryptoContext, Digest.Digest);\n const completedInitial = Deferred.make<void>().pipe(\n Effect.tap((initial) => Deferred.succeed(initial, undefined)),\n );\n\n const sync = Effect.gen(function* () {\n const revision = yield* watcher.topology.revision;\n const current = yield* Ref.get(watcher.lifecycle);\n const entries = yield* EntryPoint.discover;\n yield* Ref.set(\n watcher.declared,\n Array.some(entries, EntryPoint.Kind.$is(\"App\")),\n );\n const desiredPaths = HashSet.fromIterable(\n Array.map(entries, (entry) => entry.absolutePath),\n );\n const key = pipe(\n Array.fromIterable(desiredPaths),\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n const unchanged = WatcherLifecycle.$match(current, {\n Uninitialized: () => false,\n Empty: () => entries.length === 0,\n Active: ({ key: previousKey }) => previousKey === key,\n });\n if (unchanged) {\n const initial = yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => completedInitial,\n Empty: () => completedInitial,\n Active: ({ initial: activeInitial }) => Effect.succeed(activeInitial),\n });\n yield* refreshCurrent(current).pipe(\n Effect.catchTag(\"WatcherOperationError\", () =>\n Ref.update(pendingRef, SyncState.full),\n ),\n );\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => Effect.void,\n Empty: () => Ref.update(pendingRef, SyncState.full),\n Active: ({ entries: previousEntries, scope }) =>\n Effect.gen(function* () {\n const removedOptional = Array.filter(\n previousEntries,\n (entry) =>\n EntryPoint.isOptional(entry) &&\n !HashSet.has(desiredPaths, entry.absolutePath),\n );\n yield* Ref.update(pendingRef, (pending) =>\n SyncState.add(SyncState.full(pending), removedOptional),\n );\n yield* Scope.close(scope, Exit.void);\n }),\n });\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Uninitialized());\n yield* Ref.set(watcher.observation, HashMap.empty());\n if (!Array.isReadonlyArrayNonEmpty(entries)) {\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Empty());\n yield* Ref.update(pendingRef, SyncState.full);\n yield* Queue.offer(signal, undefined);\n const initial = yield* completedInitial;\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n\n const scope = yield* Scope.fork(parentScope, \"sequential\");\n const configs = yield* Cache.make({\n capacity: entries.length,\n lookup: TypeScriptConfig.discover,\n });\n const configured = yield* Effect.forEach(entries, (entry) =>\n Effect.map(\n Cache.get(configs, path.dirname(entry.absolutePath)),\n (config) => ({\n entry,\n config,\n key: Option.match(config, {\n onNone: () => \"\",\n onSome: (selected) => selected.path,\n }),\n }),\n ),\n ).pipe(\n Effect.mapError((cause) =>\n OperationError.make({ operation: \"create\", cause }),\n ),\n );\n const partitions = Array.groupWith(\n Array.sort(\n configured,\n Order.mapInput(\n Order.String,\n (selected: ConfiguredEntry) => selected.key,\n ),\n ),\n (left, right) => left.key === right.key,\n );\n const groups = yield* Effect.forEach(partitions, (partition) =>\n Effect.gen(function* () {\n const config = Array.headNonEmpty(partition).config;\n const groupEntries = Array.map(partition, (selected) => selected.entry);\n const captureRef = yield* Ref.make(WatchBuild.emptyCapture);\n const progress = yield* Ref.make(WatchBuild.initialProgress);\n const initial = yield* Deferred.make<void>();\n const selfReferences = yield* Effect.forEach(\n Array.dedupe(\n Array.map(groupEntries, (entry) =>\n path.dirname(entry.absolutePath),\n ),\n ),\n PackageSelfReference.discover,\n ).pipe(\n Effect.mapError((cause) =>\n OperationError.make({ operation: \"create\", cause }),\n ),\n );\n const notExternal = [\n ...TypeScriptConfig.aliasPatterns(config),\n ...Array.getSomes(selfReferences),\n ];\n const context = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n esbuild.context(\n esbuildOptions(\n path,\n fs,\n digest,\n projectRoot,\n generatedDirectory,\n groupEntries,\n notExternal,\n config,\n watcher.observation,\n captureRef,\n progress,\n signal,\n pendingRef,\n initial,\n ),\n ),\n catch: (cause) =>\n OperationError.make({ operation: \"create\", cause }),\n }),\n (ctx) =>\n Effect.tryPromise({\n try: () => ctx.dispose(),\n catch: (cause) =>\n OperationError.make({ operation: \"dispose\", cause }),\n }).pipe(Effect.orDie),\n ).pipe(Scope.provide(scope));\n const requestIds = new WeakMap<\n Promise<esbuild.BuildResult>,\n WatchBuild.RequestId\n >();\n return {\n initial,\n context,\n identifyRequest: (promise) => {\n const existing = requestIds.get(promise);\n if (existing !== undefined) return existing;\n const id = WatchBuild.makeRequestId();\n requestIds.set(promise, id);\n return id;\n },\n progress,\n verifyInputs: (snapshot) =>\n WatchBuild.verifyInputs(snapshot, fs, digest),\n } satisfies WatchGroup;\n }),\n );\n const initial = yield* Deferred.make<void>();\n yield* Ref.set(\n watcher.lifecycle,\n WatcherLifecycle.Active({ initial, key, scope, entries, groups }),\n );\n yield* Effect.forEach(groups, ({ context }) =>\n Effect.tryPromise({\n try: () => context.watch(),\n catch: (cause) => OperationError.make({ operation: \"watch\", cause }),\n }),\n );\n yield* Effect.forEach(groups, (group) =>\n Deferred.await(group.initial),\n ).pipe(\n Effect.andThen(Deferred.succeed(initial, undefined)),\n Effect.forkIn(scope),\n );\n yield* watcher.topology.reconcile(revision, initial);\n }).pipe(Semaphore.withPermit(watcher.lock));\n\n yield* sync;\n return yield* Effect.forever(\n Queue.take(restartQueue).pipe(Effect.andThen(sync)),\n );\n});\n\nconst refreshCurrent = Effect.fnUntraced(function* (current: WatcherLifecycle) {\n return yield* WatcherLifecycle.$match(current, {\n Empty: () => Effect.succeed(RefreshOutcome.Empty()),\n Uninitialized: () =>\n Effect.fail(\n OperationError.make({\n operation: \"refresh\",\n cause: \"The dependency watcher is not initialized\",\n }),\n ),\n Active: ({ groups }) =>\n Effect.gen(function* () {\n const outcomes = yield* Effect.forEach(groups, refreshGroup);\n if (groups.length > 1) {\n const unchanged = yield* Effect.forEach(\n Array.zip(groups, outcomes),\n ([group, outcome]) =>\n WatchBuild.Outcome.$match(outcome, {\n Failed: () => Effect.succeed(true),\n Succeeded: ({ snapshot }) =>\n group.verifyInputs(snapshot).pipe(\n Effect.mapError(({ cause }) =>\n OperationError.make({\n operation: \"refresh\",\n cause,\n }),\n ),\n ),\n }),\n );\n if (!Array.every(unchanged, (matches) => matches))\n return Option.none<RefreshOutcome>();\n }\n return Option.some(\n RefreshOutcome.Observed({\n outcome: WatchBuild.combine(outcomes),\n }),\n );\n }).pipe(\n Effect.repeat({ while: Option.isNone<RefreshOutcome> }),\n Effect.flatMap((outcome) =>\n Effect.fromOption(outcome).pipe(Effect.orDie),\n ),\n ),\n });\n});\n\nconst refreshGroup = Effect.fnUntraced(function* ({\n context,\n identifyRequest,\n progress,\n verifyInputs,\n}: WatchGroup) {\n const effectContext = yield* Effect.context();\n const runSync = Effect.runSyncWith(effectContext);\n const previousProgress = yield* Ref.get(progress);\n const barrier = WatchBuild.captureBarrier(previousProgress);\n const rebuild = Effect.gen(function* () {\n const built = yield* Effect.tryPromise({\n try: () => {\n const promise = context.rebuild();\n runSync(\n Ref.update(progress, (currentProgress) =>\n WatchBuild.request(currentProgress, identifyRequest(promise)),\n ),\n );\n return promise;\n },\n catch: (cause) => OperationError.make({ operation: \"rebuild\", cause }),\n }).pipe(Effect.result);\n const currentProgress = yield* Ref.get(progress);\n const completed = WatchBuild.getCompletion(currentProgress);\n if (Result.isFailure(built)) {\n const rejected = Schema.decodeUnknownOption(ReportedBuildFailure)(\n built.failure.cause,\n );\n if (Option.isNone(rejected)) return yield* built.failure;\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n if (\n Option.isNone(completed) ||\n !WatchBuild.Outcome.$is(\"Failed\")(completed.value.outcome)\n )\n return yield* OperationError.make({\n operation: \"rebuild\",\n cause: rejected.value.errors,\n });\n }\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n const observed = yield* Effect.fromOption(completed).pipe(\n Effect.mapError(() =>\n OperationError.make({\n operation: \"rebuild\",\n cause: \"esbuild completed without a build observation\",\n }),\n ),\n );\n if (\n WatchBuild.isFresh(barrier, observed) &&\n WatchBuild.Outcome.$is(\"Succeeded\")(observed.outcome)\n ) {\n const unchanged = yield* verifyInputs(observed.outcome.snapshot).pipe(\n Effect.mapError(({ cause }) =>\n OperationError.make({ operation: \"refresh\", cause }),\n ),\n );\n if (!unchanged) return Option.none<WatchBuild.Completion>();\n }\n return Option.some(observed);\n }).pipe(Effect.ensuring(Ref.update(progress, WatchBuild.endRequest)));\n const completed = yield* rebuild.pipe(\n Effect.repeat({\n while: (observed) =>\n Option.isNone(observed) || !WatchBuild.isFresh(barrier, observed.value),\n }),\n Effect.flatMap((observed) =>\n Effect.fromOption(observed).pipe(Effect.orDie),\n ),\n );\n return completed.outcome;\n});\n\nconst refresh = (watcher: State) =>\n watcher.lock.withPermit(\n Ref.get(watcher.lifecycle).pipe(Effect.flatMap(refreshCurrent)),\n );\n\nconst confectStructureWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restart: Effect.Effect<unknown>,\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const removedDirectory = Schema.Struct({\n code: Schema.Literal(\"ENOENT\"),\n syscall: Schema.Literal(\"scandir\"),\n path: Schema.String,\n });\n\n yield* pipe(\n fs.watch(confectDirectory, { recursive: true }),\n Stream.runForEach((event) =>\n handleConfectChange({\n relativePath: path.relative(\n confectDirectory,\n path.resolve(confectDirectory, event.path),\n ),\n eventTag: event._tag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n }),\n ),\n Effect.retry({\n schedule: Schedule.spaced(\"10 millis\"),\n while: (error) =>\n Effect.gen(function* () {\n const removed = Schema.decodeUnknownOption(removedDirectory)(\n error.reason.cause,\n );\n if (Option.isNone(removed)) return false;\n const relative = path.relative(confectDirectory, removed.value.path);\n if (\n relative === \"\" ||\n relative === \"..\" ||\n String.startsWith(`..${path.sep}`)(relative) ||\n path.isAbsolute(relative)\n )\n return false;\n if (\n !(yield* fs\n .exists(confectDirectory)\n .pipe(Effect.orElseSucceed(() => false)))\n ) {\n return false;\n }\n yield* restart;\n return true;\n }),\n }),\n );\n});\n\n/**\n * Non-recursive `fs.watch` on the convex directory, reacting only to\n * `convex.config.ts`. Recursion is deliberately avoided: codegen (Confect's and\n * Convex's) writes into `convex/` and `convex/_generated/` constantly, and\n * reacting to those writes would loop. Create/Remove offers to `restartQueue`\n * so the entry-point watcher set picks up (or drops) the config's esbuild\n * watcher.\n */\nconst convexConfigStructureWatcher = Effect.fnUntraced(function* (\n restart: Effect.Effect<unknown>,\n declared: Ref.Ref<boolean>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* pipe(\n fs.watch(convexDirectory),\n Stream.runForEach((event) =>\n Effect.gen(function* () {\n // A declared backend's config is codegen output; reacting to its\n // writes would rerun codegen for nothing.\n if (\n path.relative(convexDirectory, event.path) !==\n CONVEX_CONFIG_FILENAME ||\n (yield* Ref.get(declared))\n )\n return;\n yield* Match.value(event).pipe(\n Match.tag(\"Update\", () => Effect.void),\n Match.tag(\"Create\", \"Remove\", () => restart),\n Match.exhaustive,\n );\n }),\n ),\n );\n});\n\nconst flipDirtyAndSignal = (\n pendingRef: Ref.Ref<Pending>,\n signal: Queue.Queue<void>,\n restart: Effect.Effect<unknown>,\n isLifecycleChange: boolean,\n) =>\n isLifecycleChange\n ? restart\n : Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n\nconst handleConfectChange = ({\n relativePath,\n eventTag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n}: {\n relativePath: string;\n eventTag: \"Create\" | \"Update\" | \"Remove\";\n signal: Queue.Queue<void>;\n pendingRef: Ref.Ref<Pending>;\n restart: Effect.Effect<unknown>;\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>;\n}) => {\n if (String.split(/[/\\\\]/)(relativePath).includes(\"_generated\")) {\n return Effect.void;\n }\n\n if (!String.endsWith(\".ts\")(relativePath)) {\n return Effect.void;\n }\n\n const isLifecycleChange = Match.value(eventTag).pipe(\n Match.when(\"Update\", () => false),\n Match.whenOr(\"Create\", \"Remove\", () => true),\n Match.exhaustive,\n );\n\n // Sections read the files they match and those files' imports, entry points\n // included. An entry point's own watcher only validates or updates that\n // entry, so an edit to a recorded section input reruns codegen in full.\n const source = Array.join(pipe(relativePath, String.split(/[/\\\\]/)), \"/\");\n const regenerateIfInput = SectionFiles.inputs.pipe(\n Effect.map((inputs) => inputs.includes(source)),\n Effect.orElseSucceed(() => false),\n Effect.flatMap((listed) =>\n listed\n ? flipDirtyAndSignal(pendingRef, signal, restart, false)\n : Effect.void,\n ),\n );\n\n const entry = EntryPoint.parse(relativePath);\n if (Option.isSome(entry)) {\n return isLifecycleChange ? restartEntry(entry.value) : regenerateIfInput;\n }\n\n // A stray `confect/schema.ts` (now codegen-owned at\n // `_generated/schema.ts`) shouldn't exist; flagging it here ensures the\n // next codegen pass surfaces the migration error\n // (`LegacySchemaFileError`) instead of silently ignoring the file.\n if (relativePath === \"schema.ts\") {\n return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);\n }\n\n // Any other `.ts` under `confect/` (helpers like `tables/notes.ts`).\n // Updates to such files are handled by the esbuild watcher for whichever\n // entry point imports them—its onEnd flips the right dirty flag.\n // Creates are our safety net: when a previously-missing import is added,\n // esbuild may not have its parent directory on a poll path, so we\n // re-run codegen on Create here. Every manifest section's `render` sees the\n // list of `confect/` files, so a Remove re-runs codegen too. A section's\n // input, whether a file it matched or one that file imports, may have no\n // entry point importing it and is read again only by a full run, even after\n // a refusal.\n return Match.value(eventTag).pipe(\n Match.whenOr(\"Create\", \"Remove\", () =>\n flipDirtyAndSignal(pendingRef, signal, restart, false),\n ),\n Match.when(\"Update\", () => regenerateIfInput),\n Match.exhaustive,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAa,qBAAqB,QAAQ,UACxC,2CACA,EAAE,oBAAoB,SAAS,OAAO,EAAE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AAC,SAAS,YAAY,GAC3D,OAAO,OAAO;CAGhB,IAAI,CAAC,OAAO,SAAS,KAAK,CAAC,CAAC,YAAY,GACtC,OAAO,OAAO;CAGhB,MAAM,oBAAoB,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC9C,MAAM,KAAK,gBAAgB,KAAK,GAChC,MAAM,OAAO,UAAU,gBAAgB,IAAI,GAC3C,MAAM,UACR;CAKA,MAAM,SAAS,MAAM,KAAK,KAAK,cAAc,OAAO,MAAM,OAAO,CAAC,GAAG,GAAG;CACxE,MAAM,oBAAA,OAAwC,KAC5C,OAAO,KAAK,WAAW,OAAO,SAAS,MAAM,CAAC,GAC9C,OAAO,oBAAoB,KAAK,GAChC,OAAO,SAAS,WACd,SACI,mBAAmB,YAAY,QAAQ,SAAS,KAAK,IACrD,OAAO,IACb,CACF;CAEA,MAAM,QAAQ2B,QAAiB,YAAY;CAC3C,IAAI,OAAO,OAAO,KAAK,GACrB,OAAO,oBAAoB,aAAa,MAAM,KAAK,IAAI;CAOzD,IAAI,iBAAiB,aACnB,OAAO,mBAAmB,YAAY,QAAQ,SAAS,iBAAiB;CAa1E,OAAO,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC3B,MAAM,OAAO,UAAU,gBACrB,mBAAmB,YAAY,QAAQ,SAAS,KAAK,CACvD,GACA,MAAM,KAAK,gBAAgB,iBAAiB,GAC5C,MAAM,UACR;AACF"}
|
package/dist/cliApp.mjs
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { version } from "./package.mjs";
|
|
1
|
+
import { version } from "./package.json.mjs";
|
|
2
2
|
import { confect } from "./confect.mjs";
|
|
3
3
|
import * as Command from "effect/cli/Command";
|
|
4
|
-
|
|
4
|
+
// src/cliApp.ts
|
|
5
|
+
/**
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
5
8
|
const cliApp = Command.run(confect, { version });
|
|
6
|
-
//#endregion
|
|
7
9
|
export { cliApp };
|
|
8
10
|
|
|
9
11
|
//# sourceMappingURL=cliApp.mjs.map
|
package/dist/cliApp.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cliApp.mjs","names":["packageJson.version"],"sources":["../src/cliApp.ts"],"sourcesContent":["import * as Command from \"effect/cli/Command\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport { confect } from \"./confect.js\";\n\nexport const cliApp = Command.run(confect, {\n version: packageJson.version,\n});\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"cliApp.mjs","names":["packageJson.version"],"sources":["../src/cliApp.ts"],"sourcesContent":["import * as Command from \"effect/cli/Command\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport { confect } from \"./confect.js\";\n\n/**\n * @internal\n */\nexport const cliApp = Command.run(confect, {\n version: packageJson.version,\n});\n"],"mappings":";;;;;;;AAOA,MAAa,SAAS,QAAQ,IAAI,SAAS,EAChCA,QACX,CAAC"}
|
package/dist/confect/codegen.mjs
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
|
+
import { bundle, check, exportNames, resolveModule, withBatch } from "../Bundler.mjs";
|
|
1
2
|
import { fromBundlerError } from "../BuildError.mjs";
|
|
2
|
-
import { ProjectRoot } from "../ProjectRoot.mjs";
|
|
3
|
-
import { logFileAdded, logFileModified, logFileRemoved, logPending, logSuccess, logWarn } from "../log.mjs";
|
|
4
|
-
import { bundle, exportNames, resolveModule } from "../Bundler.mjs";
|
|
5
3
|
import { CallbackPrefixError, ComponentNodeGroupError, ConflictingDocNameError, InvalidConvexConfigError, InvalidDeclarationError, LegacySchemaFileError, tapAndLog } from "../CodegenError.mjs";
|
|
6
|
-
import { ConvexDirectory } from "../ConvexDirectory.mjs";
|
|
7
4
|
import { ConfectDirectory } from "../ConfectDirectory.mjs";
|
|
8
|
-
import { assemblyNodesFromLeaves } from "../SpecAssemblyNode.mjs";
|
|
9
|
-
import { assembledSpec, componentContract, components, convexSchema, docs, id, refs, registeredFunctionsForGroup, runtimeSchema, schema, services, tableWrapper } from "../templates.mjs";
|
|
10
|
-
import { generateAuthConfig, generateCrons, generateHttp, removePathIfExists, toModuleImportPath, touchConvexSchema, writeFileStringAndLog } from "../utils.mjs";
|
|
11
5
|
import { CONVEX_CONFIG_FILENAME, componentName, discoverInstalledComponents, resolveDefinition, typeImportPath } from "../ConvexConfig.mjs";
|
|
6
|
+
import { ConvexDirectory } from "../ConvexDirectory.mjs";
|
|
12
7
|
import { flags, layer } from "../DirectoryOptions.mjs";
|
|
13
8
|
import { fromTableName } from "../DocName.mjs";
|
|
14
9
|
import { FunctionPaths, make } from "../FunctionPaths.mjs";
|
|
15
|
-
import { removeUnclaimed, sync, verify } from "../SectionFiles.mjs";
|
|
16
|
-
import { diff, fromLoadedLeaves, update } from "../GenerationSnapshot.mjs";
|
|
17
10
|
import { applyFunctionPlan, assertOwnedEntrypoints, generateFunctions } from "../FunctionModule.mjs";
|
|
18
|
-
import {
|
|
19
|
-
import { TABLES_DIRNAME, discover, validate } from "../TableModule.mjs";
|
|
11
|
+
import { diff, fromLoadedLeaves, update } from "../GenerationSnapshot.mjs";
|
|
20
12
|
import { planDeclarations } from "../EntryPoint.mjs";
|
|
13
|
+
import { discoverLeafSpecFiles, implPathForSpec, loadAll, registeredFunctionsRelativePath, toLeafModule, validateAllImpls, withImplFiles } from "../LeafModule.mjs";
|
|
14
|
+
import { logFileAdded, logFileModified, logFileRemoved, logPending, logSuccess, logWarn } from "../log.mjs";
|
|
15
|
+
import { ProjectRoot } from "../ProjectRoot.mjs";
|
|
21
16
|
import { preserveComponentOutput } from "../Rollback.mjs";
|
|
17
|
+
import { assemblyNodesFromLeaves } from "../SpecAssemblyNode.mjs";
|
|
22
18
|
import { refuseSpecSections } from "../ManifestSections.mjs";
|
|
19
|
+
import { removeUnclaimed, sync, verify } from "../SectionFiles.mjs";
|
|
20
|
+
import { TABLES_DIRNAME, discover, validate } from "../TableModule.mjs";
|
|
21
|
+
import { assembledSpec, componentContract, components, convexSchema, docs, id, refs, registeredFunctionsForGroup, runtimeSchema, schema, services, tableWrapper } from "../templates.mjs";
|
|
22
|
+
import { generateAuthConfig, generateCrons, generateHttp, removePathIfExists, toModuleImportPath, touchConvexSchema, writeFileStringAndLog } from "../utils.mjs";
|
|
23
23
|
import { readPrevious, syncDeclaration, syncDeclaredHttp, syncDeployModule, syncManifestSections } from "./declaration.mjs";
|
|
24
|
+
import { quote } from "../Json.mjs";
|
|
24
25
|
import * as Effect from "effect/Effect";
|
|
25
26
|
import * as Command from "effect/cli/Command";
|
|
26
27
|
import { App, Callback, Env, Spec } from "@confect/core";
|
|
@@ -33,7 +34,8 @@ import * as HashSet from "effect/HashSet";
|
|
|
33
34
|
import * as Match from "effect/Match";
|
|
34
35
|
import * as Option from "effect/Option";
|
|
35
36
|
import * as Record from "effect/Record";
|
|
36
|
-
|
|
37
|
+
import * as String from "effect/String";
|
|
38
|
+
// src/confect/codegen.ts
|
|
37
39
|
const GENERATED_DIRNAME = "_generated";
|
|
38
40
|
const declaredSections = (backend) => Option.match(backend, {
|
|
39
41
|
onNone: () => [],
|
|
@@ -60,10 +62,16 @@ const LEGACY_PATHS = Effect.gen(function* () {
|
|
|
60
62
|
path.join(GENERATED_DIRNAME, "nodeSpec.ts")
|
|
61
63
|
];
|
|
62
64
|
});
|
|
65
|
+
/**
|
|
66
|
+
* @internal
|
|
67
|
+
*/
|
|
63
68
|
const codegen = Command.make("codegen", flags, () => Effect.gen(function* () {
|
|
64
69
|
yield* logPending("Performing initial sync…");
|
|
65
70
|
yield* codegenHandler.pipe(Effect.asVoid, Effect.tap(() => logSuccess("Generated files are up-to-date")), tapAndLog);
|
|
66
71
|
})).pipe(Command.provide(layer), Command.withDescription("Generate `confect/_generated` files and the contents of the `convex` directory (except `tsconfig.json`, and `convex.config.ts` unless `confect/app.ts` declares the backend)"));
|
|
72
|
+
/**
|
|
73
|
+
* @internal
|
|
74
|
+
*/
|
|
67
75
|
const generateWithSnapshot = Effect.gen(function* () {
|
|
68
76
|
yield* validateComponentConfiguration;
|
|
69
77
|
yield* rejectDeployModuleGroup;
|
|
@@ -75,7 +83,9 @@ const generateWithSnapshot = Effect.gen(function* () {
|
|
|
75
83
|
yield* generateIdConstructor(tableModules);
|
|
76
84
|
yield* generateTableWrappers(tableModules);
|
|
77
85
|
yield* removeObsoleteTableWrappers(tableModules);
|
|
78
|
-
|
|
86
|
+
const leafSpecFiles = yield* discoverLeafSpecFiles;
|
|
87
|
+
const forEach2 = yield* Effect.forEach(leafSpecFiles, toLeafModule);
|
|
88
|
+
yield* generateAssembledSpecs(forEach2);
|
|
79
89
|
yield* generateRefs;
|
|
80
90
|
yield* provisionalComponents;
|
|
81
91
|
const { app: declared, digest, backend } = yield* syncDeclaration(previousManifest);
|
|
@@ -118,13 +128,31 @@ const generateWithSnapshot = Effect.gen(function* () {
|
|
|
118
128
|
yield* syncDeployModule(declared);
|
|
119
129
|
if (Option.isSome(declared)) yield* generateTesting(declared.value);
|
|
120
130
|
yield* verify(backend, mounts);
|
|
131
|
+
const fs = yield* FileSystem.FileSystem;
|
|
132
|
+
const path = yield* Path.Path;
|
|
133
|
+
const confectDirectory = yield* ConfectDirectory.get;
|
|
134
|
+
const optionalFiles = yield* Effect.filter([
|
|
135
|
+
"http.ts",
|
|
136
|
+
"crons.ts",
|
|
137
|
+
"auth.ts"
|
|
138
|
+
], (file) => fs.exists(path.join(confectDirectory, file)));
|
|
139
|
+
yield* withBatch(Array.map(optionalFiles, (file) => path.join(confectDirectory, file)), Effect.forEach(optionalFiles, (file) => check(path.join(confectDirectory, file)).pipe(Effect.mapError((error) => fromBundlerError(file, error))), { discard: true }));
|
|
121
140
|
return {
|
|
122
141
|
functionPaths,
|
|
123
142
|
snapshot
|
|
124
143
|
};
|
|
125
144
|
}).pipe(Effect.withSpan("Cli.codegen"));
|
|
145
|
+
/**
|
|
146
|
+
* @internal
|
|
147
|
+
*/
|
|
126
148
|
const makeCodegenHandler = (duringRestore) => preserveComponentOutput(generateWithSnapshot, duringRestore).pipe(Effect.tap(() => touchConvexSchema), Effect.map(({ functionPaths }) => ({ functionPaths })));
|
|
149
|
+
/**
|
|
150
|
+
* @internal
|
|
151
|
+
*/
|
|
127
152
|
const codegenHandler = makeCodegenHandler();
|
|
153
|
+
/**
|
|
154
|
+
* @internal
|
|
155
|
+
*/
|
|
128
156
|
const updateDeclarations = Effect.fn("Cli.updateDeclarations")(function* (snapshot, declarations, affectedImpls) {
|
|
129
157
|
yield* rejectDeployModuleGroup;
|
|
130
158
|
const previousManifest = yield* readPrevious;
|
|
@@ -151,11 +179,11 @@ const updateDeclarations = Effect.fn("Cli.updateDeclarations")(function* (snapsh
|
|
|
151
179
|
}));
|
|
152
180
|
});
|
|
153
181
|
const validateComponentGroupRuntime = (group, groupPath, specPath) => Result.gen(function* () {
|
|
154
|
-
if (group.runtime === "Node") return yield* Result.fail(
|
|
182
|
+
if (group.runtime === "Node") return yield* Result.fail(ComponentNodeGroupError.make({
|
|
155
183
|
specPath,
|
|
156
184
|
groupPath
|
|
157
185
|
}));
|
|
158
|
-
for (const [name, child] of
|
|
186
|
+
for (const [name, child] of Record.toEntries(group.groups)) yield* validateComponentGroupRuntime(child, `${groupPath}.${name}`, specPath);
|
|
159
187
|
});
|
|
160
188
|
const rejectComponentNodeGroups = Effect.fnUntraced(function* (leaves) {
|
|
161
189
|
if ((yield* ConvexDirectory.target).kind === "app") return;
|
|
@@ -165,11 +193,12 @@ const validateCallbackPrefixes = Effect.fnUntraced(function* (declared) {
|
|
|
165
193
|
if ((yield* ConvexDirectory.target).kind !== "component") return;
|
|
166
194
|
const fs = yield* FileSystem.FileSystem;
|
|
167
195
|
const path = yield* Path.Path;
|
|
168
|
-
const
|
|
196
|
+
const confectDirectory = yield* ConfectDirectory.get;
|
|
197
|
+
const callbacksPath = path.join(confectDirectory, "callbacks.ts");
|
|
169
198
|
if (!(yield* fs.exists(callbacksPath))) return;
|
|
170
|
-
const name = Option.isSome(declared) ? Env.name(App.env(declared.value)) : yield* componentName(path.join(
|
|
199
|
+
const name = Option.isSome(declared) ? Env.name(App.env(declared.value)) : yield* Effect.flatMap(ConvexDirectory.get, (convexDirectory) => componentName(path.join(convexDirectory, CONVEX_CONFIG_FILENAME)));
|
|
171
200
|
const { module } = yield* bundle(callbacksPath).pipe(Effect.mapError((error) => fromBundlerError("confect/callbacks.ts", error)));
|
|
172
|
-
for (const contract of
|
|
201
|
+
for (const contract of Record.values(module)) if (Callback.isContract(contract) && !pipe(contract.id, String.startsWith(`${name}/`))) return yield* CallbackPrefixError.make({
|
|
173
202
|
declarationPath: "confect/callbacks.ts",
|
|
174
203
|
contractId: contract.id,
|
|
175
204
|
componentName: name
|
|
@@ -181,7 +210,7 @@ const validateComponentConfiguration = Effect.gen(function* () {
|
|
|
181
210
|
const path = yield* Path.Path;
|
|
182
211
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
183
212
|
const authPath = path.join(confectDirectory, "auth.ts");
|
|
184
|
-
if (yield* fs.exists(authPath)) return yield*
|
|
213
|
+
if (yield* fs.exists(authPath)) return yield* InvalidConvexConfigError.make({
|
|
185
214
|
configPath: authPath,
|
|
186
215
|
reason: "Components cannot configure application authentication. Pass identity explicitly through function arguments."
|
|
187
216
|
});
|
|
@@ -259,7 +288,8 @@ const removeObsoleteRegisteredFunctions = Effect.fnUntraced(function* (leaves) {
|
|
|
259
288
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
260
289
|
const registryRoot = path.join(confectDirectory, "_generated", "registeredFunctions");
|
|
261
290
|
if (!(yield* fs.exists(registryRoot))) return;
|
|
262
|
-
const
|
|
291
|
+
const expectedPaths = yield* Effect.forEach(leaves, (leaf) => registeredFunctionsRelativePath(leaf));
|
|
292
|
+
const expected = new Set(expectedPaths);
|
|
263
293
|
const existing = yield* fs.readDirectory(registryRoot, { recursive: true });
|
|
264
294
|
yield* Effect.forEach(existing, (relativePath) => {
|
|
265
295
|
if (path.extname(relativePath) !== ".ts") return Effect.void;
|
|
@@ -288,6 +318,9 @@ const loadGeneratedSpec = Effect.gen(function* () {
|
|
|
288
318
|
return spec;
|
|
289
319
|
});
|
|
290
320
|
const emptyFunctionPaths = FunctionPaths.make(HashSet.empty());
|
|
321
|
+
/**
|
|
322
|
+
* @internal
|
|
323
|
+
*/
|
|
291
324
|
const loadPreviousFunctionPaths = Effect.gen(function* () {
|
|
292
325
|
const fs = yield* FileSystem.FileSystem;
|
|
293
326
|
const specPath = yield* getGeneratedSpecPath;
|
|
@@ -327,13 +360,13 @@ const rejectLegacySchemaFile = Effect.gen(function* () {
|
|
|
327
360
|
const path = yield* Path.Path;
|
|
328
361
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
329
362
|
const legacyPath = path.join(confectDirectory, "schema.ts");
|
|
330
|
-
if (yield* fs.exists(legacyPath)) return yield*
|
|
363
|
+
if (yield* fs.exists(legacyPath)) return yield* LegacySchemaFileError.make({ schemaPath: "schema.ts" });
|
|
331
364
|
});
|
|
332
365
|
const rejectDeployModuleGroup = Effect.gen(function* () {
|
|
333
366
|
const fs = yield* FileSystem.FileSystem;
|
|
334
367
|
const path = yield* Path.Path;
|
|
335
368
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
336
|
-
if (yield* fs.exists(path.join(confectDirectory, "confectDeploy.spec.ts"))) return yield*
|
|
369
|
+
if (yield* fs.exists(path.join(confectDirectory, "confectDeploy.spec.ts"))) return yield* InvalidDeclarationError.make({
|
|
337
370
|
declarationPath: "confect/confectDeploy.spec.ts",
|
|
338
371
|
reason: "its functions would go in convex/confectDeploy.ts, which codegen writes for the mounts a push initialises. Rename the group, for example to confect/deploy.spec.ts."
|
|
339
372
|
});
|
|
@@ -366,7 +399,8 @@ const generateIdConstructor = Effect.fnUntraced(function* (tableModules) {
|
|
|
366
399
|
const generatedIdPath = yield* GENERATED_ID_PATH;
|
|
367
400
|
const idPath = path.join(confectDirectory, generatedIdPath);
|
|
368
401
|
const tableNames = Array.map(tableModules, (tableModule) => tableModule.tableName);
|
|
369
|
-
const
|
|
402
|
+
const convexDirectory = yield* ConvexDirectory.target;
|
|
403
|
+
const contents = yield* Match.value(convexDirectory).pipe(Match.when({ kind: "app" }, () => id({ tableNames })), Match.when({ kind: "component" }, ({ scope }) => id({
|
|
370
404
|
tableNames,
|
|
371
405
|
scope
|
|
372
406
|
})), Match.exhaustive);
|
|
@@ -473,7 +507,7 @@ const validateNoDocNameCollisions = Effect.fnUntraced(function* (tableModules) {
|
|
|
473
507
|
docName,
|
|
474
508
|
tableNames: Array.map(group, (tableModule) => tableModule.tableName)
|
|
475
509
|
})));
|
|
476
|
-
if (Array.isReadonlyArrayNonEmpty(collisions)) return yield*
|
|
510
|
+
if (Array.isReadonlyArrayNonEmpty(collisions)) return yield* ConflictingDocNameError.make({ collisions });
|
|
477
511
|
});
|
|
478
512
|
const generateDocs = Effect.fnUntraced(function* (tableModules) {
|
|
479
513
|
const path = yield* Path.Path;
|
|
@@ -523,6 +557,8 @@ const installedMounts = Effect.gen(function* () {
|
|
|
523
557
|
* It must exist before loading tables and specs because they may import bound
|
|
524
558
|
* component IDs and schemas. Returns each mount with the specifier of its
|
|
525
559
|
* definition, relative to `_generated` for an in-repo component.
|
|
560
|
+
*
|
|
561
|
+
* @internal
|
|
526
562
|
*/
|
|
527
563
|
const generateComponents = Effect.gen(function* () {
|
|
528
564
|
const path = yield* Path.Path;
|
|
@@ -532,24 +568,25 @@ const generateComponents = Effect.gen(function* () {
|
|
|
532
568
|
name,
|
|
533
569
|
typeImportPath: definition
|
|
534
570
|
})) });
|
|
535
|
-
|
|
571
|
+
const gENERATEDCOMPONENTSPATH = yield* GENERATED_COMPONENTS_PATH;
|
|
572
|
+
yield* writeFileStringAndLog(path.join(confectDirectory, gENERATEDCOMPONENTSPATH), contents);
|
|
536
573
|
return mounts;
|
|
537
574
|
});
|
|
538
575
|
const provisionalComponents = Effect.gen(function* () {
|
|
539
576
|
const fs = yield* FileSystem.FileSystem;
|
|
540
|
-
const
|
|
577
|
+
const path = yield* Path.Path;
|
|
578
|
+
const confectDirectory = yield* ConfectDirectory.get;
|
|
579
|
+
const gENERATEDCOMPONENTSPATH = yield* GENERATED_COMPONENTS_PATH;
|
|
580
|
+
const registry = path.join(confectDirectory, gENERATEDCOMPONENTSPATH);
|
|
541
581
|
if (yield* fs.exists(registry)) return;
|
|
542
|
-
|
|
582
|
+
const components2 = yield* components({ components: [] });
|
|
583
|
+
yield* writeFileStringAndLog(registry, components2);
|
|
543
584
|
});
|
|
544
585
|
const logGenerated = (effect) => effect.pipe(Effect.tap(Option.match({
|
|
545
586
|
onNone: () => Effect.void,
|
|
546
587
|
onSome: ({ change, convexFilePath }) => Match.value(change).pipe(Match.when("Added", () => logFileAdded(convexFilePath)), Match.when("Modified", () => logFileModified(convexFilePath)), Match.when("Unchanged", () => Effect.void), Match.exhaustive)
|
|
547
588
|
})));
|
|
548
589
|
/**
|
|
549
|
-
* Test-only imports never enter the runtime schema or function wrappers.
|
|
550
|
-
*/
|
|
551
|
-
const quote = (value) => JSON.stringify(value);
|
|
552
|
-
/**
|
|
553
590
|
* A descriptor's `testing` kit must be a package specifier, so the generated
|
|
554
591
|
* registry holds no machine-specific path, and must export `register`. A kit
|
|
555
592
|
* whose exports cannot be listed without running it passes here, and
|
|
@@ -557,11 +594,11 @@ const quote = (value) => JSON.stringify(value);
|
|
|
557
594
|
*/
|
|
558
595
|
const checkTestKit = Effect.fnUntraced(function* (mount, specifier, config, configDisplay) {
|
|
559
596
|
const path = yield* Path.Path;
|
|
560
|
-
const invalid = (problem) =>
|
|
597
|
+
const invalid = (problem) => InvalidDeclarationError.make({
|
|
561
598
|
declarationPath: "confect/app.ts",
|
|
562
599
|
reason: `the mount ${quote(mount)} names the test kit ${quote(specifier)} in its component descriptor${problem}`
|
|
563
600
|
});
|
|
564
|
-
if (specifier.startsWith(".") || path.isAbsolute(specifier)) return yield* invalid("; name it by a package specifier, such as \"<package>/testing\".");
|
|
601
|
+
if (pipe(specifier, String.startsWith(".")) || path.isAbsolute(specifier)) return yield* invalid("; name it by a package specifier, such as \"<package>/testing\".");
|
|
565
602
|
const resolved = resolveModule(specifier, config);
|
|
566
603
|
if (Option.isNone(resolved)) return yield* invalid(`, which does not resolve from ${configDisplay}.`);
|
|
567
604
|
const exports = yield* exportNames(resolved.value).pipe(Effect.mapError((error) => fromBundlerError(specifier, error)));
|
|
@@ -573,17 +610,20 @@ const generateTesting = Effect.fnUntraced(function* (app) {
|
|
|
573
610
|
const confectDirectory = yield* ConfectDirectory.get;
|
|
574
611
|
const convexDirectory = yield* ConvexDirectory.get;
|
|
575
612
|
const generated = path.join(confectDirectory, "_generated");
|
|
576
|
-
const
|
|
613
|
+
const projectRoot = yield* ProjectRoot.get;
|
|
614
|
+
const configDisplay = Array.join(pipe(path.relative(projectRoot, path.join(convexDirectory, CONVEX_CONFIG_FILENAME)), String.split(path.sep)), "/");
|
|
577
615
|
const relative = (file) => {
|
|
578
|
-
const value = path.relative(generated, file).split(path.sep)
|
|
579
|
-
return value.startsWith(".") ? value : `./${value}`;
|
|
616
|
+
const value = Array.join(pipe(path.relative(generated, file), String.split(path.sep)), "/");
|
|
617
|
+
return pipe(value, String.startsWith(".")) ? value : `./${value}`;
|
|
580
618
|
};
|
|
581
619
|
const imports = ["import schema from \"./schema.js\";", "import convexSchema from \"./convexSchema.js\";"];
|
|
582
620
|
const moduleMap = Effect.fnUntraced(function* (directory) {
|
|
583
|
-
|
|
621
|
+
const directory2 = yield* fs.readDirectory(directory, { recursive: true });
|
|
622
|
+
const files = Array.filter(directory2, (file) => /\.[cm]?[jt]s$/.test(file) && !pipe(file, String.endsWith(".d.ts")) && !pipe(file, String.split(path.sep)).includes("_generated") && !pipe(file, String.includes(".config."))).sort();
|
|
623
|
+
return `{ "_generated/testing.ts": () => Promise.resolve({}),\n${pipe(files, Array.map((file) => {
|
|
584
624
|
const specifier = relative(path.join(directory, file));
|
|
585
|
-
return `${quote(file.split(path.sep)
|
|
586
|
-
}).join("\n")}\n}`;
|
|
625
|
+
return `${quote(Array.join(pipe(file, String.split(path.sep)), "/"))}: () => import(${quote(pipe(specifier, String.replace(/\.([cm]?)[jt]s$/, ".$1js")))}),`;
|
|
626
|
+
}), Array.join("\n"))}\n}`;
|
|
587
627
|
});
|
|
588
628
|
const declarations = [];
|
|
589
629
|
const identifiers = /* @__PURE__ */ new Set(["schema", "convexSchema"]);
|
|
@@ -596,23 +636,26 @@ const generateTesting = Effect.fnUntraced(function* (app) {
|
|
|
596
636
|
const installed = yield* discoverInstalledComponents(config, relative(config), kind);
|
|
597
637
|
for (const component of installed) {
|
|
598
638
|
const name = prefix + component.name;
|
|
599
|
-
const mount = prefix === "" ? App.mounts(app)
|
|
639
|
+
const mount = prefix === "" ? Option.getOrUndefined(Array.findFirst(App.mounts(app), (declared) => declared.name === component.name)) : void 0;
|
|
600
640
|
const fromPackage = !path.isAbsolute(component.componentDefinitionPath);
|
|
601
641
|
const named = fromPackage ? mount?.component.testing : void 0;
|
|
602
642
|
if (named !== void 0) yield* checkTestKit(name, named, config, configDisplay);
|
|
603
643
|
const kitEntries = named !== void 0 ? [named] : fromPackage ? [`${component.componentDefinitionPath}/testing`, `${component.componentDefinitionPath}/test`] : [];
|
|
604
|
-
const kitEntry =
|
|
605
|
-
const resolved = fromPackage ?
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
644
|
+
const kitEntry = Option.getOrUndefined(Array.findFirst(kitEntries, (entry) => Option.isSome(resolveModule(entry, config))));
|
|
645
|
+
const resolved = fromPackage ? yield* resolveDefinition(`${component.componentDefinitionPath}/convex.config`, config, path).pipe(Effect.fromOption, Effect.mapBoth({
|
|
646
|
+
onFailure: () => InvalidConvexConfigError.make({
|
|
647
|
+
configPath: relative(config),
|
|
648
|
+
reason: `Cannot resolve component ${component.componentDefinitionPath} for testing.`
|
|
649
|
+
}),
|
|
650
|
+
onSuccess: (definition) => path.dirname(definition)
|
|
651
|
+
})) : component.componentDefinitionPath;
|
|
609
652
|
const localPrefix = prefix === "" ? mount?.httpPrefix : component.httpPrefix;
|
|
610
|
-
const httpPrefix = parentHttpPrefix === void 0 || localPrefix === void 0 ? void 0 : `${parentHttpPrefix.replace(/\/+$/, "")}${localPrefix}
|
|
653
|
+
const httpPrefix = parentHttpPrefix === void 0 || localPrefix === void 0 ? void 0 : pipe(`${pipe(parentHttpPrefix, String.replace(/\/+$/, ""))}${localPrefix}`, String.replace(/\/+$/, ""), (joined) => joined === "" ? "/" : joined);
|
|
611
654
|
if (httpPrefix !== void 0 && ((yield* fs.exists(path.join(resolved, "http.ts"))) || (yield* fs.exists(path.join(resolved, "http.js"))))) httpMounts.push(`{ componentPath: ${quote(name)}, httpPrefix: ${quote(httpPrefix)} }`);
|
|
612
655
|
const kitKey = kitEntry ?? resolved;
|
|
613
656
|
let identifier = kits.get(kitKey);
|
|
614
657
|
if (identifier === void 0) {
|
|
615
|
-
const cleaned = name.replaceAll(/[^A-Za-z0-9_$]/g, "_");
|
|
658
|
+
const cleaned = pipe(name, String.replaceAll(/[^A-Za-z0-9_$]/g, "_"));
|
|
616
659
|
const base = /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;
|
|
617
660
|
identifier = `${base}Kit`;
|
|
618
661
|
let schemaIdentifier = `${base}Schema`;
|
|
@@ -627,9 +670,9 @@ const generateTesting = Effect.fnUntraced(function* (app) {
|
|
|
627
670
|
imports.push(`import ${schemaIdentifier} from ${quote(relative(path.join(resolved, "schema.js")))};`);
|
|
628
671
|
declarations.push(`const ${identifier} = { schema: ${schemaIdentifier}, modules: ${yield* moduleMap(resolved)} };`);
|
|
629
672
|
} else {
|
|
630
|
-
if (kitEntry === void 0) return yield*
|
|
673
|
+
if (kitEntry === void 0) return yield* InvalidConvexConfigError.make({
|
|
631
674
|
configPath: relative(config),
|
|
632
|
-
reason: `the component package ${quote(component.componentDefinitionPath)} has no ${kitEntries.map(quote).join(" or ")} export. Tests register a component from another package through that entry's \`register(t, name)\`.`
|
|
675
|
+
reason: `the component package ${quote(component.componentDefinitionPath)} has no ${pipe(kitEntries, Array.map(quote), Array.join(" or "))} export. Tests register a component from another package through that entry's \`register(t, name)\`.`
|
|
633
676
|
});
|
|
634
677
|
imports.push(`import * as ${identifier} from ${quote(kitEntry)};`);
|
|
635
678
|
}
|
|
@@ -639,14 +682,13 @@ const generateTesting = Effect.fnUntraced(function* (app) {
|
|
|
639
682
|
}
|
|
640
683
|
});
|
|
641
684
|
yield* visit(convexDirectory, "", (yield* ConvexDirectory.target).kind, "");
|
|
642
|
-
yield* writeFileStringAndLog(path.join(generated, "testing.ts"), [
|
|
685
|
+
yield* writeFileStringAndLog(path.join(generated, "testing.ts"), Array.join([
|
|
643
686
|
"// Generated by `confect codegen`. Test-only; do not import in backend functions.",
|
|
644
687
|
...imports,
|
|
645
688
|
...declarations,
|
|
646
|
-
`export default { httpMounts: [${
|
|
647
|
-
]
|
|
689
|
+
`export default { httpMounts: [${Array.join(httpMounts, ",")}], schema, convexSchema, modules: ${yield* moduleMap(convexDirectory)}, components: {${Array.join(components, "\n")}} };`
|
|
690
|
+
], "\n"));
|
|
648
691
|
});
|
|
649
|
-
//#endregion
|
|
650
692
|
export { codegen, codegenHandler, generateComponents, generateWithSnapshot, loadPreviousFunctionPaths, makeCodegenHandler, updateDeclarations };
|
|
651
693
|
|
|
652
694
|
//# sourceMappingURL=codegen.mjs.map
|