@powerhousedao/vetra 6.2.3-dev.77 → 6.2.3-dev.79

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.
Files changed (51) hide show
  1. package/dist/codegen/index.d.ts +2 -2
  2. package/dist/codegen/index.js +2 -2
  3. package/dist/codegen/spec.js +1 -1
  4. package/dist/document-models/app-module/index.d.ts +2 -2
  5. package/dist/document-models/app-module/index.js +1 -1
  6. package/dist/document-models/index.d.ts +2 -2
  7. package/dist/document-models/index.js +2 -2
  8. package/dist/document-models/processor-module/index.d.ts +3 -3
  9. package/dist/document-models/processor-module/index.js +4 -4
  10. package/dist/{editor-DbE7t0TU.js → editor-CbT_8Z6A.js} +2 -2
  11. package/dist/{editor-DbE7t0TU.js.map → editor-CbT_8Z6A.js.map} +1 -1
  12. package/dist/editors/index.d.ts +4 -4
  13. package/dist/editors/index.js +1 -1
  14. package/dist/{factory-BLQkEgxk.js → factory-BQp6QPQO.js} +15 -11
  15. package/dist/factory-BQp6QPQO.js.map +1 -0
  16. package/dist/{index-CKCays-S.d.ts → index-BAeTvhwh.d.ts} +2 -2
  17. package/dist/{index-CKCays-S.d.ts.map → index-BAeTvhwh.d.ts.map} +1 -1
  18. package/dist/{index-mYlWU47F.d.ts → index-CBcJ_oc6.d.ts} +2 -2
  19. package/dist/{index-mYlWU47F.d.ts.map → index-CBcJ_oc6.d.ts.map} +1 -1
  20. package/dist/{index-cdL5k2sw.d.ts → index-CScZx1m9.d.ts} +9 -3
  21. package/dist/index-CScZx1m9.d.ts.map +1 -0
  22. package/dist/{index-B52jv-LY.d.ts → index-DIpsNezM.d.ts} +2 -2
  23. package/dist/{index-B52jv-LY.d.ts.map → index-DIpsNezM.d.ts.map} +1 -1
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +3 -3
  26. package/dist/{module-d1-9VDGb.js → module-23VayWKe.js} +5 -5
  27. package/dist/module-23VayWKe.js.map +1 -0
  28. package/dist/{module-CZLWjrD_.js → module-B6S4QGOx.js} +2 -2
  29. package/dist/{module-CZLWjrD_.js.map → module-B6S4QGOx.js.map} +1 -1
  30. package/dist/{module-Db8mmgzN.js → module-BktWa0rB.js} +11 -9
  31. package/dist/module-BktWa0rB.js.map +1 -0
  32. package/dist/{ph-factories-HuC7_vvF.js → ph-factories-fEke-Nr8.js} +2 -2
  33. package/dist/{ph-factories-HuC7_vvF.js.map → ph-factories-fEke-Nr8.js.map} +1 -1
  34. package/dist/{processor-kRJ48ypM.js → processor-C_zliXhw.js} +356 -322
  35. package/dist/processor-C_zliXhw.js.map +1 -0
  36. package/dist/processors/codegen/index.d.ts.map +1 -1
  37. package/dist/processors/codegen/index.js +2 -2
  38. package/dist/processors/index.js +1 -1
  39. package/dist/{spec-api-B01RpZM-.js → spec-api-BGj7gcQn.js} +16 -10
  40. package/dist/{spec-api-B01RpZM-.js.map → spec-api-BGj7gcQn.js.map} +1 -1
  41. package/dist/{switchboard-CZ87bHRJ.js → switchboard-DjCPLtMW.js} +2 -2
  42. package/dist/{switchboard-CZ87bHRJ.js.map → switchboard-DjCPLtMW.js.map} +1 -1
  43. package/dist/{utils-w_21RRK6.js → utils-BJk4_43W.js} +22 -2
  44. package/dist/utils-BJk4_43W.js.map +1 -0
  45. package/package.json +9 -9
  46. package/dist/factory-BLQkEgxk.js.map +0 -1
  47. package/dist/index-cdL5k2sw.d.ts.map +0 -1
  48. package/dist/module-Db8mmgzN.js.map +0 -1
  49. package/dist/module-d1-9VDGb.js.map +0 -1
  50. package/dist/processor-kRJ48ypM.js.map +0 -1
  51. package/dist/utils-w_21RRK6.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processor-C_zliXhw.js","names":["installFeatureDependencies","installForFeatures","installFeatureDependencies","installFeatureDependencies"],"sources":["../processors/codegen/document-handlers/base-document-gen.ts","../processors/codegen/interactive-manager.ts","../processors/codegen/written-files.ts","../processors/codegen/document-handlers/document-codegen-manager.ts","../processors/codegen/document-handlers/generators/utils.ts","../processors/codegen/document-handlers/generators/app-generator.ts","../processors/codegen/document-handlers/generators/document-editor-generator.ts","../processors/codegen/document-handlers/generators/document-model-generator.ts","../processors/codegen/document-handlers/generators/package-generator.ts","../processors/codegen/document-handlers/generators/processor-generator.ts","../processors/codegen/document-handlers/generators/subgraph-generator.ts","../processors/codegen/document-handlers/document-codegen-factory.ts","../processors/codegen/processor.ts"],"sourcesContent":["import type { Project } from \"ts-morph\";\nimport type {\n CodegenInput,\n CodegenJob,\n Config,\n GenerateResult,\n} from \"./types.js\";\n\n/** The base of the generators, one per document type or set of types. */\nexport abstract class BaseDocumentGen {\n /** The document type or types this generator handles. */\n abstract readonly supportedDocumentTypes: string | string[];\n project: Project;\n\n constructor(\n protected config: Config,\n project: Project,\n ) {\n this.project = project;\n }\n\n /** Generates code for the document; throws when generation fails. */\n abstract generate(\n strand: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult>;\n\n supportsDocumentType(documentType: string): boolean {\n if (typeof this.supportedDocumentTypes === \"string\") {\n return this.supportedDocumentTypes === documentType;\n }\n return this.supportedDocumentTypes.includes(documentType);\n }\n\n getSupportedDocumentTypes(): string[] {\n if (typeof this.supportedDocumentTypes === \"string\") {\n return [this.supportedDocumentTypes];\n }\n return [...this.supportedDocumentTypes];\n }\n\n /** The module's name in the strand's state, for its codegen status. */\n moduleName(strand: CodegenInput): string | undefined {\n const state = strand.state as { global?: { name?: unknown } } | undefined;\n const name = state?.global?.name;\n return typeof name === \"string\" && name !== \"\" ? name : undefined;\n }\n\n /** Why this strand is not generated from; undefined when it is. */\n skipReason(strand: CodegenInput): string | undefined {\n if (!strand.documentId || !strand.documentType) {\n return \"The operation names no document\";\n }\n if (!this.supportsDocumentType(strand.documentType)) {\n return `No generator for document type ${strand.documentType}`;\n }\n return undefined;\n }\n\n shouldProcess(strand: CodegenInput): boolean {\n return this.skipReason(strand) === undefined;\n }\n}\n","import { createInterface } from \"node:readline\";\nimport type { CodegenInput } from \"./document-handlers/types.js\";\nimport { logger } from \"./logger.js\";\n\nexport interface QueuedStrand {\n strand: CodegenInput;\n timestamp: number;\n}\n\n/**\n * InteractiveManager handles user interaction for code generation confirmation\n * Supports both individual strand processing and queue-based batch processing\n */\nexport class InteractiveManager {\n private isInteractiveMode: boolean;\n private processingConfirmation = false;\n private strandQueue = new Map<string, QueuedStrand>();\n\n constructor(interactiveMode = false) {\n this.isInteractiveMode = interactiveMode;\n }\n\n private getDocumentKey(documentType: string, documentId: string): string {\n return `${documentType}:${documentId}`;\n }\n\n /**\n * Add a strand to the queue, replacing any existing strand for the same document\n */\n public queueStrand(strand: CodegenInput): void {\n const documentKey = this.getDocumentKey(\n strand.documentType,\n strand.documentId,\n );\n\n this.strandQueue.set(documentKey, {\n strand,\n timestamp: Date.now(),\n });\n\n logger.debug(\n `>>> Queued strand for ${documentKey}, queue size: ${this.strandQueue.size}`,\n );\n }\n\n /**\n * Drop the queued strands the predicate matches\n */\n public discardWhere(predicate: (strand: CodegenInput) => boolean): void {\n for (const [key, queued] of this.strandQueue) {\n if (predicate(queued.strand)) this.strandQueue.delete(key);\n }\n }\n\n /**\n * Get all queued strands\n */\n public getQueuedStrands(): QueuedStrand[] {\n return Array.from(this.strandQueue.values());\n }\n\n /**\n * Clear and return all queued strands\n */\n public clearQueue(): QueuedStrand[] {\n const queuedStrands = Array.from(this.strandQueue.values());\n this.strandQueue.clear();\n return queuedStrands;\n }\n\n /**\n * Get the current queue size\n */\n public getQueueSize(): number {\n return this.strandQueue.size;\n }\n\n private async promptUserConfirmation(): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔄 Code generation ready to run.\");\n console.log(\"=\".repeat(50));\n\n process.stdout.write(\n \"Do you want to proceed with code generation? (y/n): \\n\\n\",\n );\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n console.log(\"\"); // Add blank line after user input\n resolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n });\n });\n }\n\n /**\n * Process generation with user confirmation (legacy single-strand method)\n * This method assumes interactive mode is already enabled (checked by caller)\n */\n public async processWithConfirmation<T>(\n documentType: string,\n generator: () => Promise<T>,\n ): Promise<T | null> {\n if (this.processingConfirmation) {\n logger.debug(\"Already processing confirmation, skipping\");\n return null;\n }\n\n this.processingConfirmation = true;\n\n try {\n // Always prompt user since this method only called in interactive mode\n const shouldProceed = await this.promptUserConfirmation();\n\n if (!shouldProceed) {\n logger.info(`❌ Code generation cancelled by user for ${documentType}`);\n return null;\n }\n\n logger.info(`✅ User approved code generation for ${documentType}`);\n\n const result = await generator();\n return result;\n } catch (error) {\n logger.error(\n `❌ Error during interactive code generation for ${documentType}:`,\n error,\n );\n throw error;\n } finally {\n this.processingConfirmation = false;\n }\n }\n\n /**\n * Process all queued strands with a single user confirmation\n * This is the main method for queue-based interactive processing\n */\n public async processQueueWithConfirmation(\n processor: (strands: QueuedStrand[]) => Promise<void>,\n onCancel?: (strands: QueuedStrand[]) => void,\n ): Promise<void> {\n if (this.processingConfirmation) {\n logger.debug(\n \"Already processing confirmation, skipping queue processing\",\n );\n return;\n }\n\n // Check if there are any strands to process\n let queuedStrands = this.getQueuedStrands();\n if (queuedStrands.length === 0) {\n logger.debug(\"No strands in queue to process\");\n return;\n }\n\n this.processingConfirmation = true;\n\n try {\n // Prompt user for confirmation\n const shouldProceed = await this.promptUserConfirmation();\n\n if (!shouldProceed) {\n logger.info(\"❌ Code generation cancelled by user\");\n onCancel?.(this.clearQueue());\n return;\n }\n\n // Get and clear the final queue state right before processing\n // (in case new strands were added while waiting for user input)\n queuedStrands = this.clearQueue();\n if (queuedStrands.length === 0) {\n logger.info(\"ℹ️ No documents to process\");\n return;\n }\n\n logger.info(\n `✅ User approved code generation for ${queuedStrands.length} document(s)`,\n );\n\n // Process all queued strands\n await processor(queuedStrands);\n logger.info(\"✅ Code generation completed\");\n } catch (error) {\n logger.error(\n \"❌ Error during interactive queue processing: @error\",\n error,\n );\n throw error;\n } finally {\n this.processingConfirmation = false;\n }\n }\n\n public setInteractiveMode(enabled: boolean): void {\n this.isInteractiveMode = enabled;\n logger.debug(`Interactive mode set to: ${enabled}`);\n }\n\n public isInteractive(): boolean {\n return this.isInteractiveMode;\n }\n\n public isProcessing(): boolean {\n return this.processingConfirmation;\n }\n}\n","import type { Dirent } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\nconst SKIPPED_DIRS = new Set([\"node_modules\", \"dist\", \"backup-documents\"]);\nconst MAX_FILES = 500;\n\n/** The project's files modified at or after `since`, relative and sorted. */\nexport async function filesWrittenSince(\n projectDir: string,\n since: number,\n): Promise<string[]> {\n const written: string[] = [];\n const visit = async (dir: string): Promise<void> => {\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (written.length >= MAX_FILES) return;\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || SKIPPED_DIRS.has(entry.name)) {\n continue;\n }\n await visit(path);\n } else if (entry.isFile()) {\n try {\n if ((await stat(path)).mtimeMs >= since) {\n written.push(relative(projectDir, path).replaceAll(\"\\\\\", \"/\"));\n }\n } catch {\n // Removed while listing.\n }\n }\n }\n };\n await visit(projectDir);\n return written.sort();\n}\n","import { afterPendingInstalls, installsPending } from \"@powerhousedao/codegen\";\nimport {\n type CodegenState,\n type CodegenStatusRegistry,\n getCodegenStatusRegistry,\n} from \"@powerhousedao/shared/processors\";\nimport type { Project } from \"ts-morph\";\nimport type { QueuedStrand } from \"../interactive-manager.js\";\nimport { InteractiveManager } from \"../interactive-manager.js\";\nimport { logger } from \"../logger.js\";\nimport { filesWrittenSince } from \"../written-files.js\";\nimport type { BaseDocumentGen } from \"./base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, Config } from \"./types.js\";\n\nconst DEFAULT_DEBOUNCE_TIME = 1000; // wait 1 second between codegen calls\nconst MODULE_NOT_FOUND_CODES = new Set([\n \"ERR_MODULE_NOT_FOUND\",\n \"MODULE_NOT_FOUND\",\n \"ERR_PACKAGE_PATH_NOT_EXPORTED\",\n]);\nconst MODULE_NOT_FOUND_MESSAGE =\n /Cannot find (module|package)|Failed to resolve (import|entry)|Failed to load url/;\n\n/** Whether a document belongs to what this manager generates from. */\nexport type DocumentScope = (documentId: string) => Promise<boolean>;\n\n/**\n * Manager class responsible for routing documents to the correct generator\n * and managing generator registration and instantiation\n */\nexport class DocumentCodegenManager {\n project: Project;\n private generators = new Map<string, BaseDocumentGen>();\n private debounceTimers = new Map<string, NodeJS.Timeout>();\n // One job at a time, so none runs while another job's install relinks node_modules.\n private jobs: Promise<void> = Promise.resolve();\n private queuedJobs = new Map<string, CodegenInput>();\n private runningJobs = 0;\n /** The wait before retrying a module-resolution failure when no install is queued. */\n retryDelayMs = 3000;\n private interactiveManager: InteractiveManager;\n private isInScope: DocumentScope = () => Promise.resolve(true);\n readonly status: CodegenStatusRegistry;\n\n constructor(\n private config: Config,\n project: Project,\n interactiveMode = false,\n status: CodegenStatusRegistry = getCodegenStatusRegistry(),\n ) {\n this.project = project;\n this.interactiveManager = new InteractiveManager(interactiveMode);\n this.status = status;\n }\n\n /**\n * Limit generation to the documents `isInScope` accepts, checked when the\n * debounce fires\n */\n setScope(isInScope: DocumentScope): void {\n this.isInScope = isInScope;\n }\n\n /**\n * Register a generator class for a specific document type\n */\n registerGenerator(\n documentType: string,\n generatorClass: new (config: Config, project: Project) => BaseDocumentGen,\n ): void {\n if (this.generators.has(documentType)) {\n logger.warn(\n `⚠️ Generator for document type \"${documentType}\" is already registered. Overwriting.`,\n );\n }\n\n this.generators.set(\n documentType,\n new generatorClass(this.config, this.project),\n );\n logger.debug(`✅ Registered generator for document type: ${documentType}`);\n }\n\n /**\n * Register a generator class that supports multiple document types\n */\n registerMultiTypeGenerator(\n generatorClass: new (config: Config, project: Project) => BaseDocumentGen,\n ): void {\n const generator = new generatorClass(this.config, this.project);\n const supportedTypes = generator.getSupportedDocumentTypes();\n\n for (const documentType of supportedTypes) {\n if (this.generators.has(documentType)) {\n logger.warn(\n `⚠️ Generator for document type \"${documentType}\" is already registered. Overwriting.`,\n );\n }\n this.generators.set(documentType, generator);\n }\n\n logger.debug(\n `✅ Registered multi-type generator for document types: ${supportedTypes.join(\", \")}`,\n );\n }\n\n /**\n * Get a generator instance for the given document type\n * Public method to allow external access for validation\n */\n public getGenerator(documentType: string): BaseDocumentGen | undefined {\n return this.generators.get(documentType);\n }\n\n /**\n * Get all registered document types\n */\n getRegisteredDocumentTypes(): string[] {\n return Array.from(this.generators.keys());\n }\n\n /**\n * Check if a document type is supported\n */\n isDocumentTypeSupported(documentType: string): boolean {\n return this.generators.has(documentType);\n }\n\n /**\n * Route a document to the appropriate generator and handle the generation\n * Handles both interactive and non-interactive modes with queue-based processing\n */\n routeAndGenerate(strand: CodegenInput): Promise<void> {\n const documentType = strand.documentType;\n\n if (!documentType) {\n logger.error(\"❌ Document type is missing from strand state\");\n throw new Error(\"Document type is missing from strand state\");\n }\n\n const generator = this.getGenerator(documentType);\n\n if (!generator) {\n logger.warn(`⚠️ No generator found for document type: ${documentType}`);\n logger.warn(\n `ℹ️ Supported document types: ${this.getRegisteredDocumentTypes().join(\", \")}`,\n );\n throw new Error(`Unsupported document type: ${documentType}`);\n }\n\n // Scope and validation are checked when the debounce fires, on the\n // document's final state.\n this.status.set({\n documentId: strand.documentId,\n documentType,\n state: \"queued\",\n message: this.interactiveManager.isInteractive()\n ? \"Waiting for confirmation in the terminal running Vetra\"\n : \"Waiting for the document's changes to settle\",\n });\n // Different flow for interactive vs non-interactive mode\n if (this.interactiveManager.isInteractive()) {\n // Interactive mode: queue strands and use debounce timer to trigger batch processing\n logger.debug(\n `>>> Queueing strand for interactive processing: ${documentType}:${strand.documentId}`,\n );\n\n // Add strand to queue (will replace any existing strand for same document)\n this.interactiveManager.queueStrand(strand);\n\n // Clear any existing debounce timer for interactive processing\n const existingTimer = this.debounceTimers.get(\"interactive\");\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Set up debounce timer for batch interactive processing\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n const debounceTimer = setTimeout(async () => {\n try {\n const rejected = new Set<CodegenInput>();\n for (const { strand } of this.interactiveManager.getQueuedStrands()) {\n if (!(await this.accepts(strand))) rejected.add(strand);\n }\n this.interactiveManager.discardWhere((queued) =>\n rejected.has(queued),\n );\n await this.interactiveManager.processQueueWithConfirmation(\n async (queuedStrands: QueuedStrand[]) => {\n await this.processQueuedStrands(queuedStrands);\n },\n (cancelled) => {\n for (const { strand } of cancelled) {\n this.setStatus(strand, \"skipped\", \"Cancelled in the terminal\");\n }\n },\n );\n } catch (error) {\n logger.error(\n \"❌ Error during interactive batch processing: @error\",\n error,\n );\n } finally {\n // Clean up the timer reference\n this.debounceTimers.delete(\"interactive\");\n }\n }, DEFAULT_DEBOUNCE_TIME);\n\n // Store the timer reference using 'interactive' key\n this.debounceTimers.set(\"interactive\", debounceTimer);\n } else {\n // Non-interactive mode: use debouncing per document instance\n // Create unique key for this specific document instance\n const timerKey = `${documentType}:${strand.documentId}`;\n\n // Clear any existing debounce timer for this document instance\n const existingTimer = this.debounceTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Set up new debounced generation (no interactive confirmation)\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n const debounceTimer = setTimeout(async () => {\n try {\n if (!(await this.accepts(strand))) return;\n logger.debug(\n `🔄 Routing document type \"${documentType}\" to generator (debounced)`,\n );\n await this.enqueueJob(strand);\n } finally {\n // Clean up the timer reference\n this.debounceTimers.delete(timerKey);\n }\n }, DEFAULT_DEBOUNCE_TIME);\n\n // Store the timer reference\n this.debounceTimers.set(timerKey, debounceTimer);\n }\n return Promise.resolve();\n }\n\n /** In scope first, so documents out of scope are never validated or logged. */\n private async accepts(strand: CodegenInput): Promise<boolean> {\n const generator = this.getGenerator(strand.documentType);\n if (!generator) return false;\n if (!(await this.isInScope(strand.documentId))) {\n logger.debug(\n `Document ${strand.documentId} is not in the Vetra drive, skipping codegen`,\n );\n this.status.delete(strand.documentId);\n this.queuedJobs.delete(strand.documentId);\n return false;\n }\n const reason = generator.skipReason(strand);\n if (reason !== undefined) {\n this.setStatus(strand, \"skipped\", reason);\n this.queuedJobs.delete(strand.documentId);\n return false;\n }\n return true;\n }\n\n /** Queues a job; one already queued for the document runs the latest strand. */\n private enqueueJob(strand: CodegenInput): Promise<void> {\n const { documentId } = strand;\n const alreadyQueued = this.queuedJobs.has(documentId);\n this.queuedJobs.set(documentId, strand);\n if (this.runningJobs > 0) {\n this.setStatus(\n strand,\n \"queued\",\n \"Waiting for codegen of other documents to finish\",\n );\n }\n if (alreadyQueued) return this.jobs;\n this.jobs = this.jobs.then(async () => {\n const latest = this.queuedJobs.get(documentId);\n this.queuedJobs.delete(documentId);\n const generator = latest && this.getGenerator(latest.documentType);\n if (!latest || !generator) return;\n this.runningJobs++;\n try {\n await this.runJob(latest, generator);\n } finally {\n this.runningJobs--;\n }\n });\n return this.jobs;\n }\n\n /** Runs a job after pending installs, once more after a module-resolution failure. */\n private async runJob(\n strand: CodegenInput,\n generator: BaseDocumentGen,\n ): Promise<void> {\n await this.afterInstalls(\n strand,\n \"Waiting for a dependency install to finish\",\n );\n const error = await this.attempt(strand, generator);\n if (error === undefined) return;\n if (!isModuleResolutionError(error)) {\n this.setStatus(strand, \"failed\", errorMessage(error));\n return;\n }\n logger.warn(\n `Codegen for ${strand.documentType} ${strand.documentId} could not resolve a module; retrying once installs finish: ${errorMessage(error)}`,\n );\n const waited = await this.afterInstalls(\n strand,\n `Retrying once dependency installs finish, after: ${errorMessage(error)}`,\n );\n if (!waited) {\n await new Promise((resolve) => setTimeout(resolve, this.retryDelayMs));\n }\n const retryError = await this.attempt(strand, generator);\n if (retryError !== undefined) {\n this.setStatus(\n strand,\n \"failed\",\n `${errorMessage(retryError)} (also after a retry; if an install is running, run it to the end, then change the document again)`,\n );\n }\n }\n\n /** Waits for queued installs, saying so; resolves to whether any was queued. */\n private async afterInstalls(\n strand: CodegenInput,\n message: string,\n ): Promise<boolean> {\n if (!installsPending()) return false;\n this.setStatus(strand, \"waiting-for-install\", message);\n await afterPendingInstalls();\n return true;\n }\n\n /** Generates once; records done or skipped, or resolves to the error. */\n private async attempt(\n strand: CodegenInput,\n generator: BaseDocumentGen,\n ): Promise<unknown> {\n const startedAt = Date.now();\n const job: CodegenJob = {\n waitingForInstall: (message) =>\n this.setStatus(strand, \"waiting-for-install\", message),\n running: () => this.setStatus(strand, \"running\"),\n };\n job.running();\n try {\n const result = await generator.generate(strand, job);\n if (result) {\n this.setStatus(strand, \"skipped\", result.skipped);\n return;\n }\n const files = await filesWrittenSince(\n this.config.CURRENT_WORKING_DIR,\n startedAt,\n );\n this.setStatus(strand, \"done\", undefined, files);\n logger.debug(\n `✅ Successfully generated code for document type: ${strand.documentType}`,\n );\n return undefined;\n } catch (error) {\n logger.error(\n `❌ Error generating code for document type \"${strand.documentType}\":`,\n error,\n );\n return error ?? new Error(\"Codegen failed\");\n }\n }\n\n private setStatus(\n strand: CodegenInput,\n state: CodegenState,\n message?: string,\n files?: string[],\n ): void {\n this.status.set({\n documentId: strand.documentId,\n documentType: strand.documentType,\n name: this.getGenerator(strand.documentType)?.moduleName(strand),\n state,\n message,\n files,\n });\n }\n\n /**\n * Process multiple strands in priority order (document-model types first)\n */\n private async processQueuedStrands(\n queuedStrands: QueuedStrand[],\n ): Promise<void> {\n logger.debug(`🔄 Processing ${queuedStrands.length} queued strand(s)`);\n\n // Sort by priority (document-model first to ensure dependencies exist)\n const documentModelStrands = queuedStrands.filter(\n (qs: QueuedStrand) =>\n qs.strand.documentType === \"powerhouse/document-model\",\n );\n const otherStrands = queuedStrands.filter(\n (qs: QueuedStrand) =>\n qs.strand.documentType !== \"powerhouse/document-model\",\n );\n\n // Process document models first\n for (const queuedStrand of documentModelStrands) {\n await this.processStrand(queuedStrand.strand);\n }\n\n // Then process other document types\n for (const queuedStrand of otherStrands) {\n await this.processStrand(queuedStrand.strand);\n }\n\n logger.debug(\n `✅ Successfully processed all ${queuedStrands.length} queued strand(s)`,\n );\n }\n\n /**\n * Process a single strand (used internally by processQueuedStrands)\n */\n private async processStrand(strand: CodegenInput): Promise<void> {\n const documentType = strand.documentType;\n const generator = this.getGenerator(documentType);\n\n if (!generator) {\n logger.warn(`⚠️ No generator found for document type: ${documentType}`);\n return;\n }\n\n logger.debug(`🔄 Generating code for document type: ${documentType}`);\n await this.enqueueJob(strand);\n }\n\n /**\n * Clear all registered generators\n */\n clearGenerators(): void {\n this.generators.clear();\n logger.debug(\"🧹 Cleared all registered generators\");\n }\n\n /**\n * Get statistics about registered generators\n */\n getStats(): { totalGenerators: number; supportedTypes: string[] } {\n return {\n totalGenerators: this.generators.size,\n supportedTypes: this.getRegisteredDocumentTypes(),\n };\n }\n\n /**\n * Set interactive mode for code generation\n */\n setInteractiveMode(enabled: boolean): void {\n this.interactiveManager.setInteractiveMode(enabled);\n }\n\n /**\n * Check if interactive mode is enabled\n */\n isInteractiveMode(): boolean {\n return this.interactiveManager.isInteractive();\n }\n\n /**\n * Check if the manager is currently processing an interactive confirmation\n */\n isProcessingInteractive(): boolean {\n return this.interactiveManager.isProcessing();\n }\n}\n\nfunction isModuleResolutionError(error: unknown): boolean {\n for (let cause = error; cause instanceof Error; cause = cause.cause) {\n const code = (cause as NodeJS.ErrnoException).code;\n if (code && MODULE_NOT_FOUND_CODES.has(code)) return true;\n if (MODULE_NOT_FOUND_MESSAGE.test(cause.message)) return true;\n }\n return false;\n}\n\nfunction errorMessage(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const cause = error.cause instanceof Error ? `: ${error.cause.message}` : \"\";\n return `${error.message}${cause}`;\n}\n","import {\n type Feature,\n installFeatureDependencies as installForFeatures,\n} from \"@powerhousedao/codegen\";\nimport type {\n MinimalBackupData,\n PHBaseState,\n PHDocument,\n PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport { baseMinimalSaveToFile, baseSaveToFile } from \"document-model/node\";\nimport { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { lintSubgraphTypes } from \"../../../../codegen/subgraph-type-lint.js\";\nimport { logger } from \"../../logger.js\";\nimport type { CodegenJob } from \"../types.js\";\n\nconst BACKUP_FOLDER = \"backup-documents\";\n\n/**\n * Exports a document to the backup directory.\n * Creates the backup directory if it doesn't exist.\n *\n * @param document - The document to backup\n * @param workingDir - Current working directory\n * @param extension - File extension for the document type (without dot)\n * @param name - Name of the document to use for the backup file (optional)\n * @returns Promise resolving to the backup file path, or undefined if backup failed\n */\nexport async function backupDocument(\n document: PHDocument,\n workingDir: string,\n extension: string = \"\",\n name?: string,\n): Promise<string | undefined> {\n const docName = name ?? document.header.name;\n\n try {\n const backupPath = join(workingDir, BACKUP_FOLDER);\n await mkdir(backupPath, { recursive: true });\n\n const filePath = await baseSaveToFile(\n document,\n backupPath,\n extension,\n docName,\n );\n\n logger.debug(`📁 Document backed up to: ${filePath}`);\n return filePath;\n } catch (error) {\n logger.warn(`⚠️ Failed to backup document \"${docName}\":`, error);\n return undefined;\n }\n}\n\n/**\n * Creates a minimal backup of a document from strand data.\n * Used when the full document is not available (e.g., in onOperations handler).\n */\nexport async function minimalBackupDocument(\n data: MinimalBackupData,\n workingDir: string,\n extension?: string,\n): Promise<string | undefined> {\n // The reactor's resultingState carries the document header alongside the\n // state scopes; lift its protocol versions into the backup header.\n const { header, ...state } = data.state as PHBaseState & {\n header?: PHDocumentHeader;\n };\n\n try {\n const backupPath = join(workingDir, BACKUP_FOLDER);\n await mkdir(backupPath, { recursive: true });\n\n const filePath = await baseMinimalSaveToFile(\n {\n ...data,\n state,\n protocolVersions: data.protocolVersions ?? header?.protocolVersions,\n },\n backupPath,\n extension ?? \"\",\n );\n\n logger.debug(`Document backed up to: ${filePath}`);\n return filePath;\n } catch (error) {\n logger.warn(`Failed to backup document \"${data.name}\":`, error);\n return undefined;\n }\n}\n\nexport async function warnSubgraphTypeConflicts(\n workingDir: string,\n): Promise<void> {\n let warnings: string[];\n try {\n warnings = await lintSubgraphTypes(workingDir);\n } catch (error) {\n logger.warn(\n `Failed to check subgraph type names: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n for (const warning of warnings) logger.warn(`⚠️ ${warning}`);\n}\n\n/** Adds and installs what `features` need before their files are written:\n * the package loader reloads on those files, so their imports must resolve. */\nexport async function installFeatureDependencies(\n features: readonly Feature[],\n projectDir: string,\n waiting?: string,\n job?: CodegenJob,\n): Promise<void> {\n const install = { ran: false };\n try {\n await installForFeatures(features, projectDir, {\n log: (message) => logger.info(message),\n warn: (message) => logger.warn(`⚠️ ${message}`),\n waiting,\n onInstall: (packages, command) => {\n install.ran = true;\n job?.waitingForInstall(\n `Installing ${packages.join(\", \")} with \\`${command}\\``,\n );\n },\n });\n } catch (error) {\n logger.warn(\n `⚠️ Could not add the dependencies of ${features.join(\", \")}: ${(error as Error).message}`,\n );\n } finally {\n if (install.ran) job?.running();\n }\n}\n","import { generateApp } from \"@powerhousedao/codegen\";\nimport type {\n AppModuleGlobalState,\n AppModulePHState,\n} from \"@powerhousedao/vetra/document-models/app-module\";\nimport { kebabCase } from \"change-case\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, GenerateResult } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for app documents\n */\nexport class AppGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/app\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): AppModuleGlobalState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as AppModulePHState;\n return fullState.global;\n }\n\n skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The app has no state\";\n else if (!state.name) reason = \"The app has no name\";\n else if (state.status !== \"CONFIRMED\") {\n reason = `App \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(input: CodegenInput): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The app has no state\" };\n }\n\n logger.info(`🔄 Starting app generation for app: ${state.name}`);\n try {\n await generateApp(\n {\n ...this.config.PH_CONFIG,\n appName: state.name,\n appId: kebabCase(state.name),\n allowedDocumentTypes: state.allowedDocumentTypes ?? [],\n isDragAndDropEnabled: state.isDragAndDropEnabled,\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during app generation for app ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ App generation completed successfully for app: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as AppModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import { generateEditor } from \"@powerhousedao/codegen\";\nimport { kebabCase } from \"change-case\";\nimport type {\n DocumentEditorPHState,\n DocumentEditorState,\n} from \"../../../../document-models/document-editor/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, GenerateResult } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for document editor documents\n */\nexport class DocumentEditorGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/document-editor\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): DocumentEditorState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as DocumentEditorPHState;\n return fullState.global;\n }\n\n skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The editor has no state\";\n else if (!state.name) reason = \"The editor has no name\";\n else if (state.documentTypes.length === 0) {\n reason = `Editor \"${state.name}\" has no document types`;\n } else if (state.status !== \"CONFIRMED\") {\n reason = `Editor \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(input: CodegenInput): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n if (!state) {\n return { skipped: \"The editor has no state\" };\n }\n\n logger.info(`🔄 Starting editor generation for: ${state.name}`);\n try {\n await generateEditor(\n {\n ...this.config.PH_CONFIG,\n editorName: state.name,\n documentTypes: state.documentTypes.map((dt) => dt.documentType),\n editorId: kebabCase(state.name),\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during editor generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ Editor generation completed successfully for: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as DocumentEditorPHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import {\n generateDocumentModel,\n validateDocumentModelState,\n} from \"@powerhousedao/codegen\";\nimport type {\n DocumentModelGlobalState,\n DocumentModelPHState,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput } from \"../types.js\";\nimport { minimalBackupDocument, warnSubgraphTypeConflicts } from \"./utils.js\";\n\n/**\n * Generator for document model documents\n */\nexport class DocumentModelGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/document-model\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): DocumentModelGlobalState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as DocumentModelPHState;\n return fullState.global;\n }\n\n skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const globalState = this.extractGlobalState(input);\n if (!globalState) {\n logger.debug(\n `>>> No global state found for document model: ${input.documentId}`,\n );\n return \"The document model has no global state\";\n }\n\n const validationResult = validateDocumentModelState(globalState);\n if (!validationResult.isValid) {\n const errorList = validationResult.errors\n .map((error) => ` - ${error}`)\n .join(\"\\n\");\n logger.info(\n `⚠️ Skipped code generation for '${globalState.name || input.documentId}' due to validation errors:\\n${errorList}`,\n );\n return `The document model is not ready for code generation:\\n${errorList}`;\n }\n\n logger.info(\n `Document model ${globalState.name} is valid, proceeding with code generation`,\n );\n return undefined;\n }\n\n async generate(input: CodegenInput): Promise<void> {\n const globalState = this.extractGlobalState(input);\n if (!globalState) {\n throw new Error(\n `No global state found for document model: ${input.documentId}`,\n );\n }\n logger.debug(\n `🔄 Starting code generation for document model: ${globalState.name}`,\n );\n try {\n await generateDocumentModel(globalState, this.project);\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during code generation for ${globalState.name}:`,\n error,\n );\n throw error;\n }\n logger.info(\n `✅ Code generation completed successfully for: ${globalState.name}`,\n );\n await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);\n\n const fullState = input.state as DocumentModelPHState;\n const extension = globalState.extension?.replace(/^\\.+|\\.+$/g, \"\") || \"\";\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: fullState,\n name: globalState.name,\n },\n this.config.CURRENT_WORKING_DIR,\n extension,\n );\n }\n}\n","import { createOrUpdateManifest } from \"@powerhousedao/codegen/file-builders\";\nimport type {\n VetraPackageGlobalState,\n VetraPackagePHState,\n} from \"../../../../document-models/vetra-package/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for package documents\n */\nexport class PackageGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/package\";\n\n skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n if (!input.state) {\n logger.debug(`>>> No state found for package: ${input.documentId}`);\n return \"The package has no state\";\n }\n return undefined;\n }\n\n async generate(input: CodegenInput): Promise<void> {\n const fullState = input.state as VetraPackagePHState;\n const state = fullState.global as VetraPackageGlobalState;\n\n await createOrUpdateManifest(\n {\n name: state.name ?? \"\",\n category: state.category ?? \"\",\n description: state.description ?? \"\",\n publisher: {\n name: state.author?.name ?? \"\",\n url: state.author?.website ?? \"\",\n },\n },\n this.config.CURRENT_WORKING_DIR,\n );\n\n // Backup the document\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: fullState,\n name: \"vetra-package\",\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import { type Feature, generateProcessor } from \"@powerhousedao/codegen\";\nimport {\n PROCESSOR_APPS,\n type ProcessorApp,\n type ProcessorApps,\n} from \"@powerhousedao/shared/processors\";\nimport type {\n ProcessorModulePHState,\n ProcessorModuleState,\n} from \"../../../../document-models/processor-module/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, GenerateResult } from \"../types.js\";\nimport { installFeatureDependencies, minimalBackupDocument } from \"./utils.js\";\n\nconst PROCESSOR_TYPES = {\n analytics: \"analytics\",\n relational: \"relationalDb\",\n} as const;\n\n/**\n * Generator for processor documents\n */\nexport class ProcessorGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/processor\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): ProcessorModuleState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as ProcessorModulePHState;\n return fullState.global;\n }\n\n skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const reason = invalidReason(this.extractGlobalState(input));\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(\n input: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The processor has no state\" };\n }\n const processorType =\n PROCESSOR_TYPES[state.type as keyof typeof PROCESSOR_TYPES];\n const processorApps = state.processorApps as ProcessorApps;\n logger.info(`🔄 Starting processor generation for: ${state.name}`);\n try {\n const features: Feature[] =\n processorType === \"analytics\"\n ? [\"analyticsProcessor\"]\n : [\"relationalDbProcessor\"];\n await installFeatureDependencies(\n features,\n this.config.CURRENT_WORKING_DIR,\n `processor \"${state.name}\"`,\n job,\n );\n\n await generateProcessor(\n {\n processorName: state.name,\n processorType,\n documentTypes: state.documentTypes.map((dt) => dt.documentType),\n processorApps,\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during processor generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ Processor generation completed successfully for: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as ProcessorModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n\nfunction invalidReason(\n state: ProcessorModuleState | undefined,\n): string | undefined {\n if (!state) return \"The processor has no state\";\n if (!state.name) return \"The processor has no name\";\n const processor = `Processor \"${state.name}\"`;\n if (!state.type) return `${processor} has no type`;\n if (!(state.type in PROCESSOR_TYPES)) {\n return `${processor} has the unsupported type \"${state.type}\"; use ${Object.keys(PROCESSOR_TYPES).join(\" or \")}`;\n }\n if (state.documentTypes.length === 0) {\n return `${processor} has no document types`;\n }\n if (state.processorApps.length === 0) {\n return `${processor} has no processor apps`;\n }\n if (!isProcessorApps(state.processorApps)) {\n return `${processor} has unsupported processor apps (${state.processorApps.join(\", \")}); use ${PROCESSOR_APPS.join(\", \")}, each once`;\n }\n if (state.status !== \"CONFIRMED\") {\n return `${processor} is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n return undefined;\n}\n\nfunction isProcessorApps(input: readonly string[]): input is ProcessorApps {\n if (input.length === 0) return false;\n if (new Set(input).size !== input.length) {\n return false;\n }\n if (!input.every((i) => PROCESSOR_APPS.includes(i as ProcessorApp)))\n return false;\n\n return true;\n}\n","import { generateSubgraph } from \"@powerhousedao/codegen\";\nimport { findSubgraphNameConflict } from \"../../../../codegen/subgraph-type-lint.js\";\nimport type {\n SubgraphModulePHState,\n SubgraphModuleState,\n} from \"../../../../document-models/subgraph-module/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, GenerateResult } from \"../types.js\";\nimport {\n installFeatureDependencies,\n minimalBackupDocument,\n warnSubgraphTypeConflicts,\n} from \"./utils.js\";\n\n/**\n * Generator for subgraph documents\n */\nexport class SubgraphGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/subgraph\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): SubgraphModuleState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as SubgraphModulePHState;\n return fullState.global;\n }\n\n skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The subgraph has no state\";\n else if (!state.name) reason = \"The subgraph has no name\";\n else if (state.status !== \"CONFIRMED\") {\n reason = `Subgraph \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(\n input: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The subgraph has no state\" };\n }\n\n logger.info(`🔄 Starting subgraph generation for: ${state.name}`);\n try {\n const conflict = await findSubgraphNameConflict(\n this.config.CURRENT_WORKING_DIR,\n state.name,\n );\n if (conflict) {\n logger.error(`❌ Skipping subgraph generation: ${conflict}`);\n return { skipped: conflict };\n }\n await installFeatureDependencies(\n [\"subgraph\"],\n this.config.CURRENT_WORKING_DIR,\n `subgraph \"${state.name}\"`,\n job,\n );\n await generateSubgraph(state.name, this.project);\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during subgraph generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n logger.info(\n `✅ Subgraph generation completed successfully for: ${state.name}`,\n );\n await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as SubgraphModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import type { CodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport type { Project } from \"ts-morph\";\nimport type { BaseDocumentGen } from \"./base-document-gen.js\";\nimport { DocumentCodegenManager } from \"./document-codegen-manager.js\";\nimport {\n AppGenerator,\n DocumentEditorGenerator,\n DocumentModelGenerator,\n PackageGenerator,\n ProcessorGenerator,\n SubgraphGenerator,\n} from \"./generators/index.js\";\nimport type { Config } from \"./types.js\";\n\n/**\n * Factory class for creating and configuring DocumentCodegenManager instances\n * with all the standard generators pre-registered\n */\nexport class DocumentCodegenFactory {\n /**\n * Create a DocumentCodegenManager with all standard generators registered\n */\n static createManager(\n config: Config,\n project: Project,\n interactiveMode: boolean = false,\n status?: CodegenStatusRegistry,\n ): DocumentCodegenManager {\n const manager = new DocumentCodegenManager(\n config,\n project,\n interactiveMode,\n status,\n );\n\n // Register all the standard generators\n manager.registerGenerator(\n \"powerhouse/document-model\",\n DocumentModelGenerator,\n );\n manager.registerGenerator(\"powerhouse/package\", PackageGenerator);\n manager.registerGenerator(\"powerhouse/app\", AppGenerator);\n manager.registerGenerator(\n \"powerhouse/document-editor\",\n DocumentEditorGenerator,\n );\n manager.registerGenerator(\"powerhouse/subgraph\", SubgraphGenerator);\n manager.registerGenerator(\"powerhouse/processor\", ProcessorGenerator);\n\n return manager;\n }\n\n /**\n * Create a DocumentCodegenManager with only specific generators\n */\n static createManagerWithGenerators(\n config: Config,\n generators: Array<new (config: Config) => any>,\n project: Project,\n interactiveMode: boolean = false,\n status?: CodegenStatusRegistry,\n ): DocumentCodegenManager {\n const manager = new DocumentCodegenManager(\n config,\n project,\n interactiveMode,\n status,\n );\n\n for (const generatorClass of generators) {\n const generator = new generatorClass(config) as BaseDocumentGen;\n const supportedTypes = generator.getSupportedDocumentTypes();\n\n for (const documentType of supportedTypes) {\n manager.registerGenerator(documentType, generatorClass);\n }\n }\n\n return manager;\n }\n\n /**\n * Get all available generator classes\n */\n static getAvailableGenerators() {\n return {\n DocumentModelGenerator,\n PackageGenerator,\n AppGenerator,\n DocumentEditorGenerator,\n SubgraphGenerator,\n ProcessorGenerator,\n };\n }\n}\n","import type {\n IProcessor,\n IReactorClient,\n OperationWithContext,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PowerhouseConfig } from \"@powerhousedao/shared\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { Project } from \"ts-morph\";\nimport type { DocumentCodegenManager } from \"./document-handlers/document-codegen-manager.js\";\nimport { DocumentCodegenFactory } from \"./document-handlers/index.js\";\nimport type { CodegenInput } from \"./document-handlers/types.js\";\nimport { logger } from \"./logger.js\";\n\nexport class CodegenProcessor implements IProcessor {\n private manager: DocumentCodegenManager;\n\n constructor(\n project: Project,\n config: PowerhouseConfig,\n cwd: string,\n private readonly driveId: string,\n private readonly client: IReactorClient,\n interactiveMode = false,\n ) {\n this.manager = DocumentCodegenFactory.createManager(\n {\n PH_CONFIG: config,\n CURRENT_WORKING_DIR: cwd,\n },\n project,\n interactiveMode,\n );\n this.manager.setScope((documentId) => this.isInDrive(documentId));\n\n if (interactiveMode) {\n logger.info(`CodegenProcessor initialized with interactive mode enabled`);\n } else {\n logger.debug(\n `CodegenProcessor initialized with interactive mode disabled`,\n );\n }\n }\n\n async onOperations(operations: OperationWithContext[]): Promise<void> {\n logger.debug(\"CodegenProcessor.onOperations()\");\n\n // Only a document's final state in the batch is generated from.\n const latest = new Map<string, OperationWithContext>();\n for (const operation of operations) {\n latest.set(operation.context.documentId, operation);\n }\n\n for (const { context } of latest.values()) {\n const generator = this.manager.getGenerator(context.documentType);\n if (!generator) {\n logger.debug(\n `No generator found for document type: ${context.documentType}`,\n );\n continue;\n }\n\n const input: CodegenInput = {\n documentId: context.documentId,\n documentType: context.documentType,\n scope: context.scope,\n branch: context.branch,\n state: context.resultingState\n ? JSON.parse(context.resultingState)\n : undefined,\n };\n\n await this.manager.routeAndGenerate(input);\n }\n }\n\n async onDisconnect() {}\n\n // Utility methods for external configuration and monitoring\n public setInteractiveMode(enabled: boolean): void {\n this.manager.setInteractiveMode(enabled);\n }\n\n public isInteractive(): boolean {\n return this.manager.isInteractiveMode();\n }\n\n public isProcessingInteractive(): boolean {\n return this.manager.isProcessingInteractive();\n }\n\n /**\n * The reactor delivers every drive's operations, so membership is checked\n * here: a node of the drive (in any folder, and in drives older than\n * relationship edges), or a child edge from it (a document attached by\n * relationship alone).\n */\n private async isInDrive(documentId: string): Promise<boolean> {\n try {\n const drive = await this.client.get<DocumentDriveDocument>(this.driveId);\n if (drive.state.global.nodes.some((node) => node.id === documentId)) {\n return true;\n }\n } catch (error) {\n logger.debug(`Could not read the Vetra drive ${this.driveId}:`, error);\n }\n try {\n const parents = await this.client.getIncomingRelationshipEdges(\n documentId,\n \"child\",\n );\n return parents.results.some((edge) => edge.sourceId === this.driveId);\n } catch (error) {\n logger.debug(`Could not read the parents of ${documentId}:`, error);\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAsB,kBAAtB,MAAsC;CAMxB;CAHZ;CAEA,YACE,QACA,SACA;EAFU,KAAA,SAAA;EAGV,KAAK,UAAU;CACjB;CAQA,q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gBAAgC;EAC9B,OAAO,KAAK,QAAQ,kBAAkB;CACxC;CAEA,0BAA0C;EACxC,OAAO,KAAK,QAAQ,wBAAwB;CAC9C;;;;;;;CAQA,MAAc,UAAU,YAAsC;EAC5D,IAAI;GAEF,KAAI,MADgB,KAAK,OAAO,IAA2B,KAAK,OAAO,EAAA,CAC7D,MAAM,OAAO,MAAM,MAAM,SAAS,KAAK,OAAO,UAAU,GAChE,OAAO;EAEX,SAAS,OAAO;GACd,OAAO,MAAM,kCAAkC,KAAK,QAAQ,IAAI,KAAK;EACvE;EACA,IAAI;GAKF,QAAO,MAJe,KAAK,OAAO,6BAChC,YACA,OACF,EAAA,CACe,QAAQ,MAAM,SAAS,KAAK,aAAa,KAAK,OAAO;EACtE,SAAS,OAAO;GACd,OAAO,MAAM,iCAAiC,WAAW,IAAI,KAAK;GAClE,OAAO;EACT;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../processors/codegen/factory.ts","../../../processors/codegen/processor.ts"],"mappings":";;;;qBAsCa,uBAAuB;;;qBCzBvB,4BAA4B;mBAOpB;mBACA;UAPX;EAER,YACE,SAAS,SACT,QAAQ,kBACR,aACiB,iBACA,QAAQ,gBACzB;EAqBI,aAAa,YAAY,yBAAyB;EAgClD,gBAAY;EAGX,mBAAmB;EAInB;EAIA;;;;;;;UAUO"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../processors/codegen/factory.ts","../../../processors/codegen/processor.ts"],"mappings":";;;;qBAuCa,uBAAuB;;;qBC1BvB,4BAA4B;mBAOpB;mBACA;UAPX;EAER,YACE,SAAS,SACT,QAAQ,kBACR,aACiB,iBACA,QAAQ,gBACzB;EAqBI,aAAa,YAAY,yBAAyB;EAgClD,gBAAY;EAGX,mBAAmB;EAInB;EAIA;;;;;;;UAUO"}
@@ -1,3 +1,3 @@
1
- import { t as codegenFactoryBuilder } from "../../factory-BLQkEgxk.js";
2
- import { t as CodegenProcessor } from "../../processor-kRJ48ypM.js";
1
+ import { t as codegenFactoryBuilder } from "../../factory-BQp6QPQO.js";
2
+ import { t as CodegenProcessor } from "../../processor-C_zliXhw.js";
3
3
  export { CodegenProcessor, codegenFactoryBuilder };
@@ -1,6 +1,6 @@
1
1
  //#region processors/factory.ts
2
2
  const processorFactory = async (module) => {
3
- const { processorFactoryBuilders } = module.processorApp === "connect" ? await import("../connect-EqImHuZ2.js") : await import("../switchboard-CZ87bHRJ.js");
3
+ const { processorFactoryBuilders } = module.processorApp === "connect" ? await import("../connect-EqImHuZ2.js") : await import("../switchboard-DjCPLtMW.js");
4
4
  const factories = await Promise.all(processorFactoryBuilders.map(async (buildFactory) => await buildFactory(module)));
5
5
  return async (driveHeader) => {
6
6
  const processors = [];
@@ -2,8 +2,8 @@ import { d as appModuleDocumentType, f as reducer, p as actions, r as utils } fr
2
2
  import { t as createAppModuleDocument } from "./ph-factories-CgoFCmG0.js";
3
3
  import { d as documentEditorDocumentType, f as reducer$1, p as actions$1, r as utils$1 } from "./utils-876N1Sph.js";
4
4
  import { t as createDocumentEditorDocument } from "./ph-factories-Bgnr3mK3.js";
5
- import { d as processorModuleDocumentType, f as reducer$2, p as actions$2, r as utils$2 } from "./utils-w_21RRK6.js";
6
- import { t as createProcessorModuleDocument } from "./ph-factories-HuC7_vvF.js";
5
+ import { d as processorModuleDocumentType, f as reducer$2, g as actions$2, r as utils$2 } from "./utils-BJk4_43W.js";
6
+ import { t as createProcessorModuleDocument } from "./ph-factories-fEke-Nr8.js";
7
7
  import { d as subgraphModuleDocumentType, f as reducer$3, p as actions$3, r as utils$3 } from "./utils-Al_SGg2a.js";
8
8
  import { n as createSubgraphModuleDocument } from "./ph-factories-DhLtvC7j.js";
9
9
  import { documentModelDocumentModelModule } from "document-model";
@@ -29,7 +29,7 @@ var app_module_default = {
29
29
  "initialValue": ""
30
30
  },
31
31
  "global": {
32
- "schema": "\"\"\"\nConfiguration for a Drive App contributed by the package. Drive apps render a\ncustom view at the drive level (instead of, or alongside, the document file\ntree) and can opt into which document types they accept.\n\"\"\"\ntype AppModuleState {\n \"\"\"Display name of the drive app. Also used as the source for the generated folder name under `editors/`.\"\"\"\n name: String!\n \"\"\"Lifecycle status. While DRAFT the app definition is editable and codegen is skipped; switching to CONFIRMED triggers app scaffold generation.\"\"\"\n status: StatusType!\n \"\"\"Document type ids this app handles. `null` means the app accepts any document type; an empty list means it accepts none.\"\"\"\n allowedDocumentTypes: [String!]\n \"\"\"Whether the app surface accepts dropped files from the user. Defaults to true.\"\"\"\n isDragAndDropEnabled: Boolean!\n}\n\n\"\"\"\nLifecycle status of a module definition.\n- DRAFT: still being edited; codegen does not run.\n- CONFIRMED: locked in; codegen produces the corresponding scaffold.\n\"\"\"\nenum StatusType {\n DRAFT\n CONFIRMED\n}",
32
+ "schema": "\"\"\"\nConfiguration for a Drive App contributed by the package. Drive apps render a\ncustom view at the drive level (instead of, or alongside, the document file\ntree) and can opt into which document types they accept.\n\"\"\"\ntype AppModuleState {\n \"\"\"Display name of the drive app. Also used as the source for the generated folder name under `editors/`.\"\"\"\n name: String!\n \"\"\"Lifecycle status. While DRAFT the app definition is editable and codegen is skipped; switching to CONFIRMED triggers app scaffold generation.\"\"\"\n status: StatusType!\n \"\"\"Document type ids this app handles. `null` and an empty list both mean the app accepts every document type.\"\"\"\n allowedDocumentTypes: [String!]\n \"\"\"Whether the app surface accepts dropped files from the user. Defaults to true.\"\"\"\n isDragAndDropEnabled: Boolean!\n}\n\n\"\"\"\nLifecycle status of a module definition.\n- DRAFT: still being edited; codegen does not run.\n- CONFIRMED: locked in; codegen produces the corresponding scaffold.\n\"\"\"\nenum StatusType {\n DRAFT\n CONFIRMED\n}",
33
33
  "examples": [],
34
34
  "initialValue": "{\n \"name\": \"\",\n \"status\": \"DRAFT\",\n \"allowedDocumentTypes\": null,\n \"isDragAndDropEnabled\": true\n}"
35
35
  }
@@ -64,7 +64,7 @@ var app_module_default = {
64
64
  {
65
65
  "id": "7376f168-695f-4aef-94d0-6e381666358c",
66
66
  "name": "ADD_DOCUMENT_TYPE",
67
- "description": "Append a document type id to the list of types this app handles. Initializes the list if it was `null` (accept-any).",
67
+ "description": "Append a document type id to the list of types this app handles. The first type added narrows the app from every type to the listed ones.",
68
68
  "schema": "input AddDocumentTypeInput {\n documentType: String!\n}",
69
69
  "template": "",
70
70
  "reducer": "",
@@ -75,7 +75,7 @@ var app_module_default = {
75
75
  {
76
76
  "id": "310e4e5b-3f14-4e9a-8e09-5583c7698a65",
77
77
  "name": "REMOVE_DOCUMENT_TYPE",
78
- "description": "Remove a document type id from the handled list. No-op if the type is not present.",
78
+ "description": "Remove a document type id from the handled list. No-op if the type is not present. Removing the last type leaves an empty list, which accepts every type.",
79
79
  "schema": "input RemoveDocumentTypeInput {\n documentType: String!\n}",
80
80
  "template": "",
81
81
  "reducer": "",
@@ -86,7 +86,7 @@ var app_module_default = {
86
86
  {
87
87
  "id": "b365727a-7df3-48f0-a4f8-02362f02ad1d",
88
88
  "name": "SET_DOCUMENT_TYPES",
89
- "description": "Replace the entire allowed-document-types list in one call. Pass an empty list to accept none.",
89
+ "description": "Replace the entire allowed-document-types list in one call. An empty list accepts every document type.",
90
90
  "schema": "input SetDocumentTypesInput {\n documentTypes: [String!]!\n}",
91
91
  "template": "",
92
92
  "reducer": "",
@@ -213,7 +213,7 @@ var processor_module_default = {
213
213
  "initialValue": ""
214
214
  },
215
215
  "global": {
216
- "schema": "\"\"\"\nConfiguration for a processor contributed by the package. A processor receives\noperations from documents of matching types and runs server-side logic (e.g.\nbuilding a read model, indexing, syncing to an external system).\n\"\"\"\ntype ProcessorModuleState {\n \"\"\"Display name of the processor. Also determines the generated folder name under `processors/`.\"\"\"\n name: String!\n \"\"\"Processor implementation kind (e.g. 'read-model', 'relational-db'). Determines which scaffold codegen emits.\"\"\"\n type: String!\n \"\"\"Document types this processor subscribes to. Each entry has a stable id so it can be removed individually.\"\"\"\n documentTypes: [DocumentTypeItem!]!\n \"\"\"Lifecycle status. While DRAFT the processor definition is editable and codegen is skipped; switching to CONFIRMED triggers scaffold generation.\"\"\"\n status: StatusType!\n \"\"\"Drive-app names this processor is attached to. The processor runs in the context of each listed app.\"\"\"\n processorApps: [String!]!\n}\n\n\"\"\"A document type id (e.g. 'my-org/invoice') attached to the processor with a stable entry id.\"\"\"\ntype DocumentTypeItem {\n \"\"\"Stable identifier for the entry; used to remove it.\"\"\"\n id: OID!\n \"\"\"Document type id this processor subscribes to.\"\"\"\n documentType: String!\n}\n\n\"\"\"\nLifecycle status of a module definition.\n- DRAFT: still being edited; codegen does not run.\n- CONFIRMED: locked in; codegen produces the corresponding scaffold.\n\"\"\"\nenum StatusType {\n DRAFT\n CONFIRMED\n}",
216
+ "schema": "\"\"\"\nConfiguration for a processor contributed by the package. A processor receives\noperations from documents of matching types and runs server-side logic (e.g.\nbuilding a read model, indexing, syncing to an external system).\n\"\"\"\ntype ProcessorModuleState {\n \"\"\"Display name of the processor. Also determines the generated folder name under `processors/`.\"\"\"\n name: String!\n \"\"\"Processor implementation kind: `analytics` or `relational`. Determines which scaffold codegen emits; codegen generates nothing for any other value.\"\"\"\n type: String!\n \"\"\"Document types this processor subscribes to. Each entry has a stable id so it can be removed individually.\"\"\"\n documentTypes: [DocumentTypeItem!]!\n \"\"\"Lifecycle status. While DRAFT the processor definition is editable and codegen is skipped; switching to CONFIRMED triggers scaffold generation.\"\"\"\n status: StatusType!\n \"\"\"Drive-app names this processor is attached to. The processor runs in the context of each listed app.\"\"\"\n processorApps: [String!]!\n}\n\n\"\"\"A document type id (e.g. 'my-org/invoice') attached to the processor with a stable entry id.\"\"\"\ntype DocumentTypeItem {\n \"\"\"Stable identifier for the entry; used to remove it.\"\"\"\n id: OID!\n \"\"\"Document type id this processor subscribes to.\"\"\"\n documentType: String!\n}\n\n\"\"\"\nLifecycle status of a module definition.\n- DRAFT: still being edited; codegen does not run.\n- CONFIRMED: locked in; codegen produces the corresponding scaffold.\n\"\"\"\nenum StatusType {\n DRAFT\n CONFIRMED\n}",
217
217
  "examples": [],
218
218
  "initialValue": "{\n \"name\": \"\",\n \"type\": \"\",\n \"documentTypes\": [],\n \"status\": \"DRAFT\",\n \"processorApps\": []\n}"
219
219
  }
@@ -237,11 +237,17 @@ var processor_module_default = {
237
237
  {
238
238
  "id": "b8f28bb4-c6ae-40e6-86fa-29ef14ff8667",
239
239
  "name": "SET_PROCESSOR_TYPE",
240
- "description": "Set the processor implementation kind (e.g. 'read-model', 'relational-db'). Determines which scaffold codegen emits.",
240
+ "description": "Set the processor implementation kind: `analytics` or `relational`. Determines which scaffold codegen emits. Any other value is rejected with UnsupportedProcessorTypeError.",
241
241
  "schema": "input SetProcessorTypeInput {\n type: String!\n}",
242
242
  "template": "",
243
243
  "reducer": "",
244
- "errors": [],
244
+ "errors": [{
245
+ "id": "ac9b9586-e2d5-4676-8c06-22890adcc2fd",
246
+ "name": "UnsupportedProcessorTypeError",
247
+ "code": "UNSUPPORTED_PROCESSOR_TYPE",
248
+ "description": "The processor type is not `analytics` or `relational`, the kinds codegen can generate.",
249
+ "template": ""
250
+ }],
245
251
  "examples": [],
246
252
  "scope": "global"
247
253
  },
@@ -637,4 +643,4 @@ function pathSubdir(filePath) {
637
643
  //#endregion
638
644
  export { getDocument as a, getDocuments as c, getSpecEntry as d, listSpecDocumentTypes as f, stripLeadingDot as g, specPath as h, deleteDocument as i, validateActions as l, specDir as m, addActionsAndSave as n, getDocumentModelSchema as o, saveSpec as p, createDocument as r, getDocumentModels as s, addActions as t, SPECS_DIRNAME as u };
639
645
 
640
- //# sourceMappingURL=spec-api-B01RpZM-.js.map
646
+ //# sourceMappingURL=spec-api-BGj7gcQn.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spec-api-B01RpZM-.js","names":["documentEditorReducer","documentEditorUtils","documentEditorActions","documentEditorSpec","processorModuleReducer","processorModuleUtils","processorModuleActions","processorModuleSpec","subgraphModuleReducer","subgraphModuleUtils","subgraphModuleActions","subgraphModuleSpec","appModuleReducer","appModuleUtils","appModuleActions","appModuleSpec"],"sources":["../document-models/app-module/app-module.json","../document-models/document-editor/document-editor.json","../document-models/processor-module/processor-module.json","../document-models/subgraph-module/subgraph-module.json","../codegen/specs.ts","../codegen/spec-api.ts"],"sourcesContent":["","","","","import type {\n Action,\n DocumentModelGlobalState,\n PHDocument,\n Reducer,\n} from \"@powerhousedao/shared/document-model\";\nimport { kebabCase } from \"change-case\";\nimport { documentModelDocumentModelModule } from \"document-model\";\nimport { baseSaveToFile } from \"document-model/node\";\nimport { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/* Import from gen/ + actions.ts directly (not the top-level barrel) so we\n * don't pull in `hooks.ts`, which depends on `@powerhousedao/reactor-browser`\n * (a browser-only module that breaks Node-side spec tooling). */\nimport appModuleSpec from \"../document-models/app-module/app-module.json\" with { type: \"json\" };\nimport { actions as appModuleActions } from \"../document-models/app-module/v1/actions.js\";\nimport {\n appModuleDocumentType,\n createAppModuleDocument,\n reducer as appModuleReducer,\n utils as appModuleUtils,\n} from \"../document-models/app-module/v1/gen/index.js\";\nimport documentEditorSpec from \"../document-models/document-editor/document-editor.json\" with { type: \"json\" };\nimport { actions as documentEditorActions } from \"../document-models/document-editor/v1/actions.js\";\nimport {\n createDocumentEditorDocument,\n documentEditorDocumentType,\n reducer as documentEditorReducer,\n utils as documentEditorUtils,\n} from \"../document-models/document-editor/v1/gen/index.js\";\nimport processorModuleSpec from \"../document-models/processor-module/processor-module.json\" with { type: \"json\" };\nimport { actions as processorModuleActions } from \"../document-models/processor-module/v1/actions.js\";\nimport {\n createProcessorModuleDocument,\n processorModuleDocumentType,\n reducer as processorModuleReducer,\n utils as processorModuleUtils,\n} from \"../document-models/processor-module/v1/gen/index.js\";\nimport subgraphModuleSpec from \"../document-models/subgraph-module/subgraph-module.json\" with { type: \"json\" };\nimport { actions as subgraphModuleActions } from \"../document-models/subgraph-module/v1/actions.js\";\nimport {\n createSubgraphModuleDocument,\n subgraphModuleDocumentType,\n reducer as subgraphModuleReducer,\n utils as subgraphModuleUtils,\n} from \"../document-models/subgraph-module/v1/gen/index.js\";\n\nexport const SPECS_DIRNAME = \"specs\";\n\nconst documentModelDocumentType = \"powerhouse/document-model\";\n\ntype ActionsModule = Record<string, (input?: any) => Action>;\n\ntype SpecEntry = {\n documentType: string;\n subdir: string;\n reducer: Reducer<any>;\n utils: { fileExtension: string };\n actions: ActionsModule;\n createDocument: (state?: any) => PHDocument;\n jsonSpec: DocumentModelGlobalState;\n};\n\nconst SPECS: Record<string, SpecEntry> = {\n [documentModelDocumentType]: {\n documentType: documentModelDocumentType,\n subdir: \"document-models\",\n reducer: documentModelDocumentModelModule.reducer,\n utils: documentModelDocumentModelModule.utils,\n actions: documentModelDocumentModelModule.actions as ActionsModule,\n createDocument: documentModelDocumentModelModule.utils.createDocument,\n jsonSpec: documentModelDocumentModelModule.documentModel\n .global as DocumentModelGlobalState,\n },\n [documentEditorDocumentType]: {\n documentType: documentEditorDocumentType,\n subdir: \"editors\",\n reducer: documentEditorReducer as Reducer<any>,\n utils: documentEditorUtils,\n actions: documentEditorActions as unknown as ActionsModule,\n createDocument: createDocumentEditorDocument as (state?: any) => PHDocument,\n jsonSpec: documentEditorSpec as unknown as DocumentModelGlobalState,\n },\n [processorModuleDocumentType]: {\n documentType: processorModuleDocumentType,\n subdir: \"processors\",\n reducer: processorModuleReducer as Reducer<any>,\n utils: processorModuleUtils,\n actions: processorModuleActions as unknown as ActionsModule,\n createDocument: createProcessorModuleDocument as (\n state?: any,\n ) => PHDocument,\n jsonSpec: processorModuleSpec as unknown as DocumentModelGlobalState,\n },\n [subgraphModuleDocumentType]: {\n documentType: subgraphModuleDocumentType,\n subdir: \"subgraphs\",\n reducer: subgraphModuleReducer as Reducer<any>,\n utils: subgraphModuleUtils,\n actions: subgraphModuleActions as unknown as ActionsModule,\n createDocument: createSubgraphModuleDocument as (state?: any) => PHDocument,\n jsonSpec: subgraphModuleSpec as unknown as DocumentModelGlobalState,\n },\n [appModuleDocumentType]: {\n documentType: appModuleDocumentType,\n subdir: \"apps\",\n reducer: appModuleReducer as Reducer<any>,\n utils: appModuleUtils,\n actions: appModuleActions as unknown as ActionsModule,\n createDocument: createAppModuleDocument as (state?: any) => PHDocument,\n jsonSpec: appModuleSpec as unknown as DocumentModelGlobalState,\n },\n};\n\nexport function getSpecEntry(documentType: string): SpecEntry {\n const entry = SPECS[documentType];\n if (!entry) {\n throw new Error(`No spec handler registered for \"${documentType}\"`);\n }\n return entry;\n}\n\nexport function listSpecDocumentTypes(): string[] {\n return Object.keys(SPECS);\n}\n\n/** Returns the directory that holds specs for a given document type. */\nexport function specDir(projectDir: string, documentType: string): string {\n return join(projectDir, SPECS_DIRNAME, getSpecEntry(documentType).subdir);\n}\n\n/**\n * Deterministic path for a doc-type + display name.\n * Format: `<projectDir>/<specsDir>/<subdir>/<kebab-name>.<ext>.phd`.\n */\nexport function specPath(\n projectDir: string,\n documentType: string,\n name: string,\n): string {\n const entry = getSpecEntry(documentType);\n const baseName = kebabCase(name);\n const ext = stripLeadingDot(entry.utils.fileExtension);\n return join(specDir(projectDir, documentType), `${baseName}.${ext}.phd`);\n}\n\n/* baseSaveToFile expects the extension WITHOUT a leading dot (\"phdm\"), while the\n * document-model utils export it WITH one (\".phdm\"). Normalize so we can pass\n * either through. */\nexport function stripLeadingDot(ext: string): string {\n return ext.startsWith(\".\") ? ext.slice(1) : ext;\n}\n\n/** Saves a document into `<projectDir>/specs/<subdir>/<kebab-name>.<ext>.phd`. */\nexport async function saveSpec(\n doc: PHDocument,\n projectDir: string,\n): Promise<string> {\n const entry = getSpecEntry(doc.header.documentType);\n const dir = specDir(projectDir, doc.header.documentType);\n await mkdir(dir, { recursive: true });\n const name = kebabCase(doc.header.name || \"untitled\");\n return baseSaveToFile(\n doc,\n dir,\n stripLeadingDot(entry.utils.fileExtension),\n name,\n );\n}\n","/**\n * File-backed mirror of reactor-mcp's tool surface. Same function names and\n * input shapes — same agent code works whether it's targeting a live reactor\n * or a `specs/` folder on disk. The \"drive id\" is the project directory;\n * \"document id\" is the file path of the spec.\n *\n * See `packages/reactor-mcp/src/tools/reactor.ts` for the canonical schema.\n */\nimport type {\n Action,\n DocumentModelGlobalState,\n OperationSpecification,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { camelCase } from \"change-case\";\nimport { baseLoadFromFile } from \"document-model/node\";\nimport { readdir, rm, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n getSpecEntry,\n listSpecDocumentTypes,\n saveSpec,\n specDir,\n SPECS_DIRNAME,\n} from \"./specs.js\";\n\nexport type DocumentModelInfo = {\n name: string;\n type: string;\n description: string;\n extension: string;\n authorName: string;\n authorWebsite: string;\n};\n\n/** Mirrors reactor-mcp `getDocumentModels`. */\nexport function getDocumentModels(): DocumentModelInfo[] {\n return listSpecDocumentTypes().map((documentType) => {\n const { jsonSpec } = getSpecEntry(documentType);\n return {\n name: jsonSpec.name,\n type: jsonSpec.id,\n description: jsonSpec.description ?? \"\",\n extension: jsonSpec.extension ?? \"\",\n authorName: jsonSpec.author?.name ?? \"\",\n authorWebsite: jsonSpec.author?.website ?? \"\",\n };\n });\n}\n\n/** Mirrors reactor-mcp `getDocumentModelSchema`. Returns the full\n * `DocumentModelGlobalState` (schema + operations + errors), same payload\n * shape reactor-mcp serves. */\nexport function getDocumentModelSchema(\n documentType: string,\n): DocumentModelGlobalState {\n return getSpecEntry(documentType).jsonSpec;\n}\n\n/** Mirrors reactor-mcp `getDocument`. Path = file location on disk. */\nexport async function getDocument(path: string): Promise<PHDocument> {\n // We don't know the documentType ahead of time, so try each registered\n // reducer until one loads cleanly. baseLoadFromFile validates against the\n // reducer; the wrong reducer rejects. Try the path's parent directory first\n // as a fast hint (matches our `specs/<subdir>/` convention).\n const subdir = pathSubdir(path);\n const hint = subdir\n ? listSpecDocumentTypes().find((t) => getSpecEntry(t).subdir === subdir)\n : undefined;\n const order = hint\n ? [hint, ...listSpecDocumentTypes().filter((t) => t !== hint)]\n : listSpecDocumentTypes();\n\n let lastError: unknown;\n for (const documentType of order) {\n const { reducer } = getSpecEntry(documentType);\n try {\n return await baseLoadFromFile(path, reducer);\n } catch (err) {\n lastError = err;\n }\n }\n throw new Error(\n `Failed to load spec at \"${path}\": no registered reducer accepted it. Last error: ${String(lastError)}`,\n );\n}\n\n/** Mirrors reactor-mcp `getDocuments`. `parentId` is the project directory\n * containing `specs/`. */\nexport async function getDocuments(\n projectDir: string,\n opts: { documentType?: string } = {},\n): Promise<PHDocument[]> {\n const documentTypes = opts.documentType\n ? [opts.documentType]\n : listSpecDocumentTypes();\n\n const results: PHDocument[] = [];\n for (const documentType of documentTypes) {\n const dir = specDir(projectDir, documentType);\n const exists = await stat(dir).then(\n (s) => s.isDirectory(),\n () => false,\n );\n if (!exists) continue;\n const entries = await readdir(dir);\n for (const entry of entries) {\n if (!entry.endsWith(\".phd\")) continue;\n results.push(await getDocument(join(dir, entry)));\n }\n }\n return results;\n}\n\n/** Mirrors reactor-mcp `createDocument`. Returns an in-memory document; the\n * caller persists with `saveSpec`. */\nexport function createDocument(\n documentType: string,\n opts: {\n name?: string;\n initialState?: { global?: unknown; local?: unknown };\n } = {},\n): PHDocument {\n const entry = getSpecEntry(documentType);\n const doc = entry.createDocument(opts.initialState);\n if (opts.name) doc.header.name = opts.name;\n return doc;\n}\n\nexport type ActionInput = {\n type: string;\n input?: unknown;\n scope?: string;\n};\n\n/** Mirrors reactor-mcp `addActions`. Validates every action up front against\n * the document model's latest specification, then applies them in order via\n * the reducer. If any action is invalid, throws an aggregated error and\n * leaves `doc` untouched. */\nexport function addActions(\n doc: PHDocument,\n actions: ActionInput[],\n): PHDocument {\n const entry = getSpecEntry(doc.header.documentType);\n const built = validateAndBuildActions(entry, actions);\n let current = doc;\n for (let i = 0; i < built.length; i++) {\n const action = built[i];\n current = entry.reducer(current, action);\n /* The base reducer wraps custom reducers in try/catch and records any\n * throw as `operation.error` instead of propagating. For an atomic\n * batch apply that's the wrong shape — surface the error so callers\n * (and `saveSpec`) bail out before persisting a half-applied doc. */\n const scope = action.scope ?? \"global\";\n const ops = current.operations[scope];\n const last = ops?.[ops.length - 1];\n if (last?.error) {\n const failures: ActionValidationError[] = [\n {\n index: i,\n type: actions[i].type ?? \"<missing>\",\n errors: [`Reducer error: ${last.error}`],\n },\n ];\n throw formatValidationError(failures);\n }\n }\n return current;\n}\n\nexport type ActionValidationError = {\n /** Position in the input array. */\n index: number;\n /** The action's `type` field (or `<missing>` when not a string). */\n type: string;\n /** Human-readable reasons the action was rejected. */\n errors: string[];\n};\n\n/** Validate a list of actions without applying them. Returns one entry per\n * invalid action with all of its problems aggregated. Used by `addActions`\n * and exposed for callers that want a dry-run check. */\nexport function validateActions(\n documentType: string,\n actions: ActionInput[],\n): ActionValidationError[] {\n const entry = getSpecEntry(documentType);\n const failures: ActionValidationError[] = [];\n for (let i = 0; i < actions.length; i++) {\n const errors = collectActionErrors(entry, actions[i]);\n if (errors.length > 0) {\n failures.push({ index: i, type: actions[i].type ?? \"<missing>\", errors });\n }\n }\n return failures;\n}\n\n/** Run validateActions across the batch and, on success, materialize the\n * built Action objects. On any failure throws with every action's errors\n * aggregated — the caller never sees a partial apply. */\nfunction validateAndBuildActions(\n entry: ReturnType<typeof getSpecEntry>,\n actions: ActionInput[],\n): Action[] {\n const built: Action[] = [];\n const failures: ActionValidationError[] = [];\n for (let i = 0; i < actions.length; i++) {\n const item = actions[i];\n const errors = collectActionErrors(entry, item);\n if (errors.length > 0) {\n failures.push({ index: i, type: item.type ?? \"<missing>\", errors });\n continue;\n }\n built.push(buildAction(entry.actions, item));\n }\n if (failures.length > 0) throw formatValidationError(failures);\n return built;\n}\n\n/* Mirrors reactor-mcp's `validateDocumentModelAction`: confirms the operation\n * is declared in the latest spec, looks up the action creator, runs the\n * creator's own input validation, and checks scope. */\nfunction collectActionErrors(\n entry: ReturnType<typeof getSpecEntry>,\n item: ActionInput,\n): string[] {\n const errors: string[] = [];\n if (typeof item.type !== \"string\" || item.type.length === 0) {\n errors.push(\"Missing `type` field\");\n return errors;\n }\n const specs = entry.jsonSpec.specifications;\n if (!specs || specs.length === 0) {\n errors.push(\"Document model has no specifications\");\n return errors;\n }\n const latest = specs[specs.length - 1];\n let operation: OperationSpecification | undefined;\n for (const module of latest.modules ?? []) {\n const found = (module.operations ?? []).find((op) => op.name === item.type);\n if (found) {\n operation = found;\n break;\n }\n }\n if (!operation) {\n errors.push(\n `Operation \"${item.type}\" is not defined in any module of the document model`,\n );\n }\n const creatorName = camelCase(item.type);\n const creator = entry.actions[creatorName];\n if (!creator) {\n errors.push(`No action creator found.`);\n } else {\n try {\n creator(item.input);\n } catch (err) {\n errors.push(\n `Input validation error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n if (operation?.scope && item.scope && item.scope !== operation.scope) {\n errors.push(\n `Scope \"${item.scope}\" does not match operation scope \"${operation.scope}\"`,\n );\n }\n return errors;\n}\n\nfunction formatValidationError(failures: ActionValidationError[]): Error {\n const lines = failures.map(\n (f) => ` [${f.index}] ${f.type}: ${f.errors.join(\"; \")}`,\n );\n const header =\n failures.length === 1\n ? \"1 action failed validation:\"\n : `${failures.length} actions failed validation:`;\n const err = new Error([header, ...lines].join(\"\\n\")) as Error & {\n failures: ActionValidationError[];\n };\n err.failures = failures;\n return err;\n}\n\nfunction buildAction(\n actionsModule: Record<string, (input?: any) => Action>,\n item: ActionInput,\n): Action {\n const creatorName = camelCase(item.type);\n const creator = actionsModule[creatorName];\n if (!creator) {\n throw new Error(\n `No action creator found for \"${item.type}\" (looked up as \"${creatorName}\")`,\n );\n }\n const action = creator(item.input);\n // Caller may override the scope (creator picks a default).\n if (item.scope) action.scope = item.scope;\n return action;\n}\n\n/** Mirrors reactor-mcp `deleteDocument`. Removes the spec file from disk. */\nexport async function deleteDocument(\n path: string,\n): Promise<{ success: boolean }> {\n try {\n await rm(path);\n return { success: true };\n } catch {\n return { success: false };\n }\n}\n\n/* Convenience: persist after applying actions. Matches the typical agent\n * loop `getDocument → addActions → saveSpec` from the plan. */\nexport async function addActionsAndSave(\n path: string,\n projectDir: string,\n actions: ActionInput[],\n): Promise<{ doc: PHDocument; savedPath: string }> {\n const doc = await getDocument(path);\n const next = addActions(doc, actions);\n const savedPath = await saveSpec(next, projectDir);\n return { doc: next, savedPath };\n}\n\nfunction pathSubdir(filePath: string): string | undefined {\n const parts = filePath.split(/[/\\\\]/);\n const i = parts.lastIndexOf(SPECS_DIRNAME);\n if (i < 0 || i + 1 >= parts.length) return undefined;\n return parts[i + 1];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AIgDA,MAAa,gBAAgB;AAE7B,MAAM,4BAA4B;AAclC,MAAM,QAAmC;EACtC,4BAA4B;EAC3B,cAAc;EACd,QAAQ;EACR,SAAS,iCAAiC;EAC1C,OAAO,iCAAiC;EACxC,SAAS,iCAAiC;EAC1C,gBAAgB,iCAAiC,MAAM;EACvD,UAAU,iCAAiC,cACxC;CACL;EACC,6BAA6B;EAC5B,cAAc;EACd,QAAQ;EACR,SAASA;EACT,OAAOC;EACP,SAASC;EACT,gBAAgB;EAChB,UAAUC;CACZ;EACC,8BAA8B;EAC7B,cAAc;EACd,QAAQ;EACR,SAASC;EACT,OAAOC;EACP,SAASC;EACT,gBAAgB;EAGhB,UAAUC;CACZ;EACC,6BAA6B;EAC5B,cAAc;EACd,QAAQ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,KAAK,IAAI,EAAE,OAAO,KAAK,IAAI,GACxD;CACA,MAAM,SACJ,SAAS,WAAW,IAChB,gCACA,GAAG,SAAS,OAAO;CACzB,MAAM,MAAM,IAAI,MAAM,CAAC,QAAQ,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI,CAAC;CAGnD,IAAI,WAAW;CACf,OAAO;AACT;AAEA,SAAS,YACP,eACA,MACQ;CACR,MAAM,cAAc,UAAU,KAAK,IAAI;CACvC,MAAM,UAAU,cAAc;CAC9B,IAAI,CAAC,SACH,MAAM,IAAI,MACR,gCAAgC,KAAK,KAAK,mBAAmB,YAAY,GAC3E;CAEF,MAAM,SAAS,QAAQ,KAAK,KAAK;CAEjC,IAAI,KAAK,OAAO,OAAO,QAAQ,KAAK;CACpC,OAAO;AACT;;AAGA,eAAsB,eACpB,MAC+B;CAC/B,IAAI;EACF,MAAM,GAAG,IAAI;EACb,OAAO,EAAE,SAAS,KAAK;CACzB,QAAQ;EACN,OAAO,EAAE,SAAS,MAAM;CAC1B;AACF;AAIA,eAAsB,kBACpB,MACA,YACA,SACiD;CAEjD,MAAM,OAAO,WAAW,MADN,YAAY,IAAI,GACL,OAAO;CAEpC,OAAO;EAAE,KAAK;EAAM,WAAA,MADI,SAAS,MAAM,UAAU;CACnB;AAChC;AAEA,SAAS,WAAW,UAAsC;CACxD,MAAM,QAAQ,SAAS,MAAM,OAAO;CACpC,MAAM,IAAI,MAAM,YAAY,aAAa;CACzC,IAAI,IAAI,KAAK,IAAI,KAAK,MAAM,QAAQ,OAAO,KAAA;CAC3C,OAAO,MAAM,IAAI;AACnB"}
1
+ {"version":3,"file":"spec-api-BGj7gcQn.js","names":["documentEditorReducer","documentEditorUtils","documentEditorActions","documentEditorSpec","processorModuleReducer","processorModuleUtils","processorModuleActions","processorModuleSpec","subgraphModuleReducer","subgraphModuleUtils","subgraphModuleActions","subgraphModuleSpec","appModuleReducer","appModuleUtils","appModuleActions","appModuleSpec"],"sources":["../document-models/app-module/app-module.json","../document-models/document-editor/document-editor.json","../document-models/processor-module/processor-module.json","../document-models/subgraph-module/subgraph-module.json","../codegen/specs.ts","../codegen/spec-api.ts"],"sourcesContent":["","","","","import type {\n Action,\n DocumentModelGlobalState,\n PHDocument,\n Reducer,\n} from \"@powerhousedao/shared/document-model\";\nimport { kebabCase } from \"change-case\";\nimport { documentModelDocumentModelModule } from \"document-model\";\nimport { baseSaveToFile } from \"document-model/node\";\nimport { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/* Import from gen/ + actions.ts directly (not the top-level barrel) so we\n * don't pull in `hooks.ts`, which depends on `@powerhousedao/reactor-browser`\n * (a browser-only module that breaks Node-side spec tooling). */\nimport appModuleSpec from \"../document-models/app-module/app-module.json\" with { type: \"json\" };\nimport { actions as appModuleActions } from \"../document-models/app-module/v1/actions.js\";\nimport {\n appModuleDocumentType,\n createAppModuleDocument,\n reducer as appModuleReducer,\n utils as appModuleUtils,\n} from \"../document-models/app-module/v1/gen/index.js\";\nimport documentEditorSpec from \"../document-models/document-editor/document-editor.json\" with { type: \"json\" };\nimport { actions as documentEditorActions } from \"../document-models/document-editor/v1/actions.js\";\nimport {\n createDocumentEditorDocument,\n documentEditorDocumentType,\n reducer as documentEditorReducer,\n utils as documentEditorUtils,\n} from \"../document-models/document-editor/v1/gen/index.js\";\nimport processorModuleSpec from \"../document-models/processor-module/processor-module.json\" with { type: \"json\" };\nimport { actions as processorModuleActions } from \"../document-models/processor-module/v1/actions.js\";\nimport {\n createProcessorModuleDocument,\n processorModuleDocumentType,\n reducer as processorModuleReducer,\n utils as processorModuleUtils,\n} from \"../document-models/processor-module/v1/gen/index.js\";\nimport subgraphModuleSpec from \"../document-models/subgraph-module/subgraph-module.json\" with { type: \"json\" };\nimport { actions as subgraphModuleActions } from \"../document-models/subgraph-module/v1/actions.js\";\nimport {\n createSubgraphModuleDocument,\n subgraphModuleDocumentType,\n reducer as subgraphModuleReducer,\n utils as subgraphModuleUtils,\n} from \"../document-models/subgraph-module/v1/gen/index.js\";\n\nexport const SPECS_DIRNAME = \"specs\";\n\nconst documentModelDocumentType = \"powerhouse/document-model\";\n\ntype ActionsModule = Record<string, (input?: any) => Action>;\n\ntype SpecEntry = {\n documentType: string;\n subdir: string;\n reducer: Reducer<any>;\n utils: { fileExtension: string };\n actions: ActionsModule;\n createDocument: (state?: any) => PHDocument;\n jsonSpec: DocumentModelGlobalState;\n};\n\nconst SPECS: Record<string, SpecEntry> = {\n [documentModelDocumentType]: {\n documentType: documentModelDocumentType,\n subdir: \"document-models\",\n reducer: documentModelDocumentModelModule.reducer,\n utils: documentModelDocumentModelModule.utils,\n actions: documentModelDocumentModelModule.actions as ActionsModule,\n createDocument: documentModelDocumentModelModule.utils.createDocument,\n jsonSpec: documentModelDocumentModelModule.documentModel\n .global as DocumentModelGlobalState,\n },\n [documentEditorDocumentType]: {\n documentType: documentEditorDocumentType,\n subdir: \"editors\",\n reducer: documentEditorReducer as Reducer<any>,\n utils: documentEditorUtils,\n actions: documentEditorActions as unknown as ActionsModule,\n createDocument: createDocumentEditorDocument as (state?: any) => PHDocument,\n jsonSpec: documentEditorSpec as unknown as DocumentModelGlobalState,\n },\n [processorModuleDocumentType]: {\n documentType: processorModuleDocumentType,\n subdir: \"processors\",\n reducer: processorModuleReducer as Reducer<any>,\n utils: processorModuleUtils,\n actions: processorModuleActions as unknown as ActionsModule,\n createDocument: createProcessorModuleDocument as (\n state?: any,\n ) => PHDocument,\n jsonSpec: processorModuleSpec as unknown as DocumentModelGlobalState,\n },\n [subgraphModuleDocumentType]: {\n documentType: subgraphModuleDocumentType,\n subdir: \"subgraphs\",\n reducer: subgraphModuleReducer as Reducer<any>,\n utils: subgraphModuleUtils,\n actions: subgraphModuleActions as unknown as ActionsModule,\n createDocument: createSubgraphModuleDocument as (state?: any) => PHDocument,\n jsonSpec: subgraphModuleSpec as unknown as DocumentModelGlobalState,\n },\n [appModuleDocumentType]: {\n documentType: appModuleDocumentType,\n subdir: \"apps\",\n reducer: appModuleReducer as Reducer<any>,\n utils: appModuleUtils,\n actions: appModuleActions as unknown as ActionsModule,\n createDocument: createAppModuleDocument as (state?: any) => PHDocument,\n jsonSpec: appModuleSpec as unknown as DocumentModelGlobalState,\n },\n};\n\nexport function getSpecEntry(documentType: string): SpecEntry {\n const entry = SPECS[documentType];\n if (!entry) {\n throw new Error(`No spec handler registered for \"${documentType}\"`);\n }\n return entry;\n}\n\nexport function listSpecDocumentTypes(): string[] {\n return Object.keys(SPECS);\n}\n\n/** Returns the directory that holds specs for a given document type. */\nexport function specDir(projectDir: string, documentType: string): string {\n return join(projectDir, SPECS_DIRNAME, getSpecEntry(documentType).subdir);\n}\n\n/**\n * Deterministic path for a doc-type + display name.\n * Format: `<projectDir>/<specsDir>/<subdir>/<kebab-name>.<ext>.phd`.\n */\nexport function specPath(\n projectDir: string,\n documentType: string,\n name: string,\n): string {\n const entry = getSpecEntry(documentType);\n const baseName = kebabCase(name);\n const ext = stripLeadingDot(entry.utils.fileExtension);\n return join(specDir(projectDir, documentType), `${baseName}.${ext}.phd`);\n}\n\n/* baseSaveToFile expects the extension WITHOUT a leading dot (\"phdm\"), while the\n * document-model utils export it WITH one (\".phdm\"). Normalize so we can pass\n * either through. */\nexport function stripLeadingDot(ext: string): string {\n return ext.startsWith(\".\") ? ext.slice(1) : ext;\n}\n\n/** Saves a document into `<projectDir>/specs/<subdir>/<kebab-name>.<ext>.phd`. */\nexport async function saveSpec(\n doc: PHDocument,\n projectDir: string,\n): Promise<string> {\n const entry = getSpecEntry(doc.header.documentType);\n const dir = specDir(projectDir, doc.header.documentType);\n await mkdir(dir, { recursive: true });\n const name = kebabCase(doc.header.name || \"untitled\");\n return baseSaveToFile(\n doc,\n dir,\n stripLeadingDot(entry.utils.fileExtension),\n name,\n );\n}\n","/**\n * File-backed mirror of reactor-mcp's tool surface. Same function names and\n * input shapes — same agent code works whether it's targeting a live reactor\n * or a `specs/` folder on disk. The \"drive id\" is the project directory;\n * \"document id\" is the file path of the spec.\n *\n * See `packages/reactor-mcp/src/tools/reactor.ts` for the canonical schema.\n */\nimport type {\n Action,\n DocumentModelGlobalState,\n OperationSpecification,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { camelCase } from \"change-case\";\nimport { baseLoadFromFile } from \"document-model/node\";\nimport { readdir, rm, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n getSpecEntry,\n listSpecDocumentTypes,\n saveSpec,\n specDir,\n SPECS_DIRNAME,\n} from \"./specs.js\";\n\nexport type DocumentModelInfo = {\n name: string;\n type: string;\n description: string;\n extension: string;\n authorName: string;\n authorWebsite: string;\n};\n\n/** Mirrors reactor-mcp `getDocumentModels`. */\nexport function getDocumentModels(): DocumentModelInfo[] {\n return listSpecDocumentTypes().map((documentType) => {\n const { jsonSpec } = getSpecEntry(documentType);\n return {\n name: jsonSpec.name,\n type: jsonSpec.id,\n description: jsonSpec.description ?? \"\",\n extension: jsonSpec.extension ?? \"\",\n authorName: jsonSpec.author?.name ?? \"\",\n authorWebsite: jsonSpec.author?.website ?? \"\",\n };\n });\n}\n\n/** Mirrors reactor-mcp `getDocumentModelSchema`. Returns the full\n * `DocumentModelGlobalState` (schema + operations + errors), same payload\n * shape reactor-mcp serves. */\nexport function getDocumentModelSchema(\n documentType: string,\n): DocumentModelGlobalState {\n return getSpecEntry(documentType).jsonSpec;\n}\n\n/** Mirrors reactor-mcp `getDocument`. Path = file location on disk. */\nexport async function getDocument(path: string): Promise<PHDocument> {\n // We don't know the documentType ahead of time, so try each registered\n // reducer until one loads cleanly. baseLoadFromFile validates against the\n // reducer; the wrong reducer rejects. Try the path's parent directory first\n // as a fast hint (matches our `specs/<subdir>/` convention).\n const subdir = pathSubdir(path);\n const hint = subdir\n ? listSpecDocumentTypes().find((t) => getSpecEntry(t).subdir === subdir)\n : undefined;\n const order = hint\n ? [hint, ...listSpecDocumentTypes().filter((t) => t !== hint)]\n : listSpecDocumentTypes();\n\n let lastError: unknown;\n for (const documentType of order) {\n const { reducer } = getSpecEntry(documentType);\n try {\n return await baseLoadFromFile(path, reducer);\n } catch (err) {\n lastError = err;\n }\n }\n throw new Error(\n `Failed to load spec at \"${path}\": no registered reducer accepted it. Last error: ${String(lastError)}`,\n );\n}\n\n/** Mirrors reactor-mcp `getDocuments`. `parentId` is the project directory\n * containing `specs/`. */\nexport async function getDocuments(\n projectDir: string,\n opts: { documentType?: string } = {},\n): Promise<PHDocument[]> {\n const documentTypes = opts.documentType\n ? [opts.documentType]\n : listSpecDocumentTypes();\n\n const results: PHDocument[] = [];\n for (const documentType of documentTypes) {\n const dir = specDir(projectDir, documentType);\n const exists = await stat(dir).then(\n (s) => s.isDirectory(),\n () => false,\n );\n if (!exists) continue;\n const entries = await readdir(dir);\n for (const entry of entries) {\n if (!entry.endsWith(\".phd\")) continue;\n results.push(await getDocument(join(dir, entry)));\n }\n }\n return results;\n}\n\n/** Mirrors reactor-mcp `createDocument`. Returns an in-memory document; the\n * caller persists with `saveSpec`. */\nexport function createDocument(\n documentType: string,\n opts: {\n name?: string;\n initialState?: { global?: unknown; local?: unknown };\n } = {},\n): PHDocument {\n const entry = getSpecEntry(documentType);\n const doc = entry.createDocument(opts.initialState);\n if (opts.name) doc.header.name = opts.name;\n return doc;\n}\n\nexport type ActionInput = {\n type: string;\n input?: unknown;\n scope?: string;\n};\n\n/** Mirrors reactor-mcp `addActions`. Validates every action up front against\n * the document model's latest specification, then applies them in order via\n * the reducer. If any action is invalid, throws an aggregated error and\n * leaves `doc` untouched. */\nexport function addActions(\n doc: PHDocument,\n actions: ActionInput[],\n): PHDocument {\n const entry = getSpecEntry(doc.header.documentType);\n const built = validateAndBuildActions(entry, actions);\n let current = doc;\n for (let i = 0; i < built.length; i++) {\n const action = built[i];\n current = entry.reducer(current, action);\n /* The base reducer wraps custom reducers in try/catch and records any\n * throw as `operation.error` instead of propagating. For an atomic\n * batch apply that's the wrong shape — surface the error so callers\n * (and `saveSpec`) bail out before persisting a half-applied doc. */\n const scope = action.scope ?? \"global\";\n const ops = current.operations[scope];\n const last = ops?.[ops.length - 1];\n if (last?.error) {\n const failures: ActionValidationError[] = [\n {\n index: i,\n type: actions[i].type ?? \"<missing>\",\n errors: [`Reducer error: ${last.error}`],\n },\n ];\n throw formatValidationError(failures);\n }\n }\n return current;\n}\n\nexport type ActionValidationError = {\n /** Position in the input array. */\n index: number;\n /** The action's `type` field (or `<missing>` when not a string). */\n type: string;\n /** Human-readable reasons the action was rejected. */\n errors: string[];\n};\n\n/** Validate a list of actions without applying them. Returns one entry per\n * invalid action with all of its problems aggregated. Used by `addActions`\n * and exposed for callers that want a dry-run check. */\nexport function validateActions(\n documentType: string,\n actions: ActionInput[],\n): ActionValidationError[] {\n const entry = getSpecEntry(documentType);\n const failures: ActionValidationError[] = [];\n for (let i = 0; i < actions.length; i++) {\n const errors = collectActionErrors(entry, actions[i]);\n if (errors.length > 0) {\n failures.push({ index: i, type: actions[i].type ?? \"<missing>\", errors });\n }\n }\n return failures;\n}\n\n/** Run validateActions across the batch and, on success, materialize the\n * built Action objects. On any failure throws with every action's errors\n * aggregated — the caller never sees a partial apply. */\nfunction validateAndBuildActions(\n entry: ReturnType<typeof getSpecEntry>,\n actions: ActionInput[],\n): Action[] {\n const built: Action[] = [];\n const failures: ActionValidationError[] = [];\n for (let i = 0; i < actions.length; i++) {\n const item = actions[i];\n const errors = collectActionErrors(entry, item);\n if (errors.length > 0) {\n failures.push({ index: i, type: item.type ?? \"<missing>\", errors });\n continue;\n }\n built.push(buildAction(entry.actions, item));\n }\n if (failures.length > 0) throw formatValidationError(failures);\n return built;\n}\n\n/* Mirrors reactor-mcp's `validateDocumentModelAction`: confirms the operation\n * is declared in the latest spec, looks up the action creator, runs the\n * creator's own input validation, and checks scope. */\nfunction collectActionErrors(\n entry: ReturnType<typeof getSpecEntry>,\n item: ActionInput,\n): string[] {\n const errors: string[] = [];\n if (typeof item.type !== \"string\" || item.type.length === 0) {\n errors.push(\"Missing `type` field\");\n return errors;\n }\n const specs = entry.jsonSpec.specifications;\n if (!specs || specs.length === 0) {\n errors.push(\"Document model has no specifications\");\n return errors;\n }\n const latest = specs[specs.length - 1];\n let operation: OperationSpecification | undefined;\n for (const module of latest.modules ?? []) {\n const found = (module.operations ?? []).find((op) => op.name === item.type);\n if (found) {\n operation = found;\n break;\n }\n }\n if (!operation) {\n errors.push(\n `Operation \"${item.type}\" is not defined in any module of the document model`,\n );\n }\n const creatorName = camelCase(item.type);\n const creator = entry.actions[creatorName];\n if (!creator) {\n errors.push(`No action creator found.`);\n } else {\n try {\n creator(item.input);\n } catch (err) {\n errors.push(\n `Input validation error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n if (operation?.scope && item.scope && item.scope !== operation.scope) {\n errors.push(\n `Scope \"${item.scope}\" does not match operation scope \"${operation.scope}\"`,\n );\n }\n return errors;\n}\n\nfunction formatValidationError(failures: ActionValidationError[]): Error {\n const lines = failures.map(\n (f) => ` [${f.index}] ${f.type}: ${f.errors.join(\"; \")}`,\n );\n const header =\n failures.length === 1\n ? \"1 action failed validation:\"\n : `${failures.length} actions failed validation:`;\n const err = new Error([header, ...lines].join(\"\\n\")) as Error & {\n failures: ActionValidationError[];\n };\n err.failures = failures;\n return err;\n}\n\nfunction buildAction(\n actionsModule: Record<string, (input?: any) => Action>,\n item: ActionInput,\n): Action {\n const creatorName = camelCase(item.type);\n const creator = actionsModule[creatorName];\n if (!creator) {\n throw new Error(\n `No action creator found for \"${item.type}\" (looked up as \"${creatorName}\")`,\n );\n }\n const action = creator(item.input);\n // Caller may override the scope (creator picks a default).\n if (item.scope) action.scope = item.scope;\n return action;\n}\n\n/** Mirrors reactor-mcp `deleteDocument`. Removes the spec file from disk. */\nexport async function deleteDocument(\n path: string,\n): Promise<{ success: boolean }> {\n try {\n await rm(path);\n return { success: true };\n } catch {\n return { success: false };\n }\n}\n\n/* Convenience: persist after applying actions. Matches the typical agent\n * loop `getDocument → addActions → saveSpec` from the plan. */\nexport async function addActionsAndSave(\n path: string,\n projectDir: string,\n actions: ActionInput[],\n): Promise<{ doc: PHDocument; savedPath: string }> {\n const doc = await getDocument(path);\n const next = addActions(doc, actions);\n const savedPath = await saveSpec(next, projectDir);\n return { doc: next, savedPath };\n}\n\nfunction pathSubdir(filePath: string): string | undefined {\n const parts = filePath.split(/[/\\\\]/);\n const i = parts.lastIndexOf(SPECS_DIRNAME);\n if (i < 0 || i + 1 >= parts.length) return undefined;\n return parts[i + 1];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AIgDA,MAAa,gBAAgB;AAE7B,MAAM,4BAA4B;AAclC,MAAM,QAAmC;EACtC,4BAA4B;EAC3B,cAAc;EACd,QAAQ;EACR,SAAS,iCAAiC;EAC1C,OAAO,iCAAiC;EACxC,SAAS,iCAAiC;EAC1C,gBAAgB,iCAAiC,MAAM;EACvD,UAAU,iCAAiC,cACxC;CACL;EACC,6BAA6B;EAC5B,cAAc;EACd,QAAQ;EACR,SAASA;EACT,OAAOC;EACP,SAASC;EACT,gBAAgB;EAChB,UAAUC;CACZ;EACC,8BAA8B;EAC7B,cAAc;EACd,QAAQ;EACR,SAASC;EACT,OAAOC;EACP,SAASC;EACT,gBAAgB;EAGhB,UAAUC;CACZ;EACC,6BAA6B;EAC5B,cAAc;EACd,QAAQ;EACR,SAASC;EACT,OAAOC;EACP,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K,IAAI,GACxD;CACA,MAAM,SACJ,SAAS,WAAW,IAChB,gCACA,GAAG,SAAS,OAAO;CACzB,MAAM,MAAM,IAAI,MAAM,CAAC,QAAQ,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI,CAAC;CAGnD,IAAI,WAAW;CACf,OAAO;AACT;AAEA,SAAS,YACP,eACA,MACQ;CACR,MAAM,cAAc,UAAU,KAAK,IAAI;CACvC,MAAM,UAAU,cAAc;CAC9B,IAAI,CAAC,SACH,MAAM,IAAI,MACR,gCAAgC,KAAK,KAAK,mBAAmB,YAAY,GAC3E;CAEF,MAAM,SAAS,QAAQ,KAAK,KAAK;CAEjC,IAAI,KAAK,OAAO,OAAO,QAAQ,KAAK;CACpC,OAAO;AACT;;AAGA,eAAsB,eACpB,MAC+B;CAC/B,IAAI;EACF,MAAM,GAAG,IAAI;EACb,OAAO,EAAE,SAAS,KAAK;CACzB,QAAQ;EACN,OAAO,EAAE,SAAS,MAAM;CAC1B;AACF;AAIA,eAAsB,kBACpB,MACA,YACA,SACiD;CAEjD,MAAM,OAAO,WAAW,MADN,YAAY,IAAI,GACL,OAAO;CAEpC,OAAO;EAAE,KAAK;EAAM,WAAA,MADI,SAAS,MAAM,UAAU;CACnB;AAChC;AAEA,SAAS,WAAW,UAAsC;CACxD,MAAM,QAAQ,SAAS,MAAM,OAAO;CACpC,MAAM,IAAI,MAAM,YAAY,aAAa;CACzC,IAAI,IAAI,KAAK,IAAI,KAAK,MAAM,QAAQ,OAAO,KAAA;CAC3C,OAAO,MAAM,IAAI;AACnB"}
@@ -1,8 +1,8 @@
1
- import { t as codegenFactoryBuilder } from "./factory-BLQkEgxk.js";
1
+ import { t as codegenFactoryBuilder } from "./factory-BQp6QPQO.js";
2
2
  import { t as vetraReadModelFactoryBuilder } from "./factory-BUuO4fIN.js";
3
3
  //#region processors/switchboard.ts
4
4
  const processorFactoryBuilders = [vetraReadModelFactoryBuilder, codegenFactoryBuilder];
5
5
  //#endregion
6
6
  export { processorFactoryBuilders };
7
7
 
8
- //# sourceMappingURL=switchboard-CZ87bHRJ.js.map
8
+ //# sourceMappingURL=switchboard-DjCPLtMW.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard-CZ87bHRJ.js","names":[],"sources":["../processors/switchboard.ts"],"sourcesContent":["/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { ProcessorFactoryBuilder } from \"@powerhousedao/reactor-browser\";\nimport { codegenFactoryBuilder } from \"./codegen/factory.js\";\nimport { vetraReadModelFactoryBuilder } from \"./vetra-read-model/factory.js\";\n\nexport const processorFactoryBuilders: ProcessorFactoryBuilder[] = [\n vetraReadModelFactoryBuilder,\n codegenFactoryBuilder,\n];\n"],"mappings":";;;AAQA,MAAa,2BAAsD,CACjE,8BACA,qBACF"}
1
+ {"version":3,"file":"switchboard-DjCPLtMW.js","names":[],"sources":["../processors/switchboard.ts"],"sourcesContent":["/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { ProcessorFactoryBuilder } from \"@powerhousedao/reactor-browser\";\nimport { codegenFactoryBuilder } from \"./codegen/factory.js\";\nimport { vetraReadModelFactoryBuilder } from \"./vetra-read-model/factory.js\";\n\nexport const processorFactoryBuilders: ProcessorFactoryBuilder[] = [\n vetraReadModelFactoryBuilder,\n codegenFactoryBuilder,\n];\n"],"mappings":";;;AAQA,MAAa,2BAAsD,CACjE,8BACA,qBACF"}
@@ -82,6 +82,25 @@ const actions = {
82
82
  ...creators_exports
83
83
  };
84
84
  //#endregion
85
+ //#region document-models/processor-module/v1/gen/base-operations/error.ts
86
+ var UnsupportedProcessorTypeError = class extends Error {
87
+ errorCode = "UnsupportedProcessorTypeError";
88
+ constructor(message = "UnsupportedProcessorTypeError") {
89
+ super(message);
90
+ }
91
+ };
92
+ //#endregion
93
+ //#region document-models/processor-module/v1/src/utils.ts
94
+ var utils_exports = /* @__PURE__ */ __exportAll({
95
+ PROCESSOR_TYPES: () => PROCESSOR_TYPES,
96
+ isProcessorType: () => isProcessorType
97
+ });
98
+ /** The processor kinds Vetra's codegen can generate. */
99
+ const PROCESSOR_TYPES = ["analytics", "relational"];
100
+ function isProcessorType(type) {
101
+ return PROCESSOR_TYPES.includes(type);
102
+ }
103
+ //#endregion
85
104
  //#region document-models/processor-module/v1/src/reducers/base-operations.ts
86
105
  const processorModuleBaseOperationsOperations = {
87
106
  setProcessorNameOperation(state, action, _dispatch) {
@@ -92,6 +111,7 @@ const processorModuleBaseOperationsOperations = {
92
111
  setProcessorTypeOperation(state, action, _dispatch) {
93
112
  const trimmedType = action.input.type.trim();
94
113
  if (trimmedType === "") throw new Error("Processor type cannot be empty");
114
+ if (!isProcessorType(trimmedType)) throw new UnsupportedProcessorTypeError(`UnsupportedProcessorTypeError: "${trimmedType}" is not a processor type. Use one of: ${PROCESSOR_TYPES.join(", ")}.`);
95
115
  state.type = trimmedType;
96
116
  },
97
117
  addDocumentTypeOperation(state, action, _dispatch) {
@@ -240,6 +260,6 @@ const utils = {
240
260
  }
241
261
  };
242
262
  //#endregion
243
- export { SetProcessorTypeInputSchema as A, AddProcessorAppInputSchema as C, RemoveProcessorAppInputSchema as D, RemoveDocumentTypeInputSchema as E, definedNonNullAnySchema as M, isDefinedNonNullAny as N, SetProcessorNameInputSchema as O, AddDocumentTypeInputSchema as S, ProcessorModuleStateSchema as T, removeDocumentType as _, ProcessorModuleDocumentSchema as a, setProcessorStatus as b, assertIsProcessorModuleState as c, processorModuleDocumentType as d, reducer as f, creators_exports as g, addProcessorApp as h, ProcessorModuleDocumentHeaderSchema as i, StatusTypeSchema as j, SetProcessorStatusInputSchema as k, isProcessorModuleDocument as l, addDocumentType as m, initialLocalState as n, ProcessorModulePHStateSchema as o, actions as p, utils as r, assertIsProcessorModuleDocument as s, initialGlobalState as t, isProcessorModuleState as u, removeProcessorApp as v, DocumentTypeItemSchema as w, setProcessorType as x, setProcessorName as y };
263
+ export { RemoveProcessorAppInputSchema as A, setProcessorStatus as C, DocumentTypeItemSchema as D, AddProcessorAppInputSchema as E, definedNonNullAnySchema as F, isDefinedNonNullAny as I, SetProcessorStatusInputSchema as M, SetProcessorTypeInputSchema as N, ProcessorModuleStateSchema as O, StatusTypeSchema as P, setProcessorName as S, AddDocumentTypeInputSchema as T, addDocumentType as _, ProcessorModuleDocumentSchema as a, removeDocumentType as b, assertIsProcessorModuleState as c, processorModuleDocumentType as d, reducer as f, actions as g, utils_exports as h, ProcessorModuleDocumentHeaderSchema as i, SetProcessorNameInputSchema as j, RemoveDocumentTypeInputSchema as k, isProcessorModuleDocument as l, isProcessorType as m, initialLocalState as n, ProcessorModulePHStateSchema as o, PROCESSOR_TYPES as p, utils as r, assertIsProcessorModuleDocument as s, initialGlobalState as t, isProcessorModuleState as u, addProcessorApp as v, setProcessorType as w, removeProcessorApp as x, creators_exports as y };
244
264
 
245
- //# sourceMappingURL=utils-w_21RRK6.js.map
265
+ //# sourceMappingURL=utils-BJk4_43W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-BJk4_43W.js","names":["z","processorModuleBaseOperationsActions"],"sources":["../document-models/processor-module/v1/gen/schema/zod.ts","../document-models/processor-module/v1/gen/base-operations/creators.ts","../document-models/processor-module/v1/actions.ts","../document-models/processor-module/v1/gen/base-operations/error.ts","../document-models/processor-module/v1/src/utils.ts","../document-models/processor-module/v1/src/reducers/base-operations.ts","../document-models/processor-module/v1/gen/reducer.ts","../document-models/processor-module/v1/gen/document-type.ts","../document-models/processor-module/v1/gen/document-schema.ts","../document-models/processor-module/v1/gen/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-empty-object-type */\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport * as z from \"zod\";\nimport type {\n AddDocumentTypeInput,\n AddProcessorAppInput,\n DocumentTypeItem,\n ProcessorModuleState,\n RemoveDocumentTypeInput,\n RemoveProcessorAppInput,\n SetProcessorNameInput,\n SetProcessorStatusInput,\n SetProcessorTypeInput,\n StatusType,\n} from \"./types.js\";\n\ntype Properties<T> = Required<{\n [K in keyof T]: z.ZodType<T[K]>;\n}>;\n\ntype definedNonNullAny = {};\n\nexport const isDefinedNonNullAny = (v: any): v is definedNonNullAny =>\n v !== undefined && v !== null;\n\nexport const definedNonNullAnySchema = z\n .any()\n .refine((v) => isDefinedNonNullAny(v));\n\nexport const StatusTypeSchema = z.enum([\"CONFIRMED\", \"DRAFT\"]);\n\nexport function AddDocumentTypeInputSchema(): z.ZodObject<\n Properties<AddDocumentTypeInput>\n> {\n return z.object({\n documentType: z.string(),\n id: z.string(),\n });\n}\n\nexport function AddProcessorAppInputSchema(): z.ZodObject<\n Properties<AddProcessorAppInput>\n> {\n return z.object({\n processorApp: z.string(),\n });\n}\n\nexport function DocumentTypeItemSchema(): z.ZodObject<\n Properties<DocumentTypeItem>\n> {\n return z.object({\n __typename: z.literal(\"DocumentTypeItem\").optional(),\n documentType: z.string(),\n id: z.string(),\n });\n}\n\nexport function ProcessorModuleStateSchema(): z.ZodObject<\n Properties<ProcessorModuleState>\n> {\n return z.object({\n __typename: z.literal(\"ProcessorModuleState\").optional(),\n documentTypes: z.array(z.lazy(() => DocumentTypeItemSchema())),\n name: z.string(),\n processorApps: z.array(z.string()),\n status: StatusTypeSchema,\n type: z.string(),\n });\n}\n\nexport function RemoveDocumentTypeInputSchema(): z.ZodObject<\n Properties<RemoveDocumentTypeInput>\n> {\n return z.object({\n id: z.string(),\n });\n}\n\nexport function RemoveProcessorAppInputSchema(): z.ZodObject<\n Properties<RemoveProcessorAppInput>\n> {\n return z.object({\n processorApp: z.string(),\n });\n}\n\nexport function SetProcessorNameInputSchema(): z.ZodObject<\n Properties<SetProcessorNameInput>\n> {\n return z.object({\n name: z.string(),\n });\n}\n\nexport function SetProcessorStatusInputSchema(): z.ZodObject<\n Properties<SetProcessorStatusInput>\n> {\n return z.object({\n status: StatusTypeSchema,\n });\n}\n\nexport function SetProcessorTypeInputSchema(): z.ZodObject<\n Properties<SetProcessorTypeInput>\n> {\n return z.object({\n type: z.string(),\n });\n}\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport { createAction } from \"document-model\";\nimport {\n AddDocumentTypeInputSchema,\n AddProcessorAppInputSchema,\n RemoveDocumentTypeInputSchema,\n RemoveProcessorAppInputSchema,\n SetProcessorNameInputSchema,\n SetProcessorStatusInputSchema,\n SetProcessorTypeInputSchema,\n} from \"../schema/zod.js\";\nimport type {\n AddDocumentTypeInput,\n AddProcessorAppInput,\n RemoveDocumentTypeInput,\n RemoveProcessorAppInput,\n SetProcessorNameInput,\n SetProcessorStatusInput,\n SetProcessorTypeInput,\n} from \"../types.js\";\nimport type {\n AddDocumentTypeAction,\n AddProcessorAppAction,\n RemoveDocumentTypeAction,\n RemoveProcessorAppAction,\n SetProcessorNameAction,\n SetProcessorStatusAction,\n SetProcessorTypeAction,\n} from \"./actions.js\";\n\nexport const setProcessorName = (input: SetProcessorNameInput) =>\n createAction<SetProcessorNameAction>(\n \"SET_PROCESSOR_NAME\",\n { ...input },\n undefined,\n SetProcessorNameInputSchema,\n \"global\",\n );\n\nexport const setProcessorType = (input: SetProcessorTypeInput) =>\n createAction<SetProcessorTypeAction>(\n \"SET_PROCESSOR_TYPE\",\n { ...input },\n undefined,\n SetProcessorTypeInputSchema,\n \"global\",\n );\n\nexport const addDocumentType = (input: AddDocumentTypeInput) =>\n createAction<AddDocumentTypeAction>(\n \"ADD_DOCUMENT_TYPE\",\n { ...input },\n undefined,\n AddDocumentTypeInputSchema,\n \"global\",\n );\n\nexport const removeDocumentType = (input: RemoveDocumentTypeInput) =>\n createAction<RemoveDocumentTypeAction>(\n \"REMOVE_DOCUMENT_TYPE\",\n { ...input },\n undefined,\n RemoveDocumentTypeInputSchema,\n \"global\",\n );\n\nexport const addProcessorApp = (input: AddProcessorAppInput) =>\n createAction<AddProcessorAppAction>(\n \"ADD_PROCESSOR_APP\",\n { ...input },\n undefined,\n AddProcessorAppInputSchema,\n \"global\",\n );\n\nexport const removeProcessorApp = (input: RemoveProcessorAppInput) =>\n createAction<RemoveProcessorAppAction>(\n \"REMOVE_PROCESSOR_APP\",\n { ...input },\n undefined,\n RemoveProcessorAppInputSchema,\n \"global\",\n );\n\nexport const setProcessorStatus = (input: SetProcessorStatusInput) =>\n createAction<SetProcessorStatusAction>(\n \"SET_PROCESSOR_STATUS\",\n { ...input },\n undefined,\n SetProcessorStatusInputSchema,\n \"global\",\n );\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport { baseActions } from \"document-model\";\nimport { processorModuleBaseOperationsActions } from \"./gen/creators.js\";\n\n/** Actions for the ProcessorModule document model */\n\nexport const actions = {\n ...baseActions,\n ...processorModuleBaseOperationsActions,\n};\n","export type ErrorCode = \"UnsupportedProcessorTypeError\";\n\nexport interface ReducerError {\n errorCode: ErrorCode;\n}\n\nexport class UnsupportedProcessorTypeError\n extends Error\n implements ReducerError\n{\n errorCode = \"UnsupportedProcessorTypeError\" as ErrorCode;\n constructor(message = \"UnsupportedProcessorTypeError\") {\n super(message);\n }\n}\n\nexport const errors = {\n SetProcessorType: { UnsupportedProcessorTypeError },\n};\n","/** The processor kinds Vetra's codegen can generate. */\nexport const PROCESSOR_TYPES = [\"analytics\", \"relational\"] as const;\nexport type ProcessorType = (typeof PROCESSOR_TYPES)[number];\n\nexport function isProcessorType(type: string): type is ProcessorType {\n return (PROCESSOR_TYPES as readonly string[]).includes(type);\n}\n","import {\n PROCESSOR_APPS,\n type ProcessorApp,\n} from \"@powerhousedao/shared/processors\";\nimport type { ProcessorModuleBaseOperationsOperations } from \"document-models/processor-module/v1\";\nimport { UnsupportedProcessorTypeError } from \"../../gen/base-operations/error.js\";\nimport { isProcessorType, PROCESSOR_TYPES } from \"../utils.js\";\n\nexport const processorModuleBaseOperationsOperations: ProcessorModuleBaseOperationsOperations =\n {\n setProcessorNameOperation(state, action, _dispatch) {\n const trimmedName = action.input.name.trim();\n if (trimmedName === \"\") {\n throw new Error(\"Processor name cannot be empty\");\n }\n state.name = trimmedName;\n },\n setProcessorTypeOperation(state, action, _dispatch) {\n const trimmedType = action.input.type.trim();\n if (trimmedType === \"\") {\n throw new Error(\"Processor type cannot be empty\");\n }\n if (!isProcessorType(trimmedType)) {\n throw new UnsupportedProcessorTypeError(\n `UnsupportedProcessorTypeError: \"${trimmedType}\" is not a processor type. Use one of: ${PROCESSOR_TYPES.join(\", \")}.`,\n );\n }\n state.type = trimmedType;\n },\n addDocumentTypeOperation(state, action, _dispatch) {\n // Check for duplicate ID\n const existingId = state.documentTypes.find(\n (dt) => dt.id === action.input.id,\n );\n if (existingId) {\n throw new Error(\n `Document type with id \"${action.input.id}\" already exists`,\n );\n }\n\n state.documentTypes.push({\n id: action.input.id,\n documentType: action.input.documentType,\n });\n },\n removeDocumentTypeOperation(state, action, _dispatch) {\n state.documentTypes = state.documentTypes.filter(\n (documentType) => documentType.id !== action.input.id,\n );\n },\n setProcessorStatusOperation(state, action, _dispatch) {\n state.status = action.input.status;\n },\n addProcessorAppOperation(state, action) {\n const { processorApp } = action.input;\n if (!PROCESSOR_APPS.includes(processorApp as ProcessorApp)) {\n throw new Error(\n `${processorApp} is not a valid processor app. Must be one of ${PROCESSOR_APPS.join(\", \")}.`,\n );\n }\n state.processorApps = [\n ...new Set([...state.processorApps, processorApp]),\n ];\n },\n removeProcessorAppOperation(state, action) {\n const { processorApp } = action.input;\n state.processorApps = state.processorApps.filter(\n (p) => p !== processorApp,\n );\n },\n };\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-unsafe-argument */\nimport type { Reducer, StateReducer } from \"document-model\";\nimport { createReducer, isDocumentAction } from \"document-model\";\nimport type { ProcessorModulePHState } from \"document-models/processor-module/v1\";\n\nimport { processorModuleBaseOperationsOperations } from \"../src/reducers/base-operations.js\";\n\nimport {\n AddDocumentTypeInputSchema,\n AddProcessorAppInputSchema,\n RemoveDocumentTypeInputSchema,\n RemoveProcessorAppInputSchema,\n SetProcessorNameInputSchema,\n SetProcessorStatusInputSchema,\n SetProcessorTypeInputSchema,\n} from \"./schema/zod.js\";\n\nconst stateReducer: StateReducer<ProcessorModulePHState> = (\n state,\n action,\n dispatch,\n) => {\n if (isDocumentAction(action)) {\n return state;\n }\n switch (action.type) {\n case \"SET_PROCESSOR_NAME\": {\n SetProcessorNameInputSchema().parse(action.input);\n\n processorModuleBaseOperationsOperations.setProcessorNameOperation(\n (state as any)[action.scope],\n action as any,\n dispatch,\n );\n\n break;\n }\n\n case \"SET_PROCESSOR_TYPE\": {\n SetProcessorTypeInputSchema().parse(action.input);\n\n processorModuleBaseOperationsOperations.setProcessorTypeOperation(\n (state as any)[action.scope],\n action as any,\n dispatch,\n );\n\n break;\n }\n\n case \"ADD_DOCUMENT_TYPE\": {\n AddDocumentTypeInputSchema().parse(action.input);\n\n processorModuleBaseOperationsOperations.addDocumentTypeOperation(\n (state as any)[action.scope],\n action as any,\n dispatch,\n );\n\n break;\n }\n\n case \"REMOVE_DOCUMENT_TYPE\": {\n RemoveDocumentTypeInputSchema().parse(action.input);\n\n processorModuleBaseOperationsOperations.removeDocumentTypeOperation(\n (state as any)[action.scope],\n action as any,\n dispatch,\n );\n\n break;\n }\n\n case \"ADD_PROCESSOR_APP\": {\n AddProcessorAppInputSchema().parse(action.input);\n\n processorModuleBaseOperationsOperations.addProcessorAppOperation(\n (state as any)[action.scope],\n action as any,\n dispatch,\n );\n\n break;\n }\n\n case \"REMOVE_PROCESSOR_APP\": {\n RemoveProcessorAppInputSchema().parse(action.input);\n\n processorModuleBaseOperationsOperations.removeProcessorAppOperation(\n (state as any)[action.scope],\n action as any,\n dispatch,\n );\n\n break;\n }\n\n case \"SET_PROCESSOR_STATUS\": {\n SetProcessorStatusInputSchema().parse(action.input);\n\n processorModuleBaseOperationsOperations.setProcessorStatusOperation(\n (state as any)[action.scope],\n action as any,\n dispatch,\n );\n\n break;\n }\n\n default:\n return state;\n }\n};\n\nexport const reducer: Reducer<ProcessorModulePHState> =\n createReducer(stateReducer);\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nexport const processorModuleDocumentType = \"powerhouse/processor\";\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport {\n BaseDocumentHeaderSchema,\n BaseDocumentStateSchema,\n} from \"document-model\";\nimport { z } from \"zod\";\nimport { processorModuleDocumentType } from \"./document-type.js\";\nimport { ProcessorModuleStateSchema } from \"./schema/zod.js\";\nimport type {\n ProcessorModuleDocument,\n ProcessorModulePHState,\n} from \"./types.js\";\n\n/** Schema for validating the header object of a ProcessorModule document */\nexport const ProcessorModuleDocumentHeaderSchema =\n BaseDocumentHeaderSchema.extend({\n documentType: z.literal(processorModuleDocumentType),\n });\n\n/** Schema for validating the state object of a ProcessorModule document */\nexport const ProcessorModulePHStateSchema = BaseDocumentStateSchema.extend({\n global: ProcessorModuleStateSchema(),\n});\n\nexport const ProcessorModuleDocumentSchema = z.object({\n header: ProcessorModuleDocumentHeaderSchema,\n state: ProcessorModulePHStateSchema,\n initialState: ProcessorModulePHStateSchema,\n});\n\n/** Simple helper function to check if a state object is a ProcessorModule document state object */\nexport function isProcessorModuleState(\n state: unknown,\n): state is ProcessorModulePHState {\n return ProcessorModulePHStateSchema.safeParse(state).success;\n}\n\n/** Simple helper function to assert that a document state object is a ProcessorModule document state object */\nexport function assertIsProcessorModuleState(\n state: unknown,\n): asserts state is ProcessorModulePHState {\n ProcessorModulePHStateSchema.parse(state);\n}\n\n/** Simple helper function to check if a document is a ProcessorModule document */\nexport function isProcessorModuleDocument(\n document: unknown,\n): document is ProcessorModuleDocument {\n return ProcessorModuleDocumentSchema.safeParse(document).success;\n}\n\n/** Simple helper function to assert that a document is a ProcessorModule document */\nexport function assertIsProcessorModuleDocument(\n document: unknown,\n): asserts document is ProcessorModuleDocument {\n ProcessorModuleDocumentSchema.parse(document);\n}\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { DocumentModelUtils } from \"document-model\";\nimport {\n baseCreateDocument,\n baseLoadFromInput,\n baseSaveToFileHandle,\n defaultBaseState,\n} from \"document-model\";\nimport {\n assertIsProcessorModuleDocument,\n assertIsProcessorModuleState,\n isProcessorModuleDocument,\n isProcessorModuleState,\n} from \"./document-schema.js\";\nimport { processorModuleDocumentType } from \"./document-type.js\";\nimport { reducer } from \"./reducer.js\";\nimport type {\n ProcessorModuleGlobalState,\n ProcessorModuleLocalState,\n ProcessorModulePHState,\n} from \"./types.js\";\n\nexport const initialGlobalState: ProcessorModuleGlobalState = {\n name: \"\",\n type: \"\",\n documentTypes: [],\n status: \"DRAFT\",\n processorApps: [],\n};\nexport const initialLocalState: ProcessorModuleLocalState = {};\n\nexport const utils: DocumentModelUtils<ProcessorModulePHState> = {\n fileExtension: \".processor\",\n createState(state) {\n return {\n ...defaultBaseState(),\n global: { ...initialGlobalState, ...state?.global },\n local: { ...initialLocalState, ...state?.local },\n };\n },\n createDocument(state) {\n return baseCreateDocument(\n utils.createState,\n state,\n processorModuleDocumentType,\n );\n },\n saveToFileHandle(document, input) {\n return baseSaveToFileHandle(document, input);\n },\n loadFromInput(input) {\n return baseLoadFromInput(input, reducer);\n },\n isStateOfType(state) {\n return isProcessorModuleState(state);\n },\n assertIsStateOfType(state) {\n return assertIsProcessorModuleState(state);\n },\n isDocumentOfType(document) {\n return isProcessorModuleDocument(document);\n },\n assertIsDocumentOfType(document) {\n return assertIsProcessorModuleDocument(document);\n },\n};\n"],"mappings":";;;;;;AAsBA,MAAa,uBAAuB,MAClC,MAAM,KAAA,KAAa,MAAM;AAE3B,MAAa,0BAA0BA,IACpC,IAAI,CAAC,CACL,QAAQ,MAAM,oBAAoB,CAAC,CAAC;AAEvC,MAAa,mBAAmBA,IAAE,KAAK,CAAC,aAAa,OAAO,CAAC;AAE7D,SAAgB,6BAEd;CACA,OAAOA,IAAE,OAAO;EACd,cAAcA,IAAE,OAAO;EACvB,IAAIA,IAAE,OAAO;CACf,CAAC;AACH;A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,iBAAiB,UAAU,OAAO;EAChC,OAAO,qBAAqB,UAAU,KAAK;CAC7C;CACA,cAAc,OAAO;EACnB,OAAO,kBAAkB,OAAO,OAAO;CACzC;CACA,cAAc,OAAO;EACnB,OAAO,uBAAuB,KAAK;CACrC;CACA,oBAAoB,OAAO;EACzB,OAAO,6BAA6B,KAAK;CAC3C;CACA,iBAAiB,UAAU;EACzB,OAAO,0BAA0B,QAAQ;CAC3C;CACA,uBAAuB,UAAU;EAC/B,OAAO,gCAAgC,QAAQ;CACjD;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/vetra",
3
- "version": "6.2.3-dev.77",
3
+ "version": "6.2.3-dev.79",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -61,21 +61,21 @@
61
61
  "./package.json": "./package.json"
62
62
  },
63
63
  "dependencies": {
64
- "@powerhousedao/codegen": "6.2.3-dev.77",
65
- "@powerhousedao/config": "6.2.3-dev.77",
66
- "@powerhousedao/design-system": "6.2.3-dev.77",
67
- "@powerhousedao/reactor-api": "6.2.3-dev.77",
68
- "@powerhousedao/reactor-browser": "6.2.3-dev.77",
69
- "@powerhousedao/shared": "6.2.3-dev.77",
64
+ "@powerhousedao/codegen": "6.2.3-dev.79",
65
+ "@powerhousedao/config": "6.2.3-dev.79",
66
+ "@powerhousedao/design-system": "6.2.3-dev.79",
67
+ "@powerhousedao/reactor-api": "6.2.3-dev.79",
68
+ "@powerhousedao/reactor-browser": "6.2.3-dev.79",
69
+ "@powerhousedao/shared": "6.2.3-dev.79",
70
70
  "change-case": "5.4.4",
71
- "document-model": "6.2.3-dev.77",
71
+ "document-model": "6.2.3-dev.79",
72
72
  "graphql": "^16",
73
73
  "react": "19.2.6",
74
74
  "zod": "^4.5.4",
75
75
  "tailwind-merge": "3.4.0"
76
76
  },
77
77
  "devDependencies": {
78
- "@powerhousedao/builder-tools": "6.2.3-dev.77",
78
+ "@powerhousedao/builder-tools": "6.2.3-dev.79",
79
79
  "@tailwindcss/cli": "4.2.2",
80
80
  "@testing-library/jest-dom": "^6.9.1",
81
81
  "@testing-library/react": "^16.3.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"factory-BLQkEgxk.js","names":[],"sources":["../processors/codegen/factory.ts"],"sourcesContent":["import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type {\n IProcessorHostModule,\n ProcessorFactoryBuilder,\n ProcessorRecord,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PHDocumentHeader } from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"./logger.js\";\n\n/**\n * Determines if a drive header matches the Vetra drive criteria.\n * @param driveHeader - The drive header to check\n * @param explicitDriveId - Optional explicit drive ID from config (if set, uses exact match)\n * @returns true if the drive is a Vetra drive, false otherwise\n */\nfunction isDriveVetra(\n driveHeader: PHDocumentHeader,\n driveIdFromConfig?: string,\n): boolean {\n // If explicit drive ID is configured, use exact match\n if (driveIdFromConfig) {\n return (\n driveHeader.slug === driveIdFromConfig ||\n driveHeader.id === driveIdFromConfig\n );\n }\n\n // Otherwise, check if slug/id matches Vetra pattern\n // Matches \"vetra\" exactly or IDs starting with \"vetra-\" (case-insensitive)\n const matchesPattern = (identifier: string): boolean => {\n const lower = identifier.toLowerCase();\n return lower === \"vetra\" || lower.startsWith(\"vetra-\");\n };\n\n return matchesPattern(driveHeader.slug) || matchesPattern(driveHeader.id);\n}\n\nexport const codegenFactoryBuilder: ProcessorFactoryBuilder = (\n module: IProcessorHostModule,\n) => {\n return async (driveHeader: PHDocumentHeader): Promise<ProcessorRecord[]> => {\n const processorsConfig = module.config ?? new Map<string, unknown>();\n const vetraConfig = processorsConfig.get(VETRA_PROCESSOR_CONFIG_KEY) as\n | VetraProcessorConfigType\n | undefined;\n\n // Exit early if it's not a vetra drive\n if (!isDriveVetra(driveHeader, vetraConfig?.driveId)) {\n logger.debug(\n `Drive ${driveHeader.slug} is not a Vetra drive, skipping codegen processor`,\n );\n return [];\n }\n\n logger.info(\n `Drive ${driveHeader.slug} is a Vetra drive, using codegen processor`,\n );\n\n // Lazy-load codegen only once a Vetra drive is confirmed.\n const [{ buildTsMorphProject }, { getConfig }, { CodegenProcessor }] =\n await Promise.all([\n import(\"@powerhousedao/codegen/utils\"),\n import(\"@powerhousedao/config/node\"),\n import(\"./processor.js\"),\n ]);\n\n const config = getConfig();\n const cwd = process.cwd();\n\n /* Use one instance of ts-morph project, which handles race conditions */\n const project = buildTsMorphProject(cwd);\n const processor = new CodegenProcessor(\n project,\n config,\n cwd,\n driveHeader.id,\n module.client,\n vetraConfig?.interactive,\n );\n return [\n {\n processor,\n filter: {\n branch: [\"main\"],\n documentId: [\"*\"],\n documentType: [\n \"powerhouse/document-model\",\n \"powerhouse/package\",\n \"powerhouse/document-editor\",\n \"powerhouse/subgraph\",\n \"powerhouse/processor\",\n \"powerhouse/app\",\n ],\n scope: [\"global\"],\n },\n },\n ];\n };\n};\n"],"mappings":";;;;;;;;;AAgBA,SAAS,aACP,aACA,mBACS;CAET,IAAI,mBACF,OACE,YAAY,SAAS,qBACrB,YAAY,OAAO;CAMvB,MAAM,kBAAkB,eAAgC;EACtD,MAAM,QAAQ,WAAW,YAAY;EACrC,OAAO,UAAU,WAAW,MAAM,WAAW,QAAQ;CACvD;CAEA,OAAO,eAAe,YAAY,IAAI,KAAK,eAAe,YAAY,EAAE;AAC1E;AAEA,MAAa,yBACX,WACG;CACH,OAAO,OAAO,gBAA8D;EAE1E,MAAM,eADmB,OAAO,0BAAU,IAAI,IAAqB,EAAA,CAC9B,IAAI,0BAA0B;EAKnE,IAAI,CAAC,aAAa,aAAa,aAAa,OAAO,GAAG;GACpD,OAAO,MACL,SAAS,YAAY,KAAK,kDAC5B;GACA,OAAO,CAAC;EACV;EAEA,OAAO,KACL,SAAS,YAAY,KAAK,2CAC5B;EAGA,MAAM,CAAC,EAAE,uBAAuB,EAAE,aAAa,EAAE,sBAC/C,MAAM,QAAQ,IAAI;GAChB,OAAO;GACP,OAAO;GACP,OAAO,0BAAiB,CAAA,MAAA,MAAA,EAAA,CAAA;EAC1B,CAAC;EAEH,MAAM,SAAS,UAAU;EACzB,MAAM,MAAM,QAAQ,IAAI;EAYxB,OAAO,CACL;GACE,WAAA,IAVkB,iBADN,oBAAoB,GAE5B,GACN,QACA,KACA,YAAY,IACZ,OAAO,QACP,aAAa,WAIH;GACR,QAAQ;IACN,QAAQ,CAAC,MAAM;IACf,YAAY,CAAC,GAAG;IAChB,cAAc;KACZ;KACA;KACA;KACA;KACA;KACA;IACF;IACA,OAAO,CAAC,QAAQ;GAClB;EACF,CACF;CACF;AACF"}