@happyvertical/smrt-core 0.51.6 → 0.51.8

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 (32) hide show
  1. package/README.md +26 -0
  2. package/agents/build-knowledge.md +13 -0
  3. package/dist/consumer-plugin/index.d.ts.map +1 -1
  4. package/dist/consumer-plugin/index.js +141 -49
  5. package/dist/consumer-plugin/index.js.map +1 -1
  6. package/dist/manifest/discover-smrt-packages.d.ts +3 -2
  7. package/dist/manifest/discover-smrt-packages.d.ts.map +1 -1
  8. package/dist/manifest/discover-smrt-packages.js +34 -15
  9. package/dist/manifest/discover-smrt-packages.js.map +1 -1
  10. package/dist/manifest/package-manifest-exports.d.ts +34 -0
  11. package/dist/manifest/package-manifest-exports.d.ts.map +1 -0
  12. package/dist/manifest/package-manifest-exports.js +144 -0
  13. package/dist/manifest/package-manifest-exports.js.map +1 -0
  14. package/dist/manifest/static-manifest.js +1 -1
  15. package/dist/manifest/static-manifest.js.map +1 -1
  16. package/dist/manifest/store.js +1 -1
  17. package/dist/manifest.json +1 -1
  18. package/dist/migrations/differ.d.ts.map +1 -1
  19. package/dist/migrations/differ.js +19 -27
  20. package/dist/migrations/differ.js.map +1 -1
  21. package/dist/schema/column-data-probes.d.ts +71 -0
  22. package/dist/schema/column-data-probes.d.ts.map +1 -1
  23. package/dist/schema/column-data-probes.js +79 -1
  24. package/dist/schema/column-data-probes.js.map +1 -1
  25. package/dist/schema/live-parity.d.ts.map +1 -1
  26. package/dist/schema/live-parity.js +10 -12
  27. package/dist/schema/live-parity.js.map +1 -1
  28. package/dist/smrt-knowledge.json +5 -5
  29. package/dist/vite-plugin/index.d.ts.map +1 -1
  30. package/dist/vite-plugin/index.js +93 -3
  31. package/dist/vite-plugin/index.js.map +1 -1
  32. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/consumer-plugin/index.ts"],"sourcesContent":["/**\n * Vite plugin for consuming SMRT packages\n * Solves virtual module resolution in downstream projects\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { DomainKnowledgeAgentSurface } from '@happyvertical/smrt-types';\nimport type { ConfigEnv, Plugin } from 'vite';\nimport {\n loadVerifiedSmrtGenerationSnapshot,\n type SmrtGenerationSnapshotOptions,\n} from '../generation-snapshot.js';\nimport { buildDomainKnowledgeManifest } from '../knowledge.js';\nimport { resolveFileKnowledgeConfig } from '../knowledge-config.js';\nimport { generateDeclarations } from '../prebuild/index.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport { generateClientModule } from '../vite-plugin/generated-client.js';\nimport type { SmrtPluginApi } from '../vite-plugin/index.js';\nimport {\n clearGeneratedSvelteKitRouteFiles,\n reconcileSvelteKitRouteGitignore,\n type SvelteKitOptions,\n} from '../vite-plugin/sveltekit-generator.js';\nimport { canonicalSvelteKitPath } from '../vite-plugin/sveltekit-path.js';\nimport {\n activeProducerKnowledgeRoutePaths,\n activeSvelteKitRouteParticipants,\n assertNoSvelteKitRouteRootSymlinkConflict,\n assertSvelteKitRouteCoordinationComplete,\n contributeSvelteKitRoutes,\n expectedSvelteKitRouteOwners,\n markSvelteKitRouteParticipant,\n producerKnowledgeRoutePaths,\n revokeSvelteKitRoutes,\n} from '../vite-plugin/sveltekit-route-coordinator.js';\nimport {\n generateWebModule,\n isCollectionManifestClass,\n resolveCollectionItemObject,\n} from '../vite-plugin/web-collections.js';\nimport { publishArtifactFiles } from './artifact-publication.js';\n\nexport {\n loadVerifiedSmrtGenerationSnapshot,\n type SerializeSmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotArtifact,\n type SmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotView,\n serializeSmrtGenerationSnapshot,\n sha256SmrtGenerationSnapshot,\n} from '../generation-snapshot.js';\n\n/**\n * Loosely-typed view of an object definition as carried by an external\n * package's static manifest. The static manifests are read from JSON at the\n * package boundary, so only the fields this plugin consumes are typed; the\n * index signature preserves any additional fields (e.g. for spreads). This is\n * a structural superset of a manifest `SmartObjectDefinition` plus the\n * consumer-only `hasCollection` marker.\n */\ninterface ConsumerObjectDefinition {\n className?: string;\n packageName?: string;\n packageVersion?: string;\n qualifiedName?: string;\n importPath?: string;\n exportName?: string;\n collectionExportName?: string;\n hasCollection?: boolean;\n collection?: string;\n extends?: string;\n extendsQualified?: string;\n extendsTypeArg?: string;\n [key: string]: unknown;\n}\n\n/**\n * Aggregated manifest assembled by the consumer plugin from one or more\n * external package manifests. Loosely typed because the inputs originate from\n * JSON read at the package boundary.\n */\ninterface ConsumerManifest {\n version: string;\n timestamp: number;\n packageName?: string;\n packageVersion?: string;\n smrtDependencies?: string[];\n objects: Record<string, ConsumerObjectDefinition>;\n}\n\n/**\n * Minimal structural shape of a parsed `package.json` consumed here (name,\n * version, and the export map used to derive import paths). The index\n * signature keeps the remaining fields accessible.\n */\ninterface ConsumerPackageJson {\n name?: string;\n version?: string;\n main?: string;\n exports?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * SvelteKit route-hosting options for dependency models. Unlike `packages`,\n * `objects` is an HTTP exposure boundary: every entry must be an exact,\n * provider-qualified manifest key (for example, `@acme/widgets:Widget`).\n */\nexport interface SmrtConsumerSvelteKitOptions\n extends Partial<\n Pick<\n SvelteKitOptions,\n | 'routesDir'\n | 'configPath'\n | 'configFileName'\n | 'kebabRoutes'\n | 'changesRoute'\n | 'eventsRoute'\n | 'resourcesRoute'\n >\n > {\n objects: readonly string[];\n}\n\nexport interface SmrtConsumerOptions {\n /** SMRT packages to scan (e.g., ['@my-org/products', '@my-org/content']) */\n packages?: string[];\n /** Generate TypeScript declarations */\n generateTypes?: boolean;\n /** Output directory for generated types */\n typesDir?: string;\n /** Project root path (defaults to the current working directory) */\n projectRoot?: string;\n /**\n * Reuse an immutable, verified aggregated manifest instead of discovering\n * packages or writing `.smrt/manifest.json`. Registration and generated\n * types still consume the verified manifest.\n */\n generationSnapshot?: SmrtGenerationSnapshotOptions;\n /**\n * Consumer SvelteKit integration. `true` retains the historical compatibility\n * mode and does not generate dependency routes. Route hosting requires an\n * explicit, provider-qualified object allowlist.\n */\n svelteKit?: boolean | SmrtConsumerSvelteKitOptions;\n /**\n * Apply kebab-case to generated custom-method URL segments. This must match\n * the producer plugin's `svelteKit.kebabRoutes` setting. When explicit\n * consumer SvelteKit hosting is configured, its `kebabRoutes` value takes\n * precedence, including an explicit `false`.\n */\n kebabRoutes?: boolean;\n /** Use static types only (for federation builds) */\n staticTypes?: boolean;\n /** Disable file scanning */\n disableScanning?: boolean;\n}\n\n// Distinct resolved ids per plugin (#1795). smrtPlugin resolves\n// `@happyvertical/smrt-virt-*` to `\\0smrt:*`; if this consumer plugin also\n// resolved its `@smrt/*` specifiers to `\\0smrt:*` the two virtual modules would\n// share a rollup id, and in standalone/federation builds the consumer's\n// fallback `load` would non-deterministically win and shadow smrtPlugin's real\n// module. Namespacing the consumer ids (`\\0smrt-consumer:*`) keeps them\n// separate so each plugin only ever loads its own module.\nconst VIRTUAL_MODULES = {\n '@smrt/routes': 'smrt-consumer:routes',\n '@smrt/client': 'smrt-consumer:client',\n '@smrt/mcp': 'smrt-consumer:mcp',\n '@smrt/types': 'smrt-consumer:types',\n '@smrt/manifest': 'smrt-consumer:manifest',\n '@smrt/web': 'smrt-consumer:web',\n};\n\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION = 1;\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT = 'consumer-sveltekit-routes.json';\n\ninterface ConsumerSvelteKitRoutesArtifact {\n version: number;\n routesDir: string[];\n}\n\nfunction consumerSvelteKitRoutesArtifactPath(projectRoot: string): string {\n return path.join(projectRoot, '.smrt', CONSUMER_SVELTEKIT_ROUTES_ARTIFACT);\n}\n\n/** Persist only project-relative consumer route roots, never an output file list. */\nfunction canonicalConsumerRouteRoot(\n projectRoot: string,\n routesDir: string,\n): string {\n const root = path.resolve(projectRoot);\n const relative = path.relative(root, path.resolve(root, routesDir));\n if (\n !relative ||\n relative === '..' ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n throw new Error(\n `[smrt:consumer] svelteKit.routesDir must be a project-relative subdirectory (received ${JSON.stringify(routesDir)})`,\n );\n }\n return relative.split(path.sep).join('/');\n}\n\nfunction loadConsumerSvelteKitRouteRoots(projectRoot: string): string[] {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (!fs.existsSync(artifactPath)) return [];\n let parsed: ConsumerSvelteKitRoutesArtifact;\n try {\n parsed = JSON.parse(fs.readFileSync(artifactPath, 'utf-8'));\n } catch {\n throw new Error(\n `[smrt:consumer] Cannot read ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n if (\n parsed?.version !== CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION ||\n !Array.isArray(parsed.routesDir) ||\n parsed.routesDir.some((routesDir) => typeof routesDir !== 'string')\n ) {\n throw new Error(\n `[smrt:consumer] Invalid ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n return [...new Set(parsed.routesDir)].map((routesDir) =>\n canonicalConsumerRouteRoot(projectRoot, routesDir),\n );\n}\n\nfunction publishConsumerSvelteKitRouteRoots(\n projectRoot: string,\n routesDir: string[],\n): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n fs.mkdirSync(path.dirname(artifactPath), { recursive: true });\n publishArtifactFiles([\n {\n path: artifactPath,\n content: JSON.stringify(\n {\n version: CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION,\n routesDir: [...new Set(routesDir)].sort(),\n } satisfies ConsumerSvelteKitRoutesArtifact,\n null,\n 2,\n ),\n },\n ]);\n}\n\nfunction removeConsumerSvelteKitRouteRoots(projectRoot: string): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (fs.existsSync(artifactPath)) fs.unlinkSync(artifactPath);\n}\n\n/**\n * A hosting-to-hosting move can replace one configured root with another in a\n * fresh lifecycle. Validate every durable former root before the new target\n * journals or clears anything, otherwise a rejected move could alter the\n * prior generated surface before reconciliation notices the conflict.\n */\nasync function assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig: unknown,\n projectRoot: string,\n routesDir: readonly string[],\n env?: ConfigEnv,\n): Promise<void> {\n if (routesDir.length === 0) return;\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n const activeRoots = activeParticipants.map(\n (participant) => participant.routesDir,\n );\n for (const priorRoutesDir of routesDir) {\n assertNoSvelteKitRouteRootSymlinkConflict(\n canonicalSvelteKitPath(path.resolve(projectRoot, priorRoutesDir)),\n activeRoots,\n );\n }\n}\n\nasync function reconcileConsumerSvelteKitRouteRoots(\n lifecycle: object,\n userConfig: unknown,\n projectRoot: string,\n routesDir: string[],\n afterReconciled: () => void,\n env?: ConfigEnv,\n): Promise<void> {\n const remaining = new Set(routesDir);\n const reconcileOne = (routesDir: string) => {\n remaining.delete(routesDir);\n if (remaining.size === 0) afterReconciled();\n };\n\n if (remaining.size === 0) {\n afterReconciled();\n return;\n }\n\n for (const routesDir of [...remaining]) {\n const routeRoot = canonicalSvelteKitPath(\n path.resolve(projectRoot, routesDir),\n );\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n // The durable consumer inventory names roots, not individual handlers.\n // Check before every reconciliation branch, including an active parent\n // consumer that would otherwise compact a nested former root without a\n // sweep. A child symlink into a foreign active root makes that ownership\n // ambiguous, so retaining the inventory makes retry safe.\n assertNoSvelteKitRouteRootSymlinkConflict(\n routeRoot,\n activeParticipants.map((participant) => participant.routesDir),\n );\n const containingConsumer = activeParticipants.find(\n (participant) =>\n participant.owner === 'consumer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n // A current parent consumer root has already swept and regenerated this\n // former child root. Sweeping it again would remove the newly selected\n // handler before SvelteKit inventories it.\n if (containingConsumer) {\n reconcileOne(routesDir);\n continue;\n }\n const containingProducer = activeParticipants.find(\n (participant) =>\n participant.owner === 'producer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n if (containingProducer) {\n await revokeSvelteKitRoutes(\n lifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n containingProducer.projectRoot,\n containingProducer.routesDir,\n env,\n ),\n containingProducer.projectRoot,\n containingProducer.routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n const owners = await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routesDir,\n env,\n );\n if (owners.includes('producer')) {\n await revokeSvelteKitRoutes(\n lifecycle,\n owners,\n projectRoot,\n routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n clearGeneratedSvelteKitRouteFiles(\n routeRoot,\n producerKnowledgeRoutePaths(lifecycle),\n new Set(\n activeParticipants\n .map((participant) => participant.routesDir)\n .filter((activeRoot) => activeRoot !== routeRoot),\n ),\n );\n reconcileSvelteKitRouteGitignore(projectRoot, routesDir);\n reconcileOne(routesDir);\n }\n}\n\nfunction consumerRouteOptions(\n value: SmrtConsumerOptions['svelteKit'],\n): SmrtConsumerSvelteKitOptions | undefined {\n if (!value || value === true) return undefined;\n if (!Array.isArray(value.objects) || value.objects.length === 0) {\n throw new Error(\n '[smrt:consumer] svelteKit.objects must list at least one provider-qualified object reference',\n );\n }\n for (const objectRef of value.objects) {\n if (typeof objectRef !== 'string' || !objectRef.includes(':')) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects entries must be provider-qualified (received ${JSON.stringify(objectRef)})`,\n );\n }\n }\n return value;\n}\n\nfunction consumerUtilityOption<T extends { enabled?: boolean }>(\n value: T | undefined,\n): T | { enabled: false } {\n return value?.enabled === true ? value : { enabled: false };\n}\n\nfunction consumerObjectRef(\n manifestKey: string,\n objectDef: ConsumerObjectDefinition,\n): string | undefined {\n if (manifestKey.includes(':')) return manifestKey;\n if (objectDef.qualifiedName?.includes(':')) return objectDef.qualifiedName;\n if (objectDef.packageName && objectDef.className) {\n return `${objectDef.packageName}:${objectDef.className}`;\n }\n return undefined;\n}\n\n/**\n * Select exactly the dependency objects that a consumer explicitly hosts.\n * Validation completes before the generator clears its managed files, so an\n * invalid deployment cannot erase a previously generated route surface.\n */\nfunction selectConsumerRouteManifest(\n manifest: ConsumerManifest,\n options: SmrtConsumerSvelteKitOptions,\n): SmartObjectManifest {\n const entriesByRef = new Map<string, [string, ConsumerObjectDefinition]>();\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const objectRef = consumerObjectRef(manifestKey, objectDef);\n if (objectRef) entriesByRef.set(objectRef, [manifestKey, objectDef]);\n }\n\n const selected = new Set<string>();\n const objects: Record<string, ConsumerObjectDefinition> = {};\n for (const objectRef of options.objects) {\n const entry = entriesByRef.get(objectRef);\n if (!entry) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects references unknown dependency object ${JSON.stringify(objectRef)}`,\n );\n }\n if (selected.has(objectRef)) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects contains duplicate object ${JSON.stringify(objectRef)}`,\n );\n }\n selected.add(objectRef);\n const [, objectDef] = entry;\n objects[objectRef] = { ...objectDef, qualifiedName: objectRef };\n }\n\n const sourceManifest = manifest as unknown as SmartObjectManifest;\n // Use the generator's canonical ancestry resolver so a collection subclass\n // inherits the selected item's identity through any number of ancestors.\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const candidate = objectDef as unknown as SmartObjectDefinition;\n if (!isCollectionManifestClass(sourceManifest, candidate)) continue;\n const item = resolveCollectionItemObject(sourceManifest, candidate);\n const itemEntry = item\n ? Object.entries(manifest.objects).find(\n ([, value]) => (value as unknown) === item,\n )\n : undefined;\n const itemRef = itemEntry\n ? consumerObjectRef(itemEntry[0], itemEntry[1])\n : undefined;\n if (!itemRef || !selected.has(itemRef)) continue;\n const collectionRef = consumerObjectRef(manifestKey, objectDef);\n if (collectionRef) {\n objects[collectionRef] = { ...objectDef, qualifiedName: collectionRef };\n }\n }\n\n return {\n ...manifest,\n // The generated route config imports this full registration entry point so\n // SSR retains every consumer provider, while only `objects` reach routing.\n // `smrtDependencies` is optional in verified snapshots, so derive this\n // generator signal from the immutable full manifest rather than treating\n // absent metadata as an empty provider inventory.\n smrtDependencies: [\n ...new Set(\n Object.values(manifest.objects)\n .map((objectDef) => objectDef.packageName)\n .filter(\n (packageName): packageName is string =>\n typeof packageName === 'string' &&\n packageName !== manifest.packageName,\n ),\n ),\n ].sort(),\n objects,\n } as unknown as SmartObjectManifest;\n}\n\n/**\n * Consumer plugin for projects that use SMRT packages\n */\nexport function smrtConsumer(options: SmrtConsumerOptions = {}): Plugin {\n const {\n packages = [],\n generateTypes = true,\n typesDir = 'src/types/smrt-generated',\n projectRoot = process.cwd(),\n generationSnapshot,\n disableScanning = false,\n kebabRoutes = false,\n } = options;\n const consumerSvelteKit = consumerRouteOptions(options.svelteKit);\n // Hosted routes, the generated client, and web tool definitions must expose\n // the same custom-action URLs. Nested consumer SvelteKit hosting owns this\n // policy when present, including an explicit false override.\n const effectiveKebabRoutes = consumerSvelteKit?.kebabRoutes ?? kebabRoutes;\n\n let smrtPackages: string[] = [];\n let typeManifest: ConsumerManifest | null = null;\n let typesGenerated = false;\n let producerApi: SmrtPluginApi | undefined;\n let routeLifecycleConfig: object | undefined;\n\n function loadGenerationSnapshot(): ConsumerManifest {\n if (!generationSnapshot) {\n throw new Error('[smrt:consumer] Generation snapshot is not configured');\n }\n return loadVerifiedSmrtGenerationSnapshot<ConsumerManifest>(\n generationSnapshot,\n projectRoot,\n 'dependencies',\n );\n }\n\n async function generateConfigTypes(\n manifest?: ConsumerManifest,\n ): Promise<void> {\n if (!generateTypes || typesGenerated) return;\n\n typeManifest =\n manifest ??\n (generationSnapshot\n ? loadGenerationSnapshot()\n : await aggregateTypeManifests(\n packages.length === 0 && !disableScanning\n ? await discoverSmrtPackages(projectRoot)\n : packages,\n projectRoot,\n ));\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n\n const plugin: Plugin = {\n name: 'smrt-consumer',\n\n // SvelteKit inventories routes in its config hook. Run before it so a\n // clean consumer build sees the explicit dependency routes on its first\n // invocation, even when sveltekit() appears first in vite.config.\n enforce: 'pre',\n\n config: {\n order: 'pre',\n async handler(userConfig, env) {\n const routeLifecycle = env ?? userConfig;\n routeLifecycleConfig = routeLifecycle;\n const previousConsumerRouteRoots =\n loadConsumerSvelteKitRouteRoots(projectRoot);\n if (consumerSvelteKit) {\n await assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n env,\n );\n const routePackages =\n packages.length === 0 && !disableScanning\n ? await discoverSmrtPackages(projectRoot)\n : packages;\n const routeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : await aggregateTypeManifests(routePackages, projectRoot);\n const hostedManifest = selectConsumerRouteManifest(\n routeManifest,\n consumerSvelteKit,\n );\n const routesDir = canonicalConsumerRouteRoot(\n projectRoot,\n consumerSvelteKit.routesDir ?? 'src/routes/api',\n );\n const reservedRoutePaths = await activeProducerKnowledgeRoutePaths(\n userConfig,\n projectRoot,\n env,\n );\n const routeOptions = {\n enabled: true,\n routesDir,\n objectsDir: 'src/lib/objects',\n configPath: consumerSvelteKit.configPath ?? 'src/lib/server',\n configFileName: consumerSvelteKit.configFileName ?? 'smrt.ts',\n kebabRoutes: effectiveKebabRoutes,\n // These span a model set rather than one selected object, so new\n // consumer hosting starts fail-closed. Callers can opt in with the\n // generator's established option shapes.\n changesRoute: consumerUtilityOption(consumerSvelteKit.changesRoute),\n eventsRoute: consumerUtilityOption(consumerSvelteKit.eventsRoute),\n resourcesRoute: consumerUtilityOption(\n consumerSvelteKit.resourcesRoute,\n ),\n rejectRouteCollisions: true,\n };\n let ownershipJournaled = false;\n let reconciliationScheduled = false;\n await contributeSvelteKitRoutes(\n routeLifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routeOptions.routesDir,\n env,\n ),\n projectRoot,\n {\n owner: 'consumer',\n routeManifest: hostedManifest,\n semanticManifest: routeManifest as unknown as SmartObjectManifest,\n options: routeOptions,\n reservedRoutePaths,\n beforeCleanup: async () => {\n // Route selection and collision checks have succeeded, but no\n // generated output has changed. SvelteKit type checking still\n // runs after this config hook and needs these declarations.\n await generateConfigTypes(routeManifest);\n if (ownershipJournaled) return;\n ownershipJournaled = true;\n // Preflight has succeeded but no generated output has changed.\n // Keep both roots until old-root reconciliation commits.\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n ...previousConsumerRouteRoots,\n routesDir,\n ]);\n },\n afterGenerate: async () => {\n if (reconciliationScheduled) return;\n reconciliationScheduled = true;\n const priorRoots = previousConsumerRouteRoots.filter(\n (previousRoot) => previousRoot !== routesDir,\n );\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n priorRoots,\n () =>\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n routesDir,\n ]),\n env,\n );\n },\n },\n );\n } else {\n // Legacy/non-hosting SvelteKit consumers have no route preflight,\n // but still need physical virtual-module declarations before their\n // SvelteKit typecheck reaches Vite's later buildStart lifecycle.\n await generateConfigTypes();\n if (previousConsumerRouteRoots.length > 0) {\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n () => removeConsumerSvelteKitRouteRoots(projectRoot),\n env,\n );\n }\n }\n return {\n build: {\n rollupOptions: {\n // Runtime registration evaluates provider entry points so their\n // exact constructors can be registered. Leave optional native\n // provider binaries to Node instead of parsing them as JavaScript.\n external: [/\\.node$/],\n },\n },\n };\n },\n },\n\n configResolved(resolvedConfig) {\n if (consumerSvelteKit && routeLifecycleConfig) {\n assertSvelteKitRouteCoordinationComplete(routeLifecycleConfig);\n }\n producerApi = (resolvedConfig.plugins ?? []).find(\n (plugin) => plugin?.name === 'smrt-auto-service',\n )?.api as SmrtPluginApi | undefined;\n },\n\n async buildStart() {\n console.log('[smrt:consumer] Initializing SMRT consumer plugin');\n\n if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n console.log(\n `[smrt:consumer] Reusing verified generation snapshot (${generationSnapshot.provenance})`,\n );\n await generateRegistrationFile(typeManifest, projectRoot);\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n return;\n }\n\n // Discover SMRT packages if not explicitly specified\n if (packages.length === 0 && !disableScanning) {\n smrtPackages = await discoverSmrtPackages(projectRoot);\n } else {\n smrtPackages = packages;\n }\n\n if (smrtPackages.length > 0) {\n console.log(\n `[smrt:consumer] Found SMRT packages: ${smrtPackages.join(', ')}`,\n );\n\n // Aggregate type manifests from discovered packages\n typeManifest = await aggregateTypeManifests(smrtPackages, projectRoot);\n // Wait before reading .smrt/manifest.json: a producer's parallel\n // buildStart writes its current local manifest after scanning. Reading\n // first could merge an older local manifest with a newer surface.\n const agentSurface = producerApi\n ? await producerApi.resolveKnowledgeAgentSurface()\n : undefined;\n\n // Save aggregated manifest for CLI discovery\n await saveAggregatedManifest(\n typeManifest,\n projectRoot,\n producerApi?.resolveKnowledgeConfig,\n agentSurface,\n );\n\n // Generate registration file for CLI class loading\n await generateRegistrationFile(typeManifest, projectRoot);\n\n // Generate types if requested\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n } else {\n console.log('[smrt:consumer] No SMRT packages found');\n typeManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n },\n\n resolveId(id, _importer) {\n // Resolve virtual modules to generated type declarations\n if (id in VIRTUAL_MODULES) {\n // Generated declarations are ambient TypeScript declarations, not\n // executable JavaScript. Vite must always load the consumer runtime\n // module after default type generation writes them.\n if (id !== '@smrt/types') {\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n\n const typeFileName = getTypeFileName(id);\n const typePath = path.join(projectRoot, typesDir, typeFileName);\n\n // If types file exists, resolve to it\n if (fs.existsSync(typePath)) {\n return typePath;\n }\n\n // Otherwise use virtual module ID for runtime resolution\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n return null;\n },\n\n async load(id) {\n // Handle virtual modules if types aren't available\n const cleanId = id.startsWith('\\0') ? id.slice(1) : id;\n\n if (!typeManifest) {\n typeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n\n switch (cleanId) {\n case 'smrt-consumer:routes':\n return generateFallbackRoutesModule();\n\n case 'smrt-consumer:client':\n return generateFallbackClientModule(typeManifest, {\n kebabRoutes: effectiveKebabRoutes,\n });\n\n case 'smrt-consumer:mcp':\n return generateFallbackMcpModule();\n\n case 'smrt-consumer:types':\n return generateFallbackTypesModule(typeManifest);\n\n case 'smrt-consumer:manifest':\n return generateFallbackManifestModule(typeManifest);\n\n case 'smrt-consumer:web':\n return generateWebModule(\n typeManifest as unknown as SmartObjectManifest,\n {\n kebabRoutes: effectiveKebabRoutes,\n },\n );\n\n default:\n return null;\n }\n },\n };\n markSvelteKitRouteParticipant(\n plugin,\n 'consumer',\n Boolean(consumerSvelteKit),\n consumerSvelteKit?.routesDir ?? 'src/routes/api',\n undefined,\n () => projectRoot,\n );\n return plugin;\n}\n\n/**\n * Discover SMRT packages from a consumer app's dependencies.\n *\n * Intentional split (#1579): this **consumer-plugin** path is async and\n * resolves SMRT packages from the downstream app's `package.json` dependency\n * names (`@have/`/`smrt` heuristic + `hasSmrtManifest` probe) inside the Vite\n * consumer plugin. It is deliberately separate from the build-time\n * `discoverSmrtPackages()` in `src/manifest/discover-smrt-packages.ts` — a\n * synchronous, lockfile-cached `node_modules` manifest scan used for manifest\n * generation. Different inputs, contexts, and lifecycles, not duplicated logic.\n */\nasync function discoverSmrtPackages(projectRoot: string): Promise<string[]> {\n const packages: string[] = [];\n const nodeModulesPath = path.join(projectRoot, 'node_modules');\n\n if (!fs.existsSync(nodeModulesPath)) {\n return packages;\n }\n\n try {\n // Check package.json for workspace dependencies\n const packageJsonPath = path.join(projectRoot, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Look for packages that likely contain SMRT objects\n for (const [name, version] of Object.entries(allDeps)) {\n if (\n typeof version === 'string' &&\n (name.includes('smrt') ||\n name.includes('@have/') ||\n (await hasSmrtManifest(nodeModulesPath, name)))\n ) {\n packages.push(name);\n }\n }\n }\n } catch (error) {\n console.warn('[smrt:consumer] Error discovering packages:', error);\n }\n\n return packages;\n}\n\n/**\n * Check if a package has SMRT manifest\n */\nasync function hasSmrtManifest(\n nodeModulesPath: string,\n packageName: string,\n): Promise<boolean> {\n const packagePath = path.join(nodeModulesPath, packageName);\n const manifestPath = path.join(\n packagePath,\n 'dist',\n 'manifest',\n 'static-manifest.js',\n );\n return fs.existsSync(manifestPath);\n}\n\n/**\n * Aggregate type manifests from multiple packages\n */\nasync function aggregateTypeManifests(\n packages: string[],\n projectRoot: string,\n): Promise<ConsumerManifest> {\n const aggregatedManifest: ConsumerManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n smrtDependencies: [...packages],\n objects: {},\n };\n\n for (const packageName of packages) {\n try {\n const packageDir = path.join(projectRoot, 'node_modules', packageName);\n\n // Load package.json for version and export information\n const packageJsonPath = path.join(packageDir, 'package.json');\n let packageJson: ConsumerPackageJson;\n try {\n const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContent) as ConsumerPackageJson;\n } catch {\n console.warn(\n `[smrt:consumer] Could not read package.json for ${packageName}`,\n );\n continue;\n }\n\n // Try multiple manifest locations\n const manifestCandidates = [\n path.join(packageDir, 'dist', 'manifest', 'static-manifest.js'),\n path.join(packageDir, 'dist', 'manifest.json'),\n path.join(packageDir, 'manifest.json'),\n ];\n\n for (const manifestPath of manifestCandidates) {\n if (fs.existsSync(manifestPath)) {\n // Import or read the manifest\n let manifest: Partial<ConsumerManifest> | undefined;\n if (manifestPath.endsWith('.js')) {\n const manifestModule = await import(manifestPath);\n manifest = manifestModule.staticManifest || manifestModule.default;\n } else {\n const manifestContent = fs.readFileSync(manifestPath, 'utf-8');\n manifest = JSON.parse(manifestContent) as Partial<ConsumerManifest>;\n }\n\n if (manifest?.objects) {\n console.log(\n `[smrt:consumer] Loaded manifest from ${packageName} (${Object.keys(manifest.objects).length} objects)`,\n );\n\n // ENHANCED: Preserve package metadata for each object\n for (const [objectName, objectDef] of Object.entries(\n manifest.objects,\n )) {\n const def = objectDef;\n\n aggregatedManifest.objects[objectName] = {\n ...def,\n // Ensure package metadata is preserved/set\n packageName:\n def.packageName || manifest.packageName || packageName,\n packageVersion:\n def.packageVersion ||\n manifest.packageVersion ||\n packageJson.version,\n // Add fallback import paths if missing\n importPath: def.importPath || determineImportPath(packageJson),\n exportName: def.exportName || def.className || objectName,\n collectionExportName:\n def.collectionExportName ||\n `${def.className || objectName}Collection`,\n };\n }\n\n break; // Use first found manifest for this package\n }\n }\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Error loading manifest from ${packageName}:`,\n error,\n );\n }\n }\n\n return aggregatedManifest;\n}\n\n/**\n * Determine import path from package.json\n */\nfunction determineImportPath(packageJson: ConsumerPackageJson): string {\n const packageName = packageJson.name;\n\n if (!packageName) {\n throw new Error('Package name not found in package.json');\n }\n\n // Strategy 1: Check for specific exports\n if (packageJson.exports) {\n // Check for objects export\n if (packageJson.exports['./objects']) {\n return `${packageName}/objects`;\n }\n\n // Check for main export\n const mainExport = packageJson.exports['.'];\n if (mainExport) {\n // Handle conditional exports\n if (typeof mainExport === 'object' && mainExport !== null) {\n const conditional = mainExport as Record<string, unknown>;\n if (conditional.import) {\n return packageName;\n }\n if (conditional.default) {\n return packageName;\n }\n }\n return packageName;\n }\n }\n\n // Strategy 2: Check main field\n if (packageJson.main) {\n return packageName;\n }\n\n // Strategy 3: Fallback to package name\n return packageName;\n}\n\n/**\n * Save aggregated manifest to .smrt/manifest.json for CLI discovery.\n *\n * Merge-preserving: `smrtPlugin()` writes the project's own scanned objects\n * to the same file (`writeLocalManifest`, issue #963), and both writes happen\n * in parallel `buildStart` hooks — so a plain overwrite here would clobber\n * the local objects whenever this plugin's write lands last (issue #1760\n * review). Local field metadata would then silently vanish from CLI schema\n * commands and from server runtimes that seed `.smrt/manifest.json`, dropping\n * domain columns on write. This function therefore only ADDS/refreshes the\n * external-package entries it owns and preserves everything else already in\n * the file (including the top-level `packageName` the local write sets).\n */\nasync function saveAggregatedManifest(\n manifest: ConsumerManifest,\n projectRoot: string,\n resolveKnowledgeConfig?: SmrtPluginApi['resolveKnowledgeConfig'],\n agentSurface?: DomainKnowledgeAgentSurface,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const manifestPath = path.join(smrtDir, 'manifest.json');\n\n try {\n // Create .smrt directory if it doesn't exist\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Merge with whatever is on disk: existing entries (typically the local\n // project's objects written by smrtPlugin) are preserved; aggregated\n // external entries win for the qualified names this plugin owns.\n let merged: ConsumerManifest = manifest;\n if (fs.existsSync(manifestPath)) {\n try {\n const existing = JSON.parse(\n fs.readFileSync(manifestPath, 'utf-8'),\n ) as Partial<ConsumerManifest>;\n if (existing && typeof existing.objects === 'object') {\n merged = {\n ...existing,\n ...manifest,\n // The aggregated manifest carries no packageName; keep the local\n // project's (used as the manifest cache key at runtime).\n ...(existing.packageName\n ? { packageName: existing.packageName }\n : {}),\n objects: { ...existing.objects, ...manifest.objects },\n };\n }\n } catch {\n // Unreadable/corrupt existing file — fall back to a plain write.\n }\n }\n\n // smrtPlugin writes the local knowledge artifact before this consumer\n // plugin merges external package entries into the same manifest. Refresh\n // the artifact from the merged manifest so its source hash always names\n // the manifest that CLI discovery and server runtimes actually consume.\n // The consumer deliberately does not load the scanner. Only carry a\n // surface from the current producer scan: a prior artifact can describe\n // declarations that have since changed while retaining the same path.\n // Re-hashing that current path under a stale declaration would make an\n // incorrect agent contract look fresh.\n const knowledgePath = path.join(smrtDir, 'smrt-knowledge.json');\n const packageJsonPath = path.join(projectRoot, 'package.json');\n const packageJson = fs.existsSync(packageJsonPath)\n ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n : undefined;\n const knowledgeConfig = resolveKnowledgeConfig\n ? await resolveKnowledgeConfig(merged as unknown as SmartObjectManifest)\n : await resolveFileKnowledgeConfig(\n projectRoot,\n merged.packageName ?? packageJson?.name,\n );\n if (knowledgeConfig.enabled === false) {\n publishArtifactFiles([\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n return;\n }\n const knowledge = buildDomainKnowledgeManifest({\n manifest: merged as unknown as SmartObjectManifest,\n rootDir: projectRoot,\n packageJson,\n manifestPath,\n config: knowledgeConfig,\n agentSurface,\n });\n // Stage both artifacts before replacing either. Renames are individually\n // atomic; if a synchronous later rename fails, restore every earlier\n // replacement. A process crash between renames cannot be made pair-atomic\n // with ordinary filesystem operations, so the next generation remains the\n // freshness repair path for that distinct failure mode.\n publishArtifactFiles([\n { path: knowledgePath, content: JSON.stringify(knowledge, null, 2) },\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n\n console.log(\n `[smrt:consumer] Saved aggregated manifest to .smrt/manifest.json (${Object.keys(merged.objects).length} objects)`,\n );\n } catch (error) {\n throw new Error('[smrt:consumer] Failed to save aggregated manifest', {\n cause: error,\n });\n }\n}\n\n/**\n * Generate registration file for CLI class loading\n *\n * Creates .smrt/register.js with static imports and registrations\n * for all external SMRT objects discovered during build.\n */\nasync function generateRegistrationFile(\n manifest: ConsumerManifest,\n projectRoot: string,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const registerPath = path.join(smrtDir, 'register.js');\n\n // Bind every imported symbol to a generated local name. Aggregated manifests\n // may contain same-named exports from different packages (and may list a\n // collection both beside its object and as its own manifest entry), so using\n // provider export names as local bindings can produce invalid duplicate\n // imports in a production consumer bundle.\n const importBindings = new Map<string, string>();\n const importsByPath = new Map<string, Map<string, string>>();\n let nextImportBinding = 0;\n const getImportBinding = (importPath: string, exportName: string): string => {\n const key = `${importPath}\\0${exportName}`;\n const existing = importBindings.get(key);\n if (existing) return existing;\n const binding = `__smrt_consumer_${nextImportBinding++}`;\n importBindings.set(key, binding);\n const specifiers =\n importsByPath.get(importPath) ?? new Map<string, string>();\n specifiers.set(exportName, binding);\n importsByPath.set(importPath, specifiers);\n return binding;\n };\n\n const registrations: string[] = [];\n const registrationManifests: Record<string, ConsumerManifest> = {};\n let importedEntryCount = 0;\n let registeredObjectCount = 0;\n\n const manifestObjects = manifest.objects;\n const manifestObjectLookup = new Map<string, ConsumerObjectDefinition>();\n for (const [key, def] of Object.entries(manifestObjects)) {\n const candidate = def;\n const lookupKeys = [\n key,\n key.includes(':') ? key.split(':').pop() : undefined,\n candidate.qualifiedName,\n candidate.className,\n candidate.exportName,\n ];\n\n for (const lookupKey of lookupKeys) {\n if (lookupKey && !manifestObjectLookup.has(lookupKey)) {\n manifestObjectLookup.set(lookupKey, candidate);\n }\n }\n }\n\n const collectionClassMemo = new WeakMap<object, boolean>();\n\n const isCollectionClass = (\n def: ConsumerObjectDefinition | undefined,\n seen = new Set<string>(),\n ): boolean => {\n if (!def || typeof def !== 'object') {\n return false;\n }\n\n const cached = collectionClassMemo.get(def);\n if (cached !== undefined) {\n return cached;\n }\n\n if (\n def?.extends === 'SmrtCollection' ||\n def?.extendsTypeArg !== undefined\n ) {\n collectionClassMemo.set(def, true);\n return true;\n }\n\n const parentName = def?.extendsQualified || def?.extends;\n if (!parentName || seen.has(parentName)) {\n collectionClassMemo.set(def, false);\n return false;\n }\n seen.add(parentName);\n\n const parentDef = manifestObjectLookup.get(parentName);\n const isCollection = parentDef ? isCollectionClass(parentDef, seen) : false;\n collectionClassMemo.set(def, isCollection);\n\n return isCollection;\n };\n\n for (const [objectName, objectDef] of Object.entries(manifestObjects)) {\n const def = objectDef;\n\n // Skip local objects (they're imported from local entry point)\n if (!def.packageName || def.packageName === manifest.packageName) {\n continue;\n }\n\n const importPath = def.importPath || def.packageName;\n const exportName = def.exportName || def.className || objectName;\n const collectionExportName = def.collectionExportName;\n const hasCollection = def.hasCollection; // Check if collection class actually exists\n const tableName = def.collection || objectName.toLowerCase();\n\n const exportBinding = getImportBinding(importPath, exportName);\n const collectionBinding =\n hasCollection && collectionExportName\n ? getImportBinding(importPath, collectionExportName)\n : undefined;\n importedEntryCount++;\n\n if (isCollectionClass(def)) {\n continue;\n }\n\n const logicalName = def.className || exportName;\n registrationManifests[objectName] = {\n ...manifest,\n packageName: def.packageName,\n packageVersion: def.packageVersion || manifest.packageVersion,\n objects: { [objectName]: def },\n };\n\n // Import evaluation triggers the provider decorator first. The explicit\n // constructor/package/key tuple then promotes that exact constructor with\n // its isolated manifest, which is stable across Rollup name deconfliction.\n registrations.push(\n `if (${exportBinding}) ObjectRegistry.register(${exportBinding}, { name: ${JSON.stringify(logicalName)}, packageName: ${JSON.stringify(def.packageName)}, _manifest: smrtRegistrationManifests[${JSON.stringify(objectName)}], _manifestKey: ${JSON.stringify(objectName)} });`,\n );\n\n // Only register collection if it exists\n if (collectionBinding) {\n registrations.push(\n `if (${collectionBinding}) ObjectRegistry.registerCollection('${tableName}', ${collectionBinding});`,\n );\n }\n\n registeredObjectCount++;\n }\n\n // Skip generation if no external entries\n if (importedEntryCount === 0) {\n console.log('[smrt:consumer] No external entries - skipping register.js');\n return;\n }\n\n const registeredObjectLabel =\n registeredObjectCount === 1 ? 'object' : 'objects';\n const sortedImports = Array.from(importsByPath.entries()).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n const imports = sortedImports.map(\n ([importPath], index) =>\n `import * as __smrt_provider_${index} from '${importPath}';`,\n );\n const importDeclarations = sortedImports.flatMap(([, specifiers], index) =>\n Array.from(specifiers.entries())\n .sort(([left], [right]) => left.localeCompare(right))\n .map(\n ([exportName, binding]) =>\n `const ${binding} = getSmrtExport(__smrt_provider_${index}, ${JSON.stringify(exportName)});`,\n ),\n );\n const registrationManifestLiteral = JSON.stringify(\n JSON.stringify(registrationManifests),\n );\n\n // Generate file content\n const content = `/**\n * Auto-generated by @happyvertical/smrt-core/consumer-plugin\n * DO NOT EDIT - This file is regenerated on every build\n *\n * Registers SMRT objects from external packages for CLI discovery.\n * Generated at: ${new Date().toISOString()}\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n${imports.join('\\n')}\n\n/**\n * @param {Record<string, unknown>} provider\n * @param {string} exportName\n * @returns {any}\n */\nconst getSmrtExport = (provider, exportName) =>\n typeof provider[exportName] === 'function' ? provider[exportName] : undefined;\n${importDeclarations.join('\\n')}\n\nconst smrtRegistrationManifests = JSON.parse(${registrationManifestLiteral});\n\n// Register all objects (executed during module evaluation)\n${registrations.join('\\n')}\n\nexport function registerAll() {\n // Objects are already registered during module evaluation\n console.log('[smrt:register] Registered ${registeredObjectCount} external ${registeredObjectLabel}');\n}\n`;\n\n // Create .smrt directory if needed\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Write registration file\n fs.writeFileSync(registerPath, content, 'utf-8');\n\n console.log(\n `[smrt:consumer] Generated .smrt/register.js with ${importedEntryCount} external entries (${registeredObjectCount} registered ${registeredObjectLabel})`,\n );\n}\n\n/**\n * Generate project-specific types\n */\nasync function generateProjectTypes(\n typeManifest: ConsumerManifest,\n typesDir: string,\n projectRoot: string,\n): Promise<void> {\n if (!typeManifest || Object.keys(typeManifest.objects).length === 0) {\n console.log(\n '[smrt:consumer] No SMRT objects found, skipping type generation',\n );\n return;\n }\n\n await generateDeclarations({\n // The aggregated manifest is a runtime SMRT manifest assembled from external\n // package manifests; it is intentionally typed loosely at the JSON boundary,\n // so narrow it to the declaration generator's strict manifest shape here.\n manifest: typeManifest as unknown as SmartObjectManifest,\n outDir: typesDir,\n projectRoot,\n includeVirtualModules: true,\n includeObjectTypes: true,\n });\n\n console.log(\n `[smrt:consumer] Generated types for ${Object.keys(typeManifest.objects).length} objects`,\n );\n}\n\n/**\n * Get type file name for virtual module\n */\nfunction getTypeFileName(virtualModule: string): string {\n const moduleMap: Record<string, string> = {\n '@smrt/routes': 'smrt-routes.d.ts',\n '@smrt/client': 'smrt-client.d.ts',\n '@smrt/mcp': 'smrt-mcp.d.ts',\n '@smrt/types': 'smrt-types.d.ts',\n '@smrt/manifest': 'smrt-manifest.d.ts',\n '@smrt/web': 'smrt-web.d.ts',\n };\n return moduleMap[virtualModule] || 'smrt-unknown.d.ts';\n}\n\n/**\n * Fallback modules for when types aren't available\n */\nfunction generateFallbackRoutesModule(): string {\n return `\n// Fallback routes module\nexport function setupRoutes(app) {\n console.warn('[smrt:consumer] No routes available - SMRT packages may not be properly configured');\n}\nexport default setupRoutes;\n`;\n}\n\nfunction generateFallbackClientModule(\n manifest: ConsumerManifest,\n options: { kebabRoutes?: boolean } = {},\n): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `\n// Fallback client module\nexport function createClient(basePath = '/api/v1') {\n console.warn('[smrt:consumer] No API client available - SMRT packages may not be properly configured');\n return {};\n}\nexport default createClient;\n`;\n }\n\n return generateClientModule(manifest as unknown as SmartObjectManifest, {\n kebabRoutes: options.kebabRoutes,\n });\n}\n\nfunction generateFallbackMcpModule(): string {\n return `\n// Fallback MCP module\nexport const tools = [];\nexport function createMCPServer() {\n console.warn('[smrt:consumer] No MCP tools available - SMRT packages may not be properly configured');\n return { name: 'smrt-consumer', version: '1.0.0', tools: [] };\n}\nexport default createMCPServer;\n`;\n}\n\nfunction generateFallbackTypesModule(manifest: ConsumerManifest): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `// No types available`;\n }\n\n // Generate basic interfaces\n const interfaces = objects.map(([_name, obj]) => {\n return `export interface ${obj.className}Data {\n id?: string;\n created_at?: string;\n updated_at?: string;\n [key: string]: any;\n}`;\n });\n\n return interfaces.join('\\n\\n');\n}\n\nfunction generateFallbackManifestModule(manifest: ConsumerManifest): string {\n return `\n// Auto-generated manifest from SMRT consumer\nexport const manifest = ${JSON.stringify(manifest, null, 2)};\nexport default manifest;\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0KA,IAAM,kBAAkB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,kBAAkB;CAClB,aAAa;AACf;AAEA,IAAM,6CAA6C;AACnD,IAAM,qCAAqC;AAO3C,SAAS,oCAAoC,aAA6B;CACxE,OAAO,KAAK,KAAK,aAAa,SAAS,kCAAkC;AAC3E;;AAGA,SAAS,2BACP,aACA,WACQ;CACR,MAAM,OAAO,KAAK,QAAQ,WAAW;CACrC,MAAM,WAAW,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM,SAAS,CAAC;CAClE,IACE,CAAC,YACD,aAAa,QACb,SAAS,WAAW,KAAK,KAAK,KAAK,KACnC,KAAK,WAAW,QAAQ,GAExB,MAAM,IAAI,MACR,yFAAyF,KAAK,UAAU,SAAS,EAAE,EACrH;CAEF,OAAO,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;AAC1C;AAEA,SAAS,gCAAgC,aAA+B;CACtE,MAAM,eAAe,oCAAoC,WAAW;CACpE,IAAI,CAAC,GAAG,WAAW,YAAY,GAAG,OAAO,CAAC;CAC1C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG,aAAa,cAAc,OAAO,CAAC;CAC5D,QAAQ;EACN,MA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AM,qBAAqB;EAIzB,UAAU;EACV,QAAQ;EACR;EACA,uBAAuB;EACvB,oBAAoB;CACtB,CAAC;CAED,QAAQ,IACN,uCAAuC,OAAO,KAAK,aAAa,OAAO,CAAC,CAAC,OAAO,SAClF;AACF;;;;AAKA,SAAS,gBAAgB,eAA+B;CAStD,OAAO;EAPL,gBAAgB;EAChB,gBAAgB;EAChB,aAAa;EACb,eAAe;EACf,kBAAkB;EAClB,aAAa;CAER,EAAU,kBAAkB;AACrC;;;;AAKA,SAAS,+BAAuC;CAC9C,OAAO;;;;;;;AAOT;AAEA,SAAS,6BACP,UACA,UAAqC,CAAC,GAC9B;CAER,IADgB,OAAO,QAAQ,UAAU,WAAW,CAAC,CACjD,CAAA,CAAQ,WAAW,GACrB,OAAO;;;;;;;;CAUT,OAAO,qBAAqB,UAA4C,EACtE,aAAa,QAAQ,YACvB,CAAC;AACH;AAEA,SAAS,4BAAoC;CAC3C,OAAO;;;;;;;;;AAST;AAEA,SAAS,4BAA4B,UAAoC;CACvE,MAAM,UAAU,OAAO,QAAQ,UAAU,WAAW,CAAC,CAAC;CACtD,IAAI,QAAQ,WAAW,GACrB,OAAO;CAaT,OATmB,QAAQ,KAAK,CAAC,OAAO,SAAS;EAC/C,OAAO,oBAAoB,IAAI,UAAU;;;;;;CAM3C,CAEO,CAAA,CAAW,KAAK,MAAM;AAC/B;AAEA,SAAS,+BAA+B,UAAoC;CAC1E,OAAO;;0BAEiB,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE;;;AAG5D"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/consumer-plugin/index.ts"],"sourcesContent":["/**\n * Vite plugin for consuming SMRT packages\n * Solves virtual module resolution in downstream projects\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { DomainKnowledgeAgentSurface } from '@happyvertical/smrt-types';\nimport type { ConfigEnv, Plugin } from 'vite';\nimport {\n loadVerifiedSmrtGenerationSnapshot,\n type SmrtGenerationSnapshotOptions,\n} from '../generation-snapshot.js';\nimport { buildDomainKnowledgeManifest } from '../knowledge.js';\nimport { resolveFileKnowledgeConfig } from '../knowledge-config.js';\nimport { manifestExportCandidates } from '../manifest/package-manifest-exports.js';\nimport { generateDeclarations } from '../prebuild/index.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport { generateClientModule } from '../vite-plugin/generated-client.js';\nimport type { SmrtPluginApi } from '../vite-plugin/index.js';\nimport {\n clearGeneratedSvelteKitRouteFiles,\n reconcileSvelteKitRouteGitignore,\n type SvelteKitOptions,\n} from '../vite-plugin/sveltekit-generator.js';\nimport { canonicalSvelteKitPath } from '../vite-plugin/sveltekit-path.js';\nimport {\n activeProducerKnowledgeRoutePaths,\n activeSvelteKitRouteParticipants,\n assertNoSvelteKitRouteRootSymlinkConflict,\n assertSvelteKitRouteCoordinationComplete,\n contributeSvelteKitRoutes,\n expectedSvelteKitRouteOwners,\n markSvelteKitRouteParticipant,\n producerKnowledgeRoutePaths,\n revokeSvelteKitRoutes,\n} from '../vite-plugin/sveltekit-route-coordinator.js';\nimport {\n generateWebModule,\n isCollectionManifestClass,\n resolveCollectionItemObject,\n} from '../vite-plugin/web-collections.js';\nimport { publishArtifactFiles } from './artifact-publication.js';\n\nexport {\n loadVerifiedSmrtGenerationSnapshot,\n type SerializeSmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotArtifact,\n type SmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotView,\n serializeSmrtGenerationSnapshot,\n sha256SmrtGenerationSnapshot,\n} from '../generation-snapshot.js';\n\n/**\n * Loosely-typed view of an object definition as carried by an external\n * package's static manifest. The static manifests are read from JSON at the\n * package boundary, so only the fields this plugin consumes are typed; the\n * index signature preserves any additional fields (e.g. for spreads). This is\n * a structural superset of a manifest `SmartObjectDefinition` plus the\n * consumer-only `hasCollection` marker.\n */\ninterface ConsumerObjectDefinition {\n className?: string;\n packageName?: string;\n packageVersion?: string;\n qualifiedName?: string;\n importPath?: string;\n exportName?: string;\n collectionExportName?: string;\n hasCollection?: boolean;\n collection?: string;\n extends?: string;\n extendsQualified?: string;\n extendsTypeArg?: string;\n [key: string]: unknown;\n}\n\n/**\n * Aggregated manifest assembled by the consumer plugin from one or more\n * external package manifests. Loosely typed because the inputs originate from\n * JSON read at the package boundary.\n */\ninterface ConsumerManifest {\n version: string;\n timestamp: number;\n packageName?: string;\n packageVersion?: string;\n smrtDependencies?: string[];\n objects: Record<string, ConsumerObjectDefinition>;\n}\n\n/**\n * Minimal structural shape of a parsed `package.json` consumed here (name,\n * version, and the export map used to derive import paths). The index\n * signature keeps the remaining fields accessible.\n */\ninterface ConsumerPackageJson {\n name?: string;\n version?: string;\n main?: string;\n exports?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * SvelteKit route-hosting options for dependency models. Unlike `packages`,\n * `objects` is an HTTP exposure boundary: every entry must be an exact,\n * provider-qualified manifest key (for example, `@acme/widgets:Widget`).\n */\nexport interface SmrtConsumerSvelteKitOptions\n extends Partial<\n Pick<\n SvelteKitOptions,\n | 'routesDir'\n | 'configPath'\n | 'configFileName'\n | 'kebabRoutes'\n | 'changesRoute'\n | 'eventsRoute'\n | 'resourcesRoute'\n >\n > {\n objects: readonly string[];\n}\n\nexport interface SmrtConsumerOptions {\n /** SMRT packages to scan (e.g., ['@my-org/products', '@my-org/content']) */\n packages?: string[];\n /** Generate TypeScript declarations */\n generateTypes?: boolean;\n /** Output directory for generated types */\n typesDir?: string;\n /** Project root path (defaults to the current working directory) */\n projectRoot?: string;\n /**\n * Reuse an immutable, verified aggregated manifest instead of discovering\n * packages or writing `.smrt/manifest.json`. Registration and generated\n * types still consume the verified manifest.\n */\n generationSnapshot?: SmrtGenerationSnapshotOptions;\n /**\n * Consumer SvelteKit integration. `true` retains the historical compatibility\n * mode and does not generate dependency routes. Route hosting requires an\n * explicit, provider-qualified object allowlist.\n */\n svelteKit?: boolean | SmrtConsumerSvelteKitOptions;\n /**\n * Apply kebab-case to generated custom-method URL segments. This must match\n * the producer plugin's `svelteKit.kebabRoutes` setting. When explicit\n * consumer SvelteKit hosting is configured, its `kebabRoutes` value takes\n * precedence, including an explicit `false`.\n */\n kebabRoutes?: boolean;\n /** Use static types only (for federation builds) */\n staticTypes?: boolean;\n /** Disable file scanning */\n disableScanning?: boolean;\n}\n\n// Distinct resolved ids per plugin (#1795). smrtPlugin resolves\n// `@happyvertical/smrt-virt-*` to `\\0smrt:*`; if this consumer plugin also\n// resolved its `@smrt/*` specifiers to `\\0smrt:*` the two virtual modules would\n// share a rollup id, and in standalone/federation builds the consumer's\n// fallback `load` would non-deterministically win and shadow smrtPlugin's real\n// module. Namespacing the consumer ids (`\\0smrt-consumer:*`) keeps them\n// separate so each plugin only ever loads its own module.\nconst VIRTUAL_MODULES = {\n '@smrt/routes': 'smrt-consumer:routes',\n '@smrt/client': 'smrt-consumer:client',\n '@smrt/mcp': 'smrt-consumer:mcp',\n '@smrt/types': 'smrt-consumer:types',\n '@smrt/manifest': 'smrt-consumer:manifest',\n '@smrt/web': 'smrt-consumer:web',\n};\n\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION = 1;\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT = 'consumer-sveltekit-routes.json';\n\ninterface ConsumerSvelteKitRoutesArtifact {\n version: number;\n routesDir: string[];\n}\n\nfunction consumerSvelteKitRoutesArtifactPath(projectRoot: string): string {\n return path.join(projectRoot, '.smrt', CONSUMER_SVELTEKIT_ROUTES_ARTIFACT);\n}\n\n/** Persist only project-relative consumer route roots, never an output file list. */\nfunction canonicalConsumerRouteRoot(\n projectRoot: string,\n routesDir: string,\n): string {\n const root = path.resolve(projectRoot);\n const relative = path.relative(root, path.resolve(root, routesDir));\n if (\n !relative ||\n relative === '..' ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n throw new Error(\n `[smrt:consumer] svelteKit.routesDir must be a project-relative subdirectory (received ${JSON.stringify(routesDir)})`,\n );\n }\n return relative.split(path.sep).join('/');\n}\n\nfunction loadConsumerSvelteKitRouteRoots(projectRoot: string): string[] {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (!fs.existsSync(artifactPath)) return [];\n let parsed: ConsumerSvelteKitRoutesArtifact;\n try {\n parsed = JSON.parse(fs.readFileSync(artifactPath, 'utf-8'));\n } catch {\n throw new Error(\n `[smrt:consumer] Cannot read ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n if (\n parsed?.version !== CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION ||\n !Array.isArray(parsed.routesDir) ||\n parsed.routesDir.some((routesDir) => typeof routesDir !== 'string')\n ) {\n throw new Error(\n `[smrt:consumer] Invalid ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n return [...new Set(parsed.routesDir)].map((routesDir) =>\n canonicalConsumerRouteRoot(projectRoot, routesDir),\n );\n}\n\nfunction publishConsumerSvelteKitRouteRoots(\n projectRoot: string,\n routesDir: string[],\n): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n fs.mkdirSync(path.dirname(artifactPath), { recursive: true });\n publishArtifactFiles([\n {\n path: artifactPath,\n content: JSON.stringify(\n {\n version: CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION,\n routesDir: [...new Set(routesDir)].sort(),\n } satisfies ConsumerSvelteKitRoutesArtifact,\n null,\n 2,\n ),\n },\n ]);\n}\n\nfunction removeConsumerSvelteKitRouteRoots(projectRoot: string): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (fs.existsSync(artifactPath)) fs.unlinkSync(artifactPath);\n}\n\n/**\n * A hosting-to-hosting move can replace one configured root with another in a\n * fresh lifecycle. Validate every durable former root before the new target\n * journals or clears anything, otherwise a rejected move could alter the\n * prior generated surface before reconciliation notices the conflict.\n */\nasync function assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig: unknown,\n projectRoot: string,\n routesDir: readonly string[],\n env?: ConfigEnv,\n): Promise<void> {\n if (routesDir.length === 0) return;\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n const activeRoots = activeParticipants.map(\n (participant) => participant.routesDir,\n );\n for (const priorRoutesDir of routesDir) {\n assertNoSvelteKitRouteRootSymlinkConflict(\n canonicalSvelteKitPath(path.resolve(projectRoot, priorRoutesDir)),\n activeRoots,\n );\n }\n}\n\nasync function reconcileConsumerSvelteKitRouteRoots(\n lifecycle: object,\n userConfig: unknown,\n projectRoot: string,\n routesDir: string[],\n afterReconciled: () => void,\n env?: ConfigEnv,\n): Promise<void> {\n const remaining = new Set(routesDir);\n const reconcileOne = (routesDir: string) => {\n remaining.delete(routesDir);\n if (remaining.size === 0) afterReconciled();\n };\n\n if (remaining.size === 0) {\n afterReconciled();\n return;\n }\n\n for (const routesDir of [...remaining]) {\n const routeRoot = canonicalSvelteKitPath(\n path.resolve(projectRoot, routesDir),\n );\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n // The durable consumer inventory names roots, not individual handlers.\n // Check before every reconciliation branch, including an active parent\n // consumer that would otherwise compact a nested former root without a\n // sweep. A child symlink into a foreign active root makes that ownership\n // ambiguous, so retaining the inventory makes retry safe.\n assertNoSvelteKitRouteRootSymlinkConflict(\n routeRoot,\n activeParticipants.map((participant) => participant.routesDir),\n );\n const containingConsumer = activeParticipants.find(\n (participant) =>\n participant.owner === 'consumer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n // A current parent consumer root has already swept and regenerated this\n // former child root. Sweeping it again would remove the newly selected\n // handler before SvelteKit inventories it.\n if (containingConsumer) {\n reconcileOne(routesDir);\n continue;\n }\n const containingProducer = activeParticipants.find(\n (participant) =>\n participant.owner === 'producer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n if (containingProducer) {\n await revokeSvelteKitRoutes(\n lifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n containingProducer.projectRoot,\n containingProducer.routesDir,\n env,\n ),\n containingProducer.projectRoot,\n containingProducer.routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n const owners = await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routesDir,\n env,\n );\n if (owners.includes('producer')) {\n await revokeSvelteKitRoutes(\n lifecycle,\n owners,\n projectRoot,\n routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n clearGeneratedSvelteKitRouteFiles(\n routeRoot,\n producerKnowledgeRoutePaths(lifecycle),\n new Set(\n activeParticipants\n .map((participant) => participant.routesDir)\n .filter((activeRoot) => activeRoot !== routeRoot),\n ),\n );\n reconcileSvelteKitRouteGitignore(projectRoot, routesDir);\n reconcileOne(routesDir);\n }\n}\n\nfunction consumerRouteOptions(\n value: SmrtConsumerOptions['svelteKit'],\n): SmrtConsumerSvelteKitOptions | undefined {\n if (!value || value === true) return undefined;\n if (!Array.isArray(value.objects) || value.objects.length === 0) {\n throw new Error(\n '[smrt:consumer] svelteKit.objects must list at least one provider-qualified object reference',\n );\n }\n for (const objectRef of value.objects) {\n if (typeof objectRef !== 'string' || !objectRef.includes(':')) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects entries must be provider-qualified (received ${JSON.stringify(objectRef)})`,\n );\n }\n }\n return value;\n}\n\nfunction consumerUtilityOption<T extends { enabled?: boolean }>(\n value: T | undefined,\n): T | { enabled: false } {\n return value?.enabled === true ? value : { enabled: false };\n}\n\nfunction consumerObjectRef(\n manifestKey: string,\n objectDef: ConsumerObjectDefinition,\n): string | undefined {\n if (manifestKey.includes(':')) return manifestKey;\n if (objectDef.qualifiedName?.includes(':')) return objectDef.qualifiedName;\n if (objectDef.packageName && objectDef.className) {\n return `${objectDef.packageName}:${objectDef.className}`;\n }\n return undefined;\n}\n\n/**\n * Select exactly the dependency objects that a consumer explicitly hosts.\n * Validation completes before the generator clears its managed files, so an\n * invalid deployment cannot erase a previously generated route surface.\n */\nfunction selectConsumerRouteManifest(\n manifest: ConsumerManifest,\n options: SmrtConsumerSvelteKitOptions,\n): SmartObjectManifest {\n const entriesByRef = new Map<string, [string, ConsumerObjectDefinition]>();\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const objectRef = consumerObjectRef(manifestKey, objectDef);\n if (objectRef) entriesByRef.set(objectRef, [manifestKey, objectDef]);\n }\n\n const selected = new Set<string>();\n const objects: Record<string, ConsumerObjectDefinition> = {};\n for (const objectRef of options.objects) {\n const entry = entriesByRef.get(objectRef);\n if (!entry) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects references unknown dependency object ${JSON.stringify(objectRef)}`,\n );\n }\n if (selected.has(objectRef)) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects contains duplicate object ${JSON.stringify(objectRef)}`,\n );\n }\n selected.add(objectRef);\n const [, objectDef] = entry;\n objects[objectRef] = { ...objectDef, qualifiedName: objectRef };\n }\n\n const sourceManifest = manifest as unknown as SmartObjectManifest;\n // Use the generator's canonical ancestry resolver so a collection subclass\n // inherits the selected item's identity through any number of ancestors.\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const candidate = objectDef as unknown as SmartObjectDefinition;\n if (!isCollectionManifestClass(sourceManifest, candidate)) continue;\n const item = resolveCollectionItemObject(sourceManifest, candidate);\n const itemEntry = item\n ? Object.entries(manifest.objects).find(\n ([, value]) => (value as unknown) === item,\n )\n : undefined;\n const itemRef = itemEntry\n ? consumerObjectRef(itemEntry[0], itemEntry[1])\n : undefined;\n if (!itemRef || !selected.has(itemRef)) continue;\n const collectionRef = consumerObjectRef(manifestKey, objectDef);\n if (collectionRef) {\n objects[collectionRef] = { ...objectDef, qualifiedName: collectionRef };\n }\n }\n\n return {\n ...manifest,\n // The generated route config imports this full registration entry point so\n // SSR retains every consumer provider, while only `objects` reach routing.\n // `smrtDependencies` is optional in verified snapshots, so derive this\n // generator signal from the immutable full manifest rather than treating\n // absent metadata as an empty provider inventory.\n smrtDependencies: [\n ...new Set(\n Object.values(manifest.objects)\n .map((objectDef) => objectDef.packageName)\n .filter(\n (packageName): packageName is string =>\n typeof packageName === 'string' &&\n packageName !== manifest.packageName,\n ),\n ),\n ].sort(),\n objects,\n } as unknown as SmartObjectManifest;\n}\n\n/**\n * Consumer plugin for projects that use SMRT packages\n */\nexport function smrtConsumer(options: SmrtConsumerOptions = {}): Plugin {\n const {\n packages = [],\n generateTypes = true,\n typesDir = 'src/types/smrt-generated',\n projectRoot = process.cwd(),\n generationSnapshot,\n disableScanning = false,\n kebabRoutes = false,\n } = options;\n const consumerSvelteKit = consumerRouteOptions(options.svelteKit);\n // Hosted routes, the generated client, and web tool definitions must expose\n // the same custom-action URLs. Nested consumer SvelteKit hosting owns this\n // policy when present, including an explicit false override.\n const effectiveKebabRoutes = consumerSvelteKit?.kebabRoutes ?? kebabRoutes;\n\n let smrtPackages: string[] = [];\n let typeManifest: ConsumerManifest | null = null;\n let typesGenerated = false;\n let producerApi: SmrtPluginApi | undefined;\n let routeLifecycleConfig: object | undefined;\n\n function loadGenerationSnapshot(): ConsumerManifest {\n if (!generationSnapshot) {\n throw new Error('[smrt:consumer] Generation snapshot is not configured');\n }\n return loadVerifiedSmrtGenerationSnapshot<ConsumerManifest>(\n generationSnapshot,\n projectRoot,\n 'dependencies',\n );\n }\n\n /**\n * Resolve the packages to aggregate, and whether that list was asserted by\n * the consumer's config. An explicit list fails closed when a package\n * yields no manifest; a heuristically discovered one only warns.\n */\n async function resolveConsumerPackages(): Promise<{\n names: string[];\n explicit: boolean;\n }> {\n if (packages.length === 0 && !disableScanning) {\n return {\n names: await discoverSmrtPackages(projectRoot),\n explicit: false,\n };\n }\n return { names: packages, explicit: packages.length > 0 };\n }\n\n async function generateConfigTypes(\n manifest?: ConsumerManifest,\n ): Promise<void> {\n if (!generateTypes || typesGenerated) return;\n\n if (manifest) {\n typeManifest = manifest;\n } else if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n } else {\n const resolved = await resolveConsumerPackages();\n typeManifest = await aggregateTypeManifests(resolved.names, projectRoot, {\n explicit: resolved.explicit,\n });\n }\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n\n const plugin: Plugin = {\n name: 'smrt-consumer',\n\n // SvelteKit inventories routes in its config hook. Run before it so a\n // clean consumer build sees the explicit dependency routes on its first\n // invocation, even when sveltekit() appears first in vite.config.\n enforce: 'pre',\n\n config: {\n order: 'pre',\n async handler(userConfig, env) {\n const routeLifecycle = env ?? userConfig;\n routeLifecycleConfig = routeLifecycle;\n const previousConsumerRouteRoots =\n loadConsumerSvelteKitRouteRoots(projectRoot);\n if (consumerSvelteKit) {\n await assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n env,\n );\n const routePackages = await resolveConsumerPackages();\n const routeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : await aggregateTypeManifests(routePackages.names, projectRoot, {\n explicit: routePackages.explicit,\n });\n const hostedManifest = selectConsumerRouteManifest(\n routeManifest,\n consumerSvelteKit,\n );\n const routesDir = canonicalConsumerRouteRoot(\n projectRoot,\n consumerSvelteKit.routesDir ?? 'src/routes/api',\n );\n const reservedRoutePaths = await activeProducerKnowledgeRoutePaths(\n userConfig,\n projectRoot,\n env,\n );\n const routeOptions = {\n enabled: true,\n routesDir,\n objectsDir: 'src/lib/objects',\n configPath: consumerSvelteKit.configPath ?? 'src/lib/server',\n configFileName: consumerSvelteKit.configFileName ?? 'smrt.ts',\n kebabRoutes: effectiveKebabRoutes,\n // These span a model set rather than one selected object, so new\n // consumer hosting starts fail-closed. Callers can opt in with the\n // generator's established option shapes.\n changesRoute: consumerUtilityOption(consumerSvelteKit.changesRoute),\n eventsRoute: consumerUtilityOption(consumerSvelteKit.eventsRoute),\n resourcesRoute: consumerUtilityOption(\n consumerSvelteKit.resourcesRoute,\n ),\n rejectRouteCollisions: true,\n };\n let ownershipJournaled = false;\n let reconciliationScheduled = false;\n await contributeSvelteKitRoutes(\n routeLifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routeOptions.routesDir,\n env,\n ),\n projectRoot,\n {\n owner: 'consumer',\n routeManifest: hostedManifest,\n semanticManifest: routeManifest as unknown as SmartObjectManifest,\n options: routeOptions,\n reservedRoutePaths,\n beforeCleanup: async () => {\n // Route selection and collision checks have succeeded, but no\n // generated output has changed. SvelteKit type checking still\n // runs after this config hook and needs these declarations.\n await generateConfigTypes(routeManifest);\n if (ownershipJournaled) return;\n ownershipJournaled = true;\n // Preflight has succeeded but no generated output has changed.\n // Keep both roots until old-root reconciliation commits.\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n ...previousConsumerRouteRoots,\n routesDir,\n ]);\n },\n afterGenerate: async () => {\n if (reconciliationScheduled) return;\n reconciliationScheduled = true;\n const priorRoots = previousConsumerRouteRoots.filter(\n (previousRoot) => previousRoot !== routesDir,\n );\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n priorRoots,\n () =>\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n routesDir,\n ]),\n env,\n );\n },\n },\n );\n } else {\n // Legacy/non-hosting SvelteKit consumers have no route preflight,\n // but still need physical virtual-module declarations before their\n // SvelteKit typecheck reaches Vite's later buildStart lifecycle.\n await generateConfigTypes();\n if (previousConsumerRouteRoots.length > 0) {\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n () => removeConsumerSvelteKitRouteRoots(projectRoot),\n env,\n );\n }\n }\n return {\n build: {\n rollupOptions: {\n // Runtime registration evaluates provider entry points so their\n // exact constructors can be registered. Leave optional native\n // provider binaries to Node instead of parsing them as JavaScript.\n external: [/\\.node$/],\n },\n },\n };\n },\n },\n\n configResolved(resolvedConfig) {\n if (consumerSvelteKit && routeLifecycleConfig) {\n assertSvelteKitRouteCoordinationComplete(routeLifecycleConfig);\n }\n producerApi = (resolvedConfig.plugins ?? []).find(\n (plugin) => plugin?.name === 'smrt-auto-service',\n )?.api as SmrtPluginApi | undefined;\n },\n\n async buildStart() {\n console.log('[smrt:consumer] Initializing SMRT consumer plugin');\n\n if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n console.log(\n `[smrt:consumer] Reusing verified generation snapshot (${generationSnapshot.provenance})`,\n );\n await generateRegistrationFile(typeManifest, projectRoot);\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n return;\n }\n\n // Discover SMRT packages if not explicitly specified\n const resolvedPackages = await resolveConsumerPackages();\n smrtPackages = resolvedPackages.names;\n\n if (smrtPackages.length > 0) {\n console.log(\n `[smrt:consumer] Found SMRT packages: ${smrtPackages.join(', ')}`,\n );\n\n // Aggregate type manifests from discovered packages\n typeManifest = await aggregateTypeManifests(smrtPackages, projectRoot, {\n explicit: resolvedPackages.explicit,\n });\n // Wait before reading .smrt/manifest.json: a producer's parallel\n // buildStart writes its current local manifest after scanning. Reading\n // first could merge an older local manifest with a newer surface.\n const agentSurface = producerApi\n ? await producerApi.resolveKnowledgeAgentSurface()\n : undefined;\n\n // Save aggregated manifest for CLI discovery\n await saveAggregatedManifest(\n typeManifest,\n projectRoot,\n producerApi?.resolveKnowledgeConfig,\n agentSurface,\n );\n\n // Generate registration file for CLI class loading\n await generateRegistrationFile(typeManifest, projectRoot);\n\n // Generate types if requested\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n } else {\n console.log('[smrt:consumer] No SMRT packages found');\n typeManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n },\n\n resolveId(id, _importer) {\n // Resolve virtual modules to generated type declarations\n if (id in VIRTUAL_MODULES) {\n // Generated declarations are ambient TypeScript declarations, not\n // executable JavaScript. Vite must always load the consumer runtime\n // module after default type generation writes them.\n if (id !== '@smrt/types') {\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n\n const typeFileName = getTypeFileName(id);\n const typePath = path.join(projectRoot, typesDir, typeFileName);\n\n // If types file exists, resolve to it\n if (fs.existsSync(typePath)) {\n return typePath;\n }\n\n // Otherwise use virtual module ID for runtime resolution\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n return null;\n },\n\n async load(id) {\n // Handle virtual modules if types aren't available\n const cleanId = id.startsWith('\\0') ? id.slice(1) : id;\n\n if (!typeManifest) {\n typeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n\n switch (cleanId) {\n case 'smrt-consumer:routes':\n return generateFallbackRoutesModule();\n\n case 'smrt-consumer:client':\n return generateFallbackClientModule(typeManifest, {\n kebabRoutes: effectiveKebabRoutes,\n });\n\n case 'smrt-consumer:mcp':\n return generateFallbackMcpModule();\n\n case 'smrt-consumer:types':\n return generateFallbackTypesModule(typeManifest);\n\n case 'smrt-consumer:manifest':\n return generateFallbackManifestModule(typeManifest);\n\n case 'smrt-consumer:web':\n return generateWebModule(\n typeManifest as unknown as SmartObjectManifest,\n {\n kebabRoutes: effectiveKebabRoutes,\n },\n );\n\n default:\n return null;\n }\n },\n };\n markSvelteKitRouteParticipant(\n plugin,\n 'consumer',\n Boolean(consumerSvelteKit),\n consumerSvelteKit?.routesDir ?? 'src/routes/api',\n undefined,\n () => projectRoot,\n );\n return plugin;\n}\n\n/**\n * Discover SMRT packages from a consumer app's dependencies.\n *\n * Intentional split (#1579): this **consumer-plugin** path is async and\n * resolves SMRT packages from the downstream app's `package.json` dependency\n * names (`@have/`/`smrt` heuristic + `hasSmrtManifest` probe) inside the Vite\n * consumer plugin. It is deliberately separate from the build-time\n * `discoverSmrtPackages()` in `src/manifest/discover-smrt-packages.ts` — a\n * synchronous, lockfile-cached `node_modules` manifest scan used for manifest\n * generation. Different inputs, contexts, and lifecycles, not duplicated logic.\n */\nasync function discoverSmrtPackages(projectRoot: string): Promise<string[]> {\n const packages: string[] = [];\n const nodeModulesPath = path.join(projectRoot, 'node_modules');\n\n if (!fs.existsSync(nodeModulesPath)) {\n return packages;\n }\n\n try {\n // Check package.json for workspace dependencies\n const packageJsonPath = path.join(projectRoot, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Look for packages that likely contain SMRT objects\n for (const [name, version] of Object.entries(allDeps)) {\n if (\n typeof version === 'string' &&\n (name.includes('smrt') ||\n name.includes('@have/') ||\n (await hasSmrtManifest(nodeModulesPath, name)))\n ) {\n packages.push(name);\n }\n }\n }\n } catch (error) {\n console.warn('[smrt:consumer] Error discovering packages:', error);\n }\n\n return packages;\n}\n\n/**\n * Manifest locations probed for a consumed package, in preference order.\n *\n * The package's own `package.json#exports` map comes first: it is the\n * published contract for where the manifest lives, and a package whose build\n * emits outside this framework's conventional layout (for example\n * `\"./manifest.json\": \"./dist/lib/manifest.json\"`) is otherwise skipped\n * entirely (issue #2923). The conventional paths remain as a fallback for\n * packages that ship a manifest without exporting a subpath for it.\n */\nfunction legacyStaticManifestPath(packageDir: string): string {\n return path.join(packageDir, 'dist', 'manifest', 'static-manifest.js');\n}\n\nfunction packageManifestCandidates(\n packageDir: string,\n packageJson?: ConsumerPackageJson,\n): string[] {\n return [\n ...manifestExportCandidates(packageDir, packageJson),\n legacyStaticManifestPath(packageDir),\n path.join(packageDir, 'dist', 'manifest.json'),\n path.join(packageDir, 'manifest.json'),\n ];\n}\n\n/**\n * Whether a dependency looks like a SMRT package, for the name-heuristic\n * discovery path only.\n *\n * This decides whether a package this framework knows nothing about is pulled\n * into aggregation at all, so mere existence of a manifest-shaped file is not\n * enough: `manifest.json` at a package root or `dist/manifest.json` is a\n * common artifact of unrelated tooling (Vite build manifests, PWA and\n * extension manifests). A false positive would announce a stranger under\n * \"Found SMRT packages\", tell the user to publish a manifest for a package\n * that has nothing to do with SMRT, and — for a JS candidate — evaluate that\n * dependency's module inside the build.\n *\n * A JSON candidate is therefore confirmed by parsing it and requiring\n * `moduleType: 'smrt'`, matching what build-time discovery requires. A JS\n * candidate cannot be identified without importing it, which is the thing\n * being avoided, so only the historical `dist/manifest/static-manifest.js`\n * location counts — exactly the probe this function used before #2923.\n */\nasync function hasSmrtManifest(\n nodeModulesPath: string,\n packageName: string,\n): Promise<boolean> {\n const packagePath = path.join(nodeModulesPath, packageName);\n const legacyStaticManifest = legacyStaticManifestPath(packagePath);\n\n for (const manifestPath of packageManifestCandidates(packagePath)) {\n if (!fs.existsSync(manifestPath)) continue;\n\n if (!manifestPath.endsWith('.json')) {\n if (manifestPath === legacyStaticManifest) return true;\n continue;\n }\n\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as {\n moduleType?: string;\n };\n if (manifest?.moduleType === 'smrt') return true;\n } catch {\n // Not a readable SMRT manifest; keep probing the remaining candidates.\n }\n }\n\n return false;\n}\n\n/**\n * Aggregate type manifests from multiple packages.\n *\n * A package that yields no usable manifest is never dropped silently\n * (issue #2923): an explicitly listed package fails the build, and a\n * heuristically discovered one warns by name. Silence here surfaces much\n * later as missing tables, routes, and generated types with nothing in the\n * build log to connect them to the package that was skipped.\n *\n * @param packages - Package names to aggregate.\n * @param projectRoot - Consumer project root containing `node_modules`.\n * @param options - `explicit` marks a caller-supplied `packages` list, whose\n * entries are assertions rather than guesses and therefore fail closed.\n */\nasync function aggregateTypeManifests(\n packages: string[],\n projectRoot: string,\n options: { explicit?: boolean } = {},\n): Promise<ConsumerManifest> {\n const aggregatedManifest: ConsumerManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n smrtDependencies: [...packages],\n objects: {},\n };\n\n const unresolvedPackages: string[] = [];\n\n for (const packageName of packages) {\n let loadedManifest = false;\n try {\n const packageDir = path.join(projectRoot, 'node_modules', packageName);\n\n // Load package.json for version and export information\n const packageJsonPath = path.join(packageDir, 'package.json');\n let packageJson: ConsumerPackageJson;\n try {\n const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContent) as ConsumerPackageJson;\n } catch {\n console.warn(\n `[smrt:consumer] Could not read package.json for ${packageName}`,\n );\n unresolvedPackages.push(packageName);\n continue;\n }\n\n // Try the package's declared manifest export first, then convention.\n const manifestCandidates = packageManifestCandidates(\n packageDir,\n packageJson,\n );\n\n for (const manifestPath of manifestCandidates) {\n if (fs.existsSync(manifestPath)) {\n // Import or read the manifest. A candidate that exists but cannot be\n // read, parsed, or imported must not end the search: the export map\n // is probed before the conventional paths, so letting one stale or\n // malformed exported target throw out of this loop would take away\n // the `dist/manifest.json` fallback a package used to load through.\n let manifest: Partial<ConsumerManifest> | undefined;\n try {\n if (manifestPath.endsWith('.js')) {\n const manifestModule = await import(manifestPath);\n manifest =\n manifestModule.staticManifest || manifestModule.default;\n } else {\n const manifestContent = fs.readFileSync(manifestPath, 'utf-8');\n manifest = JSON.parse(\n manifestContent,\n ) as Partial<ConsumerManifest>;\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Could not load manifest candidate ${manifestPath} for ${packageName}; trying the next location:`,\n error,\n );\n continue;\n }\n\n if (manifest?.objects) {\n console.log(\n `[smrt:consumer] Loaded manifest from ${packageName} (${Object.keys(manifest.objects).length} objects)`,\n );\n\n // ENHANCED: Preserve package metadata for each object\n for (const [objectName, objectDef] of Object.entries(\n manifest.objects,\n )) {\n const def = objectDef;\n\n aggregatedManifest.objects[objectName] = {\n ...def,\n // Ensure package metadata is preserved/set\n packageName:\n def.packageName || manifest.packageName || packageName,\n packageVersion:\n def.packageVersion ||\n manifest.packageVersion ||\n packageJson.version,\n // Add fallback import paths if missing\n importPath: def.importPath || determineImportPath(packageJson),\n exportName: def.exportName || def.className || objectName,\n collectionExportName:\n def.collectionExportName ||\n `${def.className || objectName}Collection`,\n };\n }\n\n loadedManifest = true;\n break; // Use first found manifest for this package\n }\n }\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Error loading manifest from ${packageName}:`,\n error,\n );\n }\n\n if (!loadedManifest) {\n unresolvedPackages.push(packageName);\n }\n }\n\n if (unresolvedPackages.length > 0) {\n const named = unresolvedPackages.join(', ');\n if (options.explicit) {\n throw new Error(\n `[smrt:consumer] No SMRT manifest could be resolved for ${named}. ` +\n 'Listed packages must publish a manifest through ' +\n 'package.json#exports (\"./manifest.json\") or at dist/manifest.json, ' +\n 'dist/manifest/static-manifest.js, or manifest.json. Build the ' +\n 'package, or remove it from smrtConsumer({ packages }).',\n );\n }\n // Discovery matches on dependency name, so a hit here is a guess: some\n // matched packages (UI/runtime helpers) legitimately have no objects.\n // Name them anyway — a missing manifest is otherwise invisible until the\n // objects turn up absent from routes and schema.\n console.warn(\n `[smrt:consumer] No SMRT manifest could be resolved for ${named}; ` +\n 'contributing 0 objects. If the package provides SMRT objects, ' +\n 'publish its manifest through package.json#exports (\"./manifest.json\").',\n );\n }\n\n return aggregatedManifest;\n}\n\n/**\n * Determine import path from package.json\n */\nfunction determineImportPath(packageJson: ConsumerPackageJson): string {\n const packageName = packageJson.name;\n\n if (!packageName) {\n throw new Error('Package name not found in package.json');\n }\n\n // Strategy 1: Check for specific exports\n if (packageJson.exports) {\n // Check for objects export\n if (packageJson.exports['./objects']) {\n return `${packageName}/objects`;\n }\n\n // Check for main export\n const mainExport = packageJson.exports['.'];\n if (mainExport) {\n // Handle conditional exports\n if (typeof mainExport === 'object' && mainExport !== null) {\n const conditional = mainExport as Record<string, unknown>;\n if (conditional.import) {\n return packageName;\n }\n if (conditional.default) {\n return packageName;\n }\n }\n return packageName;\n }\n }\n\n // Strategy 2: Check main field\n if (packageJson.main) {\n return packageName;\n }\n\n // Strategy 3: Fallback to package name\n return packageName;\n}\n\n/**\n * Save aggregated manifest to .smrt/manifest.json for CLI discovery.\n *\n * Merge-preserving: `smrtPlugin()` writes the project's own scanned objects\n * to the same file (`writeLocalManifest`, issue #963), and both writes happen\n * in parallel `buildStart` hooks — so a plain overwrite here would clobber\n * the local objects whenever this plugin's write lands last (issue #1760\n * review). Local field metadata would then silently vanish from CLI schema\n * commands and from server runtimes that seed `.smrt/manifest.json`, dropping\n * domain columns on write. This function therefore only ADDS/refreshes the\n * external-package entries it owns and preserves everything else already in\n * the file (including the top-level `packageName` the local write sets).\n */\nasync function saveAggregatedManifest(\n manifest: ConsumerManifest,\n projectRoot: string,\n resolveKnowledgeConfig?: SmrtPluginApi['resolveKnowledgeConfig'],\n agentSurface?: DomainKnowledgeAgentSurface,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const manifestPath = path.join(smrtDir, 'manifest.json');\n\n try {\n // Create .smrt directory if it doesn't exist\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Merge with whatever is on disk: existing entries (typically the local\n // project's objects written by smrtPlugin) are preserved; aggregated\n // external entries win for the qualified names this plugin owns.\n let merged: ConsumerManifest = manifest;\n if (fs.existsSync(manifestPath)) {\n try {\n const existing = JSON.parse(\n fs.readFileSync(manifestPath, 'utf-8'),\n ) as Partial<ConsumerManifest>;\n if (existing && typeof existing.objects === 'object') {\n merged = {\n ...existing,\n ...manifest,\n // The aggregated manifest carries no packageName; keep the local\n // project's (used as the manifest cache key at runtime).\n ...(existing.packageName\n ? { packageName: existing.packageName }\n : {}),\n objects: { ...existing.objects, ...manifest.objects },\n };\n }\n } catch {\n // Unreadable/corrupt existing file — fall back to a plain write.\n }\n }\n\n // smrtPlugin writes the local knowledge artifact before this consumer\n // plugin merges external package entries into the same manifest. Refresh\n // the artifact from the merged manifest so its source hash always names\n // the manifest that CLI discovery and server runtimes actually consume.\n // The consumer deliberately does not load the scanner. Only carry a\n // surface from the current producer scan: a prior artifact can describe\n // declarations that have since changed while retaining the same path.\n // Re-hashing that current path under a stale declaration would make an\n // incorrect agent contract look fresh.\n const knowledgePath = path.join(smrtDir, 'smrt-knowledge.json');\n const packageJsonPath = path.join(projectRoot, 'package.json');\n const packageJson = fs.existsSync(packageJsonPath)\n ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n : undefined;\n const knowledgeConfig = resolveKnowledgeConfig\n ? await resolveKnowledgeConfig(merged as unknown as SmartObjectManifest)\n : await resolveFileKnowledgeConfig(\n projectRoot,\n merged.packageName ?? packageJson?.name,\n );\n if (knowledgeConfig.enabled === false) {\n publishArtifactFiles([\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n return;\n }\n const knowledge = buildDomainKnowledgeManifest({\n manifest: merged as unknown as SmartObjectManifest,\n rootDir: projectRoot,\n packageJson,\n manifestPath,\n config: knowledgeConfig,\n agentSurface,\n });\n // Stage both artifacts before replacing either. Renames are individually\n // atomic; if a synchronous later rename fails, restore every earlier\n // replacement. A process crash between renames cannot be made pair-atomic\n // with ordinary filesystem operations, so the next generation remains the\n // freshness repair path for that distinct failure mode.\n publishArtifactFiles([\n { path: knowledgePath, content: JSON.stringify(knowledge, null, 2) },\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n\n console.log(\n `[smrt:consumer] Saved aggregated manifest to .smrt/manifest.json (${Object.keys(merged.objects).length} objects)`,\n );\n } catch (error) {\n throw new Error('[smrt:consumer] Failed to save aggregated manifest', {\n cause: error,\n });\n }\n}\n\n/**\n * Generate registration file for CLI class loading\n *\n * Creates .smrt/register.js with static imports and registrations\n * for all external SMRT objects discovered during build.\n */\nasync function generateRegistrationFile(\n manifest: ConsumerManifest,\n projectRoot: string,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const registerPath = path.join(smrtDir, 'register.js');\n\n // Bind every imported symbol to a generated local name. Aggregated manifests\n // may contain same-named exports from different packages (and may list a\n // collection both beside its object and as its own manifest entry), so using\n // provider export names as local bindings can produce invalid duplicate\n // imports in a production consumer bundle.\n const importBindings = new Map<string, string>();\n const importsByPath = new Map<string, Map<string, string>>();\n let nextImportBinding = 0;\n const getImportBinding = (importPath: string, exportName: string): string => {\n const key = `${importPath}\\0${exportName}`;\n const existing = importBindings.get(key);\n if (existing) return existing;\n const binding = `__smrt_consumer_${nextImportBinding++}`;\n importBindings.set(key, binding);\n const specifiers =\n importsByPath.get(importPath) ?? new Map<string, string>();\n specifiers.set(exportName, binding);\n importsByPath.set(importPath, specifiers);\n return binding;\n };\n\n const registrations: string[] = [];\n const registrationManifests: Record<string, ConsumerManifest> = {};\n let importedEntryCount = 0;\n let registeredObjectCount = 0;\n\n const manifestObjects = manifest.objects;\n const manifestObjectLookup = new Map<string, ConsumerObjectDefinition>();\n for (const [key, def] of Object.entries(manifestObjects)) {\n const candidate = def;\n const lookupKeys = [\n key,\n key.includes(':') ? key.split(':').pop() : undefined,\n candidate.qualifiedName,\n candidate.className,\n candidate.exportName,\n ];\n\n for (const lookupKey of lookupKeys) {\n if (lookupKey && !manifestObjectLookup.has(lookupKey)) {\n manifestObjectLookup.set(lookupKey, candidate);\n }\n }\n }\n\n const collectionClassMemo = new WeakMap<object, boolean>();\n\n const isCollectionClass = (\n def: ConsumerObjectDefinition | undefined,\n seen = new Set<string>(),\n ): boolean => {\n if (!def || typeof def !== 'object') {\n return false;\n }\n\n const cached = collectionClassMemo.get(def);\n if (cached !== undefined) {\n return cached;\n }\n\n if (\n def?.extends === 'SmrtCollection' ||\n def?.extendsTypeArg !== undefined\n ) {\n collectionClassMemo.set(def, true);\n return true;\n }\n\n const parentName = def?.extendsQualified || def?.extends;\n if (!parentName || seen.has(parentName)) {\n collectionClassMemo.set(def, false);\n return false;\n }\n seen.add(parentName);\n\n const parentDef = manifestObjectLookup.get(parentName);\n const isCollection = parentDef ? isCollectionClass(parentDef, seen) : false;\n collectionClassMemo.set(def, isCollection);\n\n return isCollection;\n };\n\n for (const [objectName, objectDef] of Object.entries(manifestObjects)) {\n const def = objectDef;\n\n // Skip local objects (they're imported from local entry point)\n if (!def.packageName || def.packageName === manifest.packageName) {\n continue;\n }\n\n const importPath = def.importPath || def.packageName;\n const exportName = def.exportName || def.className || objectName;\n const collectionExportName = def.collectionExportName;\n const hasCollection = def.hasCollection; // Check if collection class actually exists\n const tableName = def.collection || objectName.toLowerCase();\n\n const exportBinding = getImportBinding(importPath, exportName);\n const collectionBinding =\n hasCollection && collectionExportName\n ? getImportBinding(importPath, collectionExportName)\n : undefined;\n importedEntryCount++;\n\n if (isCollectionClass(def)) {\n continue;\n }\n\n const logicalName = def.className || exportName;\n registrationManifests[objectName] = {\n ...manifest,\n packageName: def.packageName,\n packageVersion: def.packageVersion || manifest.packageVersion,\n objects: { [objectName]: def },\n };\n\n // Import evaluation triggers the provider decorator first. The explicit\n // constructor/package/key tuple then promotes that exact constructor with\n // its isolated manifest, which is stable across Rollup name deconfliction.\n registrations.push(\n `if (${exportBinding}) ObjectRegistry.register(${exportBinding}, { name: ${JSON.stringify(logicalName)}, packageName: ${JSON.stringify(def.packageName)}, _manifest: smrtRegistrationManifests[${JSON.stringify(objectName)}], _manifestKey: ${JSON.stringify(objectName)} });`,\n );\n\n // Only register collection if it exists\n if (collectionBinding) {\n registrations.push(\n `if (${collectionBinding}) ObjectRegistry.registerCollection('${tableName}', ${collectionBinding});`,\n );\n }\n\n registeredObjectCount++;\n }\n\n // Skip generation if no external entries\n if (importedEntryCount === 0) {\n console.log('[smrt:consumer] No external entries - skipping register.js');\n return;\n }\n\n const registeredObjectLabel =\n registeredObjectCount === 1 ? 'object' : 'objects';\n const sortedImports = Array.from(importsByPath.entries()).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n const imports = sortedImports.map(\n ([importPath], index) =>\n `import * as __smrt_provider_${index} from '${importPath}';`,\n );\n const importDeclarations = sortedImports.flatMap(([, specifiers], index) =>\n Array.from(specifiers.entries())\n .sort(([left], [right]) => left.localeCompare(right))\n .map(\n ([exportName, binding]) =>\n `const ${binding} = getSmrtExport(__smrt_provider_${index}, ${JSON.stringify(exportName)});`,\n ),\n );\n const registrationManifestLiteral = JSON.stringify(\n JSON.stringify(registrationManifests),\n );\n\n // Generate file content\n const content = `/**\n * Auto-generated by @happyvertical/smrt-core/consumer-plugin\n * DO NOT EDIT - This file is regenerated on every build\n *\n * Registers SMRT objects from external packages for CLI discovery.\n * Generated at: ${new Date().toISOString()}\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n${imports.join('\\n')}\n\n/**\n * @param {Record<string, unknown>} provider\n * @param {string} exportName\n * @returns {any}\n */\nconst getSmrtExport = (provider, exportName) =>\n typeof provider[exportName] === 'function' ? provider[exportName] : undefined;\n${importDeclarations.join('\\n')}\n\nconst smrtRegistrationManifests = JSON.parse(${registrationManifestLiteral});\n\n// Register all objects (executed during module evaluation)\n${registrations.join('\\n')}\n\nexport function registerAll() {\n // Objects are already registered during module evaluation\n console.log('[smrt:register] Registered ${registeredObjectCount} external ${registeredObjectLabel}');\n}\n`;\n\n // Create .smrt directory if needed\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Write registration file\n fs.writeFileSync(registerPath, content, 'utf-8');\n\n console.log(\n `[smrt:consumer] Generated .smrt/register.js with ${importedEntryCount} external entries (${registeredObjectCount} registered ${registeredObjectLabel})`,\n );\n}\n\n/**\n * Generate project-specific types\n */\nasync function generateProjectTypes(\n typeManifest: ConsumerManifest,\n typesDir: string,\n projectRoot: string,\n): Promise<void> {\n if (!typeManifest || Object.keys(typeManifest.objects).length === 0) {\n console.log(\n '[smrt:consumer] No SMRT objects found, skipping type generation',\n );\n return;\n }\n\n await generateDeclarations({\n // The aggregated manifest is a runtime SMRT manifest assembled from external\n // package manifests; it is intentionally typed loosely at the JSON boundary,\n // so narrow it to the declaration generator's strict manifest shape here.\n manifest: typeManifest as unknown as SmartObjectManifest,\n outDir: typesDir,\n projectRoot,\n includeVirtualModules: true,\n includeObjectTypes: true,\n });\n\n console.log(\n `[smrt:consumer] Generated types for ${Object.keys(typeManifest.objects).length} objects`,\n );\n}\n\n/**\n * Get type file name for virtual module\n */\nfunction getTypeFileName(virtualModule: string): string {\n const moduleMap: Record<string, string> = {\n '@smrt/routes': 'smrt-routes.d.ts',\n '@smrt/client': 'smrt-client.d.ts',\n '@smrt/mcp': 'smrt-mcp.d.ts',\n '@smrt/types': 'smrt-types.d.ts',\n '@smrt/manifest': 'smrt-manifest.d.ts',\n '@smrt/web': 'smrt-web.d.ts',\n };\n return moduleMap[virtualModule] || 'smrt-unknown.d.ts';\n}\n\n/**\n * Fallback modules for when types aren't available\n */\nfunction generateFallbackRoutesModule(): string {\n return `\n// Fallback routes module\nexport function setupRoutes(app) {\n console.warn('[smrt:consumer] No routes available - SMRT packages may not be properly configured');\n}\nexport default setupRoutes;\n`;\n}\n\nfunction generateFallbackClientModule(\n manifest: ConsumerManifest,\n options: { kebabRoutes?: boolean } = {},\n): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `\n// Fallback client module\nexport function createClient(basePath = '/api/v1') {\n console.warn('[smrt:consumer] No API client available - SMRT packages may not be properly configured');\n return {};\n}\nexport default createClient;\n`;\n }\n\n return generateClientModule(manifest as unknown as SmartObjectManifest, {\n kebabRoutes: options.kebabRoutes,\n });\n}\n\nfunction generateFallbackMcpModule(): string {\n return `\n// Fallback MCP module\nexport const tools = [];\nexport function createMCPServer() {\n console.warn('[smrt:consumer] No MCP tools available - SMRT packages may not be properly configured');\n return { name: 'smrt-consumer', version: '1.0.0', tools: [] };\n}\nexport default createMCPServer;\n`;\n}\n\nfunction generateFallbackTypesModule(manifest: ConsumerManifest): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `// No types available`;\n }\n\n // Generate basic interfaces\n const interfaces = objects.map(([_name, obj]) => {\n return `export interface ${obj.className}Data {\n id?: string;\n created_at?: string;\n updated_at?: string;\n [key: string]: any;\n}`;\n });\n\n return interfaces.join('\\n\\n');\n}\n\nfunction generateFallbackManifestModule(manifest: ConsumerManifest): string {\n return `\n// Auto-generated manifest from SMRT consumer\nexport const manifest = ${JSON.stringify(manifest, null, 2)};\nexport default manifest;\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2KA,IAAM,kBAAkB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,kBAAkB;CAClB,aAAa;AACf;AAEA,IAAM,6CAA6C;AACnD,IAAM,qCAAqC;AAO3C,SAAS,oCAAoC,aAA6B;CACxE,OAAO,KAAK,KAAK,aAAa,SAAS,kCAAkC;AAC3E;;AAGA,SAAS,2BACP,aACA,WACQ;CACR,MAAM,OAAO,KAAK,QAAQ,WAAW;CACrC,MAAM,WAAW,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM,SAAS,CAAC;CAClE,IACE,CAAC,YACD,aAAa,QACb,SAAS,WAAW,KAAK,KAAK,KAAK,KACnC,KAAK,WAAW,QAAQ,GAExB,MAAM,IAAI,MACR,yFAAyF,KAAK,UAAU,SAAS,EAAE,EACrH;CAEF,OAAO,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;AAC1C;AAEA,SAAS,gCAAgC,aAA+B;CACtE,MAAM,eAAe,oCAAoC,WAAW;CACpE,IAAI,CAAC,GAAG,WAAW,YAAY,GAAG,OAAO,CAAC;CAC1C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG,aAAa,cAAc,OAAO,CAAC;CAC5D,QAAQ;EACN,MAAM,IAAI,MACR,+BAA+B,mCAAmC,+CACpE;CACF;CACA,IACE,QAAQ,YAAY,8CACpB,CAAC,MAAM,QAAQ,OAAO,SAAS,KAC/B,OAAO,UAAU,MAAM,cAAc,OAAO,cAAc,QAAQ,GA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AAe;EACf,kBAAkB;EAClB,aAAa;CAER,EAAU,kBAAkB;AACrC;;;;AAKA,SAAS,+BAAuC;CAC9C,OAAO;;;;;;;AAOT;AAEA,SAAS,6BACP,UACA,UAAqC,CAAC,GAC9B;CAER,IADgB,OAAO,QAAQ,UAAU,WAAW,CAAC,CACjD,CAAA,CAAQ,WAAW,GACrB,OAAO;;;;;;;;CAUT,OAAO,qBAAqB,UAA4C,EACtE,aAAa,QAAQ,YACvB,CAAC;AACH;AAEA,SAAS,4BAAoC;CAC3C,OAAO;;;;;;;;;AAST;AAEA,SAAS,4BAA4B,UAAoC;CACvE,MAAM,UAAU,OAAO,QAAQ,UAAU,WAAW,CAAC,CAAC;CACtD,IAAI,QAAQ,WAAW,GACrB,OAAO;CAaT,OATmB,QAAQ,KAAK,CAAC,OAAO,SAAS;EAC/C,OAAO,oBAAoB,IAAI,UAAU;;;;;;CAM3C,CAEO,CAAA,CAAW,KAAK,MAAM;AAC/B;AAEA,SAAS,+BAA+B,UAAoC;CAC1E,OAAO;;0BAEiB,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE;;;AAG5D"}
@@ -4,8 +4,9 @@
4
4
  * Discovers all SMRT packages in node_modules by:
5
5
  * 1. Scanning node_modules directory for installed packages
6
6
  * 2. Following symlinks for workspace: dependencies
7
- * 3. Checking for a package manifest (`dist/manifest.json`,
8
- * `.smrt/manifest.json`, or `src/manifest/manifest.json`) with moduleType: "smrt"
7
+ * 3. Checking for a package manifest — the location declared by the package's
8
+ * own `package.json#exports` map, else `dist/manifest.json`,
9
+ * `.smrt/manifest.json`, or `src/manifest/manifest.json` — with moduleType: "smrt"
9
10
  * 4. Caching results based on lockfile hash and manifest timestamps
10
11
  *
11
12
  * Cache Strategy:
@@ -1 +1 @@
1
- {"version":3,"file":"discover-smrt-packages.d.ts","sourceRoot":"","sources":["../../src/manifest/discover-smrt-packages.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAoBH,oCAAoC;AACpC,UAAU,UAAU;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAKD;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,UAAU,CAE/C;AA2ID,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,OAAO,GAAE,MAAsB,GAC9B,MAAM,GAAG,IAAI,CAoBf;AAkPD,MAAM,WAAW,gBAAgB;IAC/B,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0BAA0B;IAC1B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,yBAAyB;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,gBAAqB,GAAG,MAAM,EAAE,CAsE7E"}
1
+ {"version":3,"file":"discover-smrt-packages.d.ts","sourceRoot":"","sources":["../../src/manifest/discover-smrt-packages.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA8BH,oCAAoC;AACpC,UAAU,UAAU;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAKD;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,UAAU,CAE/C;AAgJD,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,OAAO,GAAE,MAAsB,GAC9B,MAAM,GAAG,IAAI,CAwBf;AAkPD,MAAM,WAAW,gBAAgB;IAC/B,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0BAA0B;IAC1B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,yBAAyB;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,gBAAqB,GAAG,MAAM,EAAE,CAsE7E"}
@@ -1,4 +1,5 @@
1
1
  import { parse } from "../utils/json.js";
2
+ import { manifestExportCandidates } from "./package-manifest-exports.js";
2
3
  import { createHash } from "node:crypto";
3
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
4
5
  import { createRequire } from "node:module";
@@ -10,8 +11,9 @@ import { dirname, join } from "node:path";
10
11
  * Discovers all SMRT packages in node_modules by:
11
12
  * 1. Scanning node_modules directory for installed packages
12
13
  * 2. Following symlinks for workspace: dependencies
13
- * 3. Checking for a package manifest (`dist/manifest.json`,
14
- * `.smrt/manifest.json`, or `src/manifest/manifest.json`) with moduleType: "smrt"
14
+ * 3. Checking for a package manifest — the location declared by the package's
15
+ * own `package.json#exports` map, else `dist/manifest.json`,
16
+ * `.smrt/manifest.json`, or `src/manifest/manifest.json` — with moduleType: "smrt"
15
17
  * 4. Caching results based on lockfile hash and manifest timestamps
16
18
  *
17
19
  * Cache Strategy:
@@ -21,7 +23,16 @@ import { dirname, join } from "node:path";
21
23
  */
22
24
  var CACHE_DIR = ".smrt";
23
25
  var CACHE_FILE = "discovery-cache.json";
24
- var CACHE_VERSION = 4;
26
+ /**
27
+ * Bump whenever what counts as a discoverable package changes, not only when
28
+ * the cache file's shape changes. Version 5 adds export-map manifest
29
+ * resolution (#2923): a version-4 cache can hold an EMPTY package list, and
30
+ * `getCachedDiscovery()` skips manifest rehashing in that case, so without
31
+ * this bump a project would keep replaying the pre-fix "no packages" answer
32
+ * and never re-probe a package whose manifest is only at, say,
33
+ * `dist/lib/manifest.json`.
34
+ */
35
+ var CACHE_VERSION = 5;
25
36
  /** Module-level timing storage */
26
37
  var lastTimingData = {};
27
38
  /**
@@ -64,14 +75,25 @@ function getManifestTimestampsHash(baseDir, packages) {
64
75
  } catch {}
65
76
  return createHash("sha256").update(timestamps.join("|")).digest("hex");
66
77
  }
67
- function findManifestPath(pkgPath) {
68
- const candidates = [
78
+ /**
79
+ * Every manifest file that exists for a package, in preference order.
80
+ *
81
+ * This returns ALL of them rather than just the first, because existing is not
82
+ * the same as being a manifest. An export target can exist and still be
83
+ * unusable here: `./manifest` is commonly a JS module (`@happyvertical/smrt-core`
84
+ * itself maps it to `dist/manifest.js`) and `./static-manifest` always is, and
85
+ * an exported JSON file can be stale or malformed. Stopping at the first
86
+ * existing path would let any of those hide a perfectly good
87
+ * `dist/manifest.json` and drop the package silently — the very #2923 failure
88
+ * mode this file is fixing.
89
+ */
90
+ function manifestPathCandidates(pkgPath) {
91
+ return [
92
+ ...manifestExportCandidates(pkgPath),
69
93
  join(pkgPath, "dist", "manifest.json"),
70
94
  join(pkgPath, ".smrt", "manifest.json"),
71
95
  join(pkgPath, "src", "manifest", "manifest.json")
72
- ];
73
- for (const candidate of candidates) if (existsSync(candidate)) return candidate;
74
- return null;
96
+ ].filter((candidate) => existsSync(candidate));
75
97
  }
76
98
  function normalizePackagePath(pkgPath) {
77
99
  try {
@@ -102,13 +124,10 @@ function resolvePackageDir(packageName, baseDir = process.cwd()) {
102
124
  function resolveManifestPath(packageName, baseDir = process.cwd()) {
103
125
  const pkgPath = resolvePackageDir(packageName, baseDir);
104
126
  if (!pkgPath) return null;
105
- const manifestPath = findManifestPath(pkgPath);
106
- if (!manifestPath) return null;
107
- try {
108
- return parse(readFileSync(manifestPath, "utf-8")).moduleType === "smrt" ? manifestPath : null;
109
- } catch {
110
- return null;
111
- }
127
+ for (const manifestPath of manifestPathCandidates(pkgPath)) try {
128
+ if (parse(readFileSync(manifestPath, "utf-8")).moduleType === "smrt") return manifestPath;
129
+ } catch {}
130
+ return null;
112
131
  }
113
132
  /**
114
133
  * Load cached discovery results if valid
@@ -1 +1 @@
1
- {"version":3,"file":"discover-smrt-packages.js","names":[],"sources":["../../src/manifest/discover-smrt-packages.ts"],"sourcesContent":["/**\n * SMRT Package Discovery\n *\n * Discovers all SMRT packages in node_modules by:\n * 1. Scanning node_modules directory for installed packages\n * 2. Following symlinks for workspace: dependencies\n * 3. Checking for a package manifest (`dist/manifest.json`,\n * `.smrt/manifest.json`, or `src/manifest/manifest.json`) with moduleType: \"smrt\"\n * 4. Caching results based on lockfile hash and manifest timestamps\n *\n * Cache Strategy:\n * - ENABLED by default (5-50x faster startup)\n * - Automatically invalidates when lockfile or any manifest.json changes\n * - Disable with SMRT_DISABLE_DISCOVERY_CACHE=true for debugging\n */\n\nimport { createHash } from 'node:crypto';\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n realpathSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { parse } from '../utils/json.js';\n\nconst CACHE_DIR = '.smrt';\nconst CACHE_FILE = 'discovery-cache.json';\nconst CACHE_VERSION = 4;\n\n/** Timing data for --timing flag */\ninterface TimingData {\n discovery?: number;\n cacheCheck?: number;\n total?: number;\n}\n\n/** Module-level timing storage */\nlet lastTimingData: TimingData = {};\n\n/**\n * Get timing data from last discovery operation\n */\nexport function getDiscoveryTiming(): TimingData {\n return { ...lastTimingData };\n}\n\n/**\n * Get hash of lockfile for cache invalidation\n */\nfunction getLockfileHash(baseDir: string): string | null {\n // Check for pnpm or npm lockfile\n const lockfile = existsSync(join(baseDir, 'pnpm-lock.yaml'))\n ? join(baseDir, 'pnpm-lock.yaml')\n : join(baseDir, 'package-lock.json');\n\n if (!existsSync(lockfile)) {\n return null;\n }\n\n const content = readFileSync(lockfile, 'utf-8');\n return createHash('sha256').update(content).digest('hex');\n}\n\n/**\n * Get hash of package.json for cache invalidation when a package workspace\n * changes its declared dependencies without a colocated lockfile.\n */\nfunction getPackageJsonHash(baseDir: string): string | null {\n const packageJsonPath = join(baseDir, 'package.json');\n\n if (!existsSync(packageJsonPath)) {\n return null;\n }\n\n const content = readFileSync(packageJsonPath, 'utf-8');\n return createHash('sha256').update(content).digest('hex');\n}\n\n/**\n * Get a hash of all manifest timestamps for cache invalidation\n * This catches changes to SMRT packages even when lockfile hasn't changed\n */\nfunction getManifestTimestampsHash(\n baseDir: string,\n packages: string[],\n): string {\n const timestamps: string[] = [];\n\n for (const pkgName of packages) {\n try {\n const manifestPath = resolveManifestPath(pkgName, baseDir);\n\n if (manifestPath && existsSync(manifestPath)) {\n const stats = statSync(manifestPath);\n timestamps.push(`${pkgName}:${stats.mtimeMs}`);\n }\n } catch {\n // Ignore errors, package may have been removed\n }\n }\n\n return createHash('sha256').update(timestamps.join('|')).digest('hex');\n}\n\ninterface DiscoveryCache {\n version: number;\n lockfileHash: string | null;\n packageJsonHash: string | null;\n manifestsHash: string;\n timestamp: number;\n packages: string[];\n}\n\nfunction findManifestPath(pkgPath: string): string | null {\n const candidates = [\n join(pkgPath, 'dist', 'manifest.json'),\n join(pkgPath, '.smrt', 'manifest.json'),\n join(pkgPath, 'src', 'manifest', 'manifest.json'),\n ];\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n return null;\n}\n\nfunction normalizePackagePath(pkgPath: string): string {\n try {\n return realpathSync(pkgPath);\n } catch {\n return pkgPath;\n }\n}\n\nfunction resolvePackageDir(\n packageName: string,\n baseDir: string = process.cwd(),\n): string | null {\n try {\n const requireFromBase = createRequire(join(baseDir, 'package.json'));\n const packageEntry = requireFromBase.resolve(packageName);\n let currentDir = dirname(packageEntry);\n let resolvedPackageDir: string | null = null;\n\n for (let i = 0; i < 10; i++) {\n const packageJsonPath = join(currentDir, 'package.json');\n\n if (existsSync(packageJsonPath)) {\n const packageJson = parse<{ name?: string }>(\n readFileSync(packageJsonPath, 'utf-8'),\n );\n\n if (packageJson.name === packageName) {\n resolvedPackageDir = currentDir;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n\n currentDir = parentDir;\n }\n\n if (resolvedPackageDir) {\n return normalizePackagePath(resolvedPackageDir);\n }\n } catch {\n // Fall through to direct node_modules lookup below.\n }\n\n const directPath = join(baseDir, 'node_modules', packageName);\n if (existsSync(directPath)) {\n return normalizePackagePath(directPath);\n }\n\n return null;\n}\n\nexport function resolveManifestPath(\n packageName: string,\n baseDir: string = process.cwd(),\n): string | null {\n const pkgPath = resolvePackageDir(packageName, baseDir);\n if (!pkgPath) {\n return null;\n }\n\n const manifestPath = findManifestPath(pkgPath);\n if (!manifestPath) {\n return null;\n }\n\n try {\n const manifest = parse<{ moduleType?: string }>(\n readFileSync(manifestPath, 'utf-8'),\n );\n\n return manifest.moduleType === 'smrt' ? manifestPath : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Load cached discovery results if valid\n * Cache is invalidated if:\n * - Lockfile hash changed (dependencies changed)\n * - Manifest timestamps hash changed (SMRT packages rebuilt)\n */\nfunction getCachedDiscovery(\n baseDir: string,\n verbose: boolean,\n): { packages: string[]; reason?: string } | null {\n const cachePath = join(baseDir, CACHE_DIR, CACHE_FILE);\n\n if (!existsSync(cachePath)) {\n return null;\n }\n\n try {\n const cache: DiscoveryCache = parse(readFileSync(cachePath, 'utf-8'));\n if (cache.version !== CACHE_VERSION) {\n if (verbose) {\n console.log('[discovery] Cache invalid: discovery version changed');\n }\n return null;\n }\n\n const currentLockfileHash = getLockfileHash(baseDir);\n const currentPackageJsonHash = getPackageJsonHash(baseDir);\n\n // Check lockfile hash\n if (cache.lockfileHash !== currentLockfileHash) {\n if (verbose) {\n console.log('[discovery] Cache invalid: lockfile changed');\n }\n return null;\n }\n\n if (cache.packageJsonHash !== currentPackageJsonHash) {\n if (verbose) {\n console.log('[discovery] Cache invalid: package.json changed');\n }\n return null;\n }\n\n // Check manifest timestamps (only if we have cached packages)\n if (cache.packages.length > 0) {\n const currentManifestsHash = getManifestTimestampsHash(\n baseDir,\n cache.packages,\n );\n if (cache.manifestsHash !== currentManifestsHash) {\n if (verbose) {\n console.log('[discovery] Cache invalid: manifest(s) changed');\n }\n return null;\n }\n }\n\n return { packages: cache.packages };\n } catch (error) {\n if (verbose) {\n console.warn(\n '[discovery] Failed to read cache:',\n (error as Error).message,\n );\n }\n return null;\n }\n}\n\n/**\n * Save discovery results to cache\n */\nfunction saveCachedDiscovery(\n baseDir: string,\n packages: string[],\n verbose: boolean,\n): void {\n const cache: DiscoveryCache = {\n version: CACHE_VERSION,\n lockfileHash: getLockfileHash(baseDir),\n packageJsonHash: getPackageJsonHash(baseDir),\n manifestsHash: getManifestTimestampsHash(baseDir, packages),\n timestamp: Date.now(),\n packages: packages,\n };\n\n try {\n mkdirSync(join(baseDir, CACHE_DIR), { recursive: true });\n writeFileSync(\n join(baseDir, CACHE_DIR, CACHE_FILE),\n JSON.stringify(cache, null, 2),\n );\n if (verbose) {\n console.log(`[discovery] Saved cache with ${packages.length} package(s)`);\n }\n } catch (error) {\n if (verbose) {\n console.warn(\n '[discovery] Failed to save cache:',\n (error as Error).message,\n );\n }\n }\n}\n\n/**\n * Check if a package provides a SMRT manifest\n *\n * Supports both regular npm dependencies and workspace: symlinks\n */\nfunction hasManifestExport(packageName: string, baseDir: string): boolean {\n return resolveManifestPath(packageName, baseDir) !== null;\n}\n\nfunction getDeclaredSmrtPackages(baseDir: string, verbose: boolean): string[] {\n const packageJsonPath = join(baseDir, 'package.json');\n if (!existsSync(packageJsonPath)) {\n return [];\n }\n\n try {\n const packageJson = parse<{\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n }>(readFileSync(packageJsonPath, 'utf-8'));\n\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n return Object.keys(allDeps).filter((pkgName) => {\n if (!pkgName.startsWith('@happyvertical/smrt-')) {\n return false;\n }\n\n const hasManifest = hasManifestExport(pkgName, baseDir);\n if (verbose && hasManifest) {\n console.log(`[discovery] ✅ Found declared SMRT package: ${pkgName}`);\n }\n\n return hasManifest;\n });\n } catch (error) {\n if (verbose) {\n console.warn(\n '[discovery] Failed to read declared dependencies:',\n (error as Error).message,\n );\n }\n return [];\n }\n}\n\n/**\n * Scan node_modules recursively for packages\n */\nfunction* scanNodeModules(baseDir: string): Generator<string> {\n const nodeModulesPath = join(baseDir, 'node_modules');\n\n if (!existsSync(nodeModulesPath)) {\n return;\n }\n\n try {\n const entries = readdirSync(nodeModulesPath);\n\n for (const entry of entries) {\n if (entry === '.bin' || entry === '.pnpm' || entry === '.cache') {\n continue;\n }\n\n const entryPath = join(nodeModulesPath, entry);\n\n try {\n const stats = statSync(entryPath);\n\n if (stats.isDirectory() || stats.isSymbolicLink()) {\n // Scoped packages (e.g., @happyvertical/smrt-core)\n if (entry.startsWith('@')) {\n const scopeEntries = readdirSync(entryPath);\n for (const scopedPkg of scopeEntries) {\n yield `${entry}/${scopedPkg}`;\n }\n } else {\n // Regular packages\n yield entry;\n }\n }\n } catch {}\n }\n } catch (error) {\n // node_modules doesn't exist or can't be read\n return;\n }\n}\n\n/**\n * Perform fresh discovery of SMRT packages\n */\nfunction performDiscovery(baseDir: string, verbose: boolean): string[] {\n if (verbose) {\n console.log('[discovery] Scanning node_modules for SMRT packages...');\n }\n\n try {\n const smrtPackages = new Set<string>();\n\n // Scan node_modules for all packages\n for (const pkgName of scanNodeModules(baseDir)) {\n if (hasManifestExport(pkgName, baseDir)) {\n smrtPackages.add(pkgName);\n if (verbose) {\n console.log(`[discovery] ✅ Found SMRT package: ${pkgName}`);\n }\n }\n }\n\n for (const pkgName of getDeclaredSmrtPackages(baseDir, verbose)) {\n smrtPackages.add(pkgName);\n }\n\n if (verbose) {\n console.log(\n `[discovery] Discovered ${smrtPackages.size} SMRT package(s)`,\n );\n }\n\n return Array.from(smrtPackages);\n } catch (error) {\n console.error(\n '[discovery] Failed to discover packages:',\n (error as Error).message,\n );\n return [];\n }\n}\n\nexport interface DiscoveryOptions {\n /** Override project root for discovery/cache */\n baseDir?: string;\n /** Force fresh discovery, ignoring cache */\n noCache?: boolean;\n /** Show verbose output */\n verbose?: boolean;\n /** Record timing data */\n timing?: boolean;\n}\n\n/**\n * Main discovery function\n *\n * Cache ENABLED by default (5-50x faster startup)\n * - Automatically invalidates when lockfile changes (dependencies updated)\n * - Automatically invalidates when any manifest.json changes (packages rebuilt)\n *\n * Disable with SMRT_DISABLE_DISCOVERY_CACHE=true for debugging\n *\n * Intentional split (#1579): this is the **build-time** discovery path —\n * synchronous, scans `node_modules` for `manifest.json` files with\n * `moduleType: \"smrt\"`, and caches by lockfile/manifest hash for fast manifest\n * generation. It is deliberately distinct from the consumer-plugin's\n * `discoverSmrtPackages(projectRoot)` (`src/consumer-plugin/index.ts`), which is\n * **async**, reads a downstream app's `package.json` dependency names with a\n * lightweight `@have/`/`smrt` heuristic, and runs inside the Vite consumer\n * plugin. Different inputs, contexts, and lifecycles — not duplicated logic to\n * consolidate.\n */\nexport function discoverSmrtPackages(options: DiscoveryOptions = {}): string[] {\n const startTime = options.timing ? performance.now() : 0;\n lastTimingData = {};\n const baseDir = options.baseDir || process.cwd();\n\n const cacheDisabled =\n options.noCache || process.env.SMRT_DISABLE_DISCOVERY_CACHE === 'true';\n\n const verbose: boolean =\n options.verbose === true ||\n process.env.SMRT_VERBOSE === 'true' ||\n !!process.env.DEBUG?.includes('smrt');\n\n if (cacheDisabled) {\n if (verbose) {\n console.log('[discovery] Cache disabled, performing fresh discovery...');\n }\n\n const packages = performDiscovery(baseDir, verbose);\n\n if (options.timing) {\n lastTimingData.discovery = performance.now() - startTime;\n lastTimingData.total = lastTimingData.discovery;\n }\n\n return packages;\n }\n\n // Try cache first\n const cacheCheckStart = options.timing ? performance.now() : 0;\n const cached = getCachedDiscovery(baseDir, verbose);\n\n if (options.timing) {\n lastTimingData.cacheCheck = performance.now() - cacheCheckStart;\n }\n\n if (cached) {\n if (verbose) {\n console.log(\n `[discovery] ✅ Using cached SMRT packages (${cached.packages.length} package(s))`,\n );\n }\n\n if (options.timing) {\n lastTimingData.total = performance.now() - startTime;\n }\n\n return cached.packages;\n }\n\n // No valid cache - perform fresh discovery\n if (verbose) {\n console.log('[discovery] Cache miss, performing discovery...');\n }\n\n const discoveryStart = options.timing ? performance.now() : 0;\n const packages = performDiscovery(baseDir, verbose);\n\n if (options.timing) {\n lastTimingData.discovery = performance.now() - discoveryStart;\n }\n\n // Save to cache\n saveCachedDiscovery(baseDir, packages, verbose);\n\n if (options.timing) {\n lastTimingData.total = performance.now() - startTime;\n }\n\n return packages;\n}\n\n// Run if called directly\nif (import.meta.url === `file://${process.argv[1]}`) {\n const noCache = process.argv.includes('--no-cache');\n const verbose =\n process.argv.includes('--verbose') || process.argv.includes('-v');\n const timing = process.argv.includes('--timing');\n\n const packages = discoverSmrtPackages({ noCache, verbose, timing });\n\n console.log('\\nDiscovered SMRT packages:');\n console.log(JSON.stringify(packages, null, 2));\n\n if (timing) {\n const timingData = getDiscoveryTiming();\n console.log('\\nTiming:');\n if (timingData.cacheCheck !== undefined) {\n console.log(` Cache check: ${timingData.cacheCheck.toFixed(2)}ms`);\n }\n if (timingData.discovery !== undefined) {\n console.log(` Discovery: ${timingData.discovery.toFixed(2)}ms`);\n }\n if (timingData.total !== undefined) {\n console.log(` Total: ${timingData.total.toFixed(2)}ms`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8BA,IAAM,YAAY;AAClB,IAAM,aAAa;AACnB,IAAM,gBAAgB;;AAUtB,IAAI,iBAA6B,CAAC;;;;AAKlC,SAAgB,qBAAiC;CAC/C,OAAO,EAAE,GAAG,eAAe;AAC7B;;;;AAKA,SAAS,gBAAgB,SAAgC;CAEvD,MAAM,WAAW,WAAW,KAAK,SAAS,gBAAgB,CAAC,IACvD,KAAK,SAAS,gBAAgB,IAC9B,KAAK,SAAS,mBAAmB;CAErC,IAAI,CAAC,WAAW,QAAQ,GACtB,OAAO;CAGT,MAAM,UAAU,aAAa,UAAU,OAAO;CAC9C,OAAO,WAAW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AAQ,KAAK,SAAS,YAAY;CAClD,MAAM,UACJ,QAAQ,KAAK,SAAS,WAAW,KAAK,QAAQ,KAAK,SAAS,IAAI;CAClE,MAAM,SAAS,QAAQ,KAAK,SAAS,UAAU;CAE/C,MAAM,WAAW,qBAAqB;EAAE;EAAS;EAAS;CAAO,CAAC;CAElE,QAAQ,IAAI,6BAA6B;CACzC,QAAQ,IAAI,KAAK,UAAU,UAAU,MAAM,CAAC,CAAC;CAE7C,IAAI,QAAQ;EACV,MAAM,aAAa,mBAAmB;EACtC,QAAQ,IAAI,WAAW;EACvB,IAAI,WAAW,eAAe,KAAA,GAC5B,QAAQ,IAAI,kBAAkB,WAAW,WAAW,QAAQ,CAAC,EAAE,GAAG;EAEpE,IAAI,WAAW,cAAc,KAAA,GAC3B,QAAQ,IAAI,kBAAkB,WAAW,UAAU,QAAQ,CAAC,EAAE,GAAG;EAEnE,IAAI,WAAW,UAAU,KAAA,GACvB,QAAQ,IAAI,kBAAkB,WAAW,MAAM,QAAQ,CAAC,EAAE,GAAG;CAEjE;AACF"}
1
+ {"version":3,"file":"discover-smrt-packages.js","names":[],"sources":["../../src/manifest/discover-smrt-packages.ts"],"sourcesContent":["/**\n * SMRT Package Discovery\n *\n * Discovers all SMRT packages in node_modules by:\n * 1. Scanning node_modules directory for installed packages\n * 2. Following symlinks for workspace: dependencies\n * 3. Checking for a package manifest — the location declared by the package's\n * own `package.json#exports` map, else `dist/manifest.json`,\n * `.smrt/manifest.json`, or `src/manifest/manifest.json` — with moduleType: \"smrt\"\n * 4. Caching results based on lockfile hash and manifest timestamps\n *\n * Cache Strategy:\n * - ENABLED by default (5-50x faster startup)\n * - Automatically invalidates when lockfile or any manifest.json changes\n * - Disable with SMRT_DISABLE_DISCOVERY_CACHE=true for debugging\n */\n\nimport { createHash } from 'node:crypto';\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n realpathSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { parse } from '../utils/json.js';\nimport { manifestExportCandidates } from './package-manifest-exports.js';\n\nconst CACHE_DIR = '.smrt';\nconst CACHE_FILE = 'discovery-cache.json';\n/**\n * Bump whenever what counts as a discoverable package changes, not only when\n * the cache file's shape changes. Version 5 adds export-map manifest\n * resolution (#2923): a version-4 cache can hold an EMPTY package list, and\n * `getCachedDiscovery()` skips manifest rehashing in that case, so without\n * this bump a project would keep replaying the pre-fix \"no packages\" answer\n * and never re-probe a package whose manifest is only at, say,\n * `dist/lib/manifest.json`.\n */\nconst CACHE_VERSION = 5;\n\n/** Timing data for --timing flag */\ninterface TimingData {\n discovery?: number;\n cacheCheck?: number;\n total?: number;\n}\n\n/** Module-level timing storage */\nlet lastTimingData: TimingData = {};\n\n/**\n * Get timing data from last discovery operation\n */\nexport function getDiscoveryTiming(): TimingData {\n return { ...lastTimingData };\n}\n\n/**\n * Get hash of lockfile for cache invalidation\n */\nfunction getLockfileHash(baseDir: string): string | null {\n // Check for pnpm or npm lockfile\n const lockfile = existsSync(join(baseDir, 'pnpm-lock.yaml'))\n ? join(baseDir, 'pnpm-lock.yaml')\n : join(baseDir, 'package-lock.json');\n\n if (!existsSync(lockfile)) {\n return null;\n }\n\n const content = readFileSync(lockfile, 'utf-8');\n return createHash('sha256').update(content).digest('hex');\n}\n\n/**\n * Get hash of package.json for cache invalidation when a package workspace\n * changes its declared dependencies without a colocated lockfile.\n */\nfunction getPackageJsonHash(baseDir: string): string | null {\n const packageJsonPath = join(baseDir, 'package.json');\n\n if (!existsSync(packageJsonPath)) {\n return null;\n }\n\n const content = readFileSync(packageJsonPath, 'utf-8');\n return createHash('sha256').update(content).digest('hex');\n}\n\n/**\n * Get a hash of all manifest timestamps for cache invalidation\n * This catches changes to SMRT packages even when lockfile hasn't changed\n */\nfunction getManifestTimestampsHash(\n baseDir: string,\n packages: string[],\n): string {\n const timestamps: string[] = [];\n\n for (const pkgName of packages) {\n try {\n const manifestPath = resolveManifestPath(pkgName, baseDir);\n\n if (manifestPath && existsSync(manifestPath)) {\n const stats = statSync(manifestPath);\n timestamps.push(`${pkgName}:${stats.mtimeMs}`);\n }\n } catch {\n // Ignore errors, package may have been removed\n }\n }\n\n return createHash('sha256').update(timestamps.join('|')).digest('hex');\n}\n\ninterface DiscoveryCache {\n version: number;\n lockfileHash: string | null;\n packageJsonHash: string | null;\n manifestsHash: string;\n timestamp: number;\n packages: string[];\n}\n\n/**\n * Every manifest file that exists for a package, in preference order.\n *\n * This returns ALL of them rather than just the first, because existing is not\n * the same as being a manifest. An export target can exist and still be\n * unusable here: `./manifest` is commonly a JS module (`@happyvertical/smrt-core`\n * itself maps it to `dist/manifest.js`) and `./static-manifest` always is, and\n * an exported JSON file can be stale or malformed. Stopping at the first\n * existing path would let any of those hide a perfectly good\n * `dist/manifest.json` and drop the package silently — the very #2923 failure\n * mode this file is fixing.\n */\nfunction manifestPathCandidates(pkgPath: string): string[] {\n return [\n ...manifestExportCandidates(pkgPath),\n join(pkgPath, 'dist', 'manifest.json'),\n join(pkgPath, '.smrt', 'manifest.json'),\n join(pkgPath, 'src', 'manifest', 'manifest.json'),\n ].filter((candidate) => existsSync(candidate));\n}\n\nfunction normalizePackagePath(pkgPath: string): string {\n try {\n return realpathSync(pkgPath);\n } catch {\n return pkgPath;\n }\n}\n\nfunction resolvePackageDir(\n packageName: string,\n baseDir: string = process.cwd(),\n): string | null {\n try {\n const requireFromBase = createRequire(join(baseDir, 'package.json'));\n const packageEntry = requireFromBase.resolve(packageName);\n let currentDir = dirname(packageEntry);\n let resolvedPackageDir: string | null = null;\n\n for (let i = 0; i < 10; i++) {\n const packageJsonPath = join(currentDir, 'package.json');\n\n if (existsSync(packageJsonPath)) {\n const packageJson = parse<{ name?: string }>(\n readFileSync(packageJsonPath, 'utf-8'),\n );\n\n if (packageJson.name === packageName) {\n resolvedPackageDir = currentDir;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n\n currentDir = parentDir;\n }\n\n if (resolvedPackageDir) {\n return normalizePackagePath(resolvedPackageDir);\n }\n } catch {\n // Fall through to direct node_modules lookup below.\n }\n\n const directPath = join(baseDir, 'node_modules', packageName);\n if (existsSync(directPath)) {\n return normalizePackagePath(directPath);\n }\n\n return null;\n}\n\nexport function resolveManifestPath(\n packageName: string,\n baseDir: string = process.cwd(),\n): string | null {\n const pkgPath = resolvePackageDir(packageName, baseDir);\n if (!pkgPath) {\n return null;\n }\n\n // Take the first candidate that actually parses as a SMRT manifest. A\n // candidate that exists but is a JS module, stale, or malformed must not end\n // the search, or it would mask a valid conventional manifest behind it.\n for (const manifestPath of manifestPathCandidates(pkgPath)) {\n try {\n const manifest = parse<{ moduleType?: string }>(\n readFileSync(manifestPath, 'utf-8'),\n );\n\n if (manifest.moduleType === 'smrt') {\n return manifestPath;\n }\n } catch {\n // Not a readable JSON manifest; try the next candidate.\n }\n }\n\n return null;\n}\n\n/**\n * Load cached discovery results if valid\n * Cache is invalidated if:\n * - Lockfile hash changed (dependencies changed)\n * - Manifest timestamps hash changed (SMRT packages rebuilt)\n */\nfunction getCachedDiscovery(\n baseDir: string,\n verbose: boolean,\n): { packages: string[]; reason?: string } | null {\n const cachePath = join(baseDir, CACHE_DIR, CACHE_FILE);\n\n if (!existsSync(cachePath)) {\n return null;\n }\n\n try {\n const cache: DiscoveryCache = parse(readFileSync(cachePath, 'utf-8'));\n if (cache.version !== CACHE_VERSION) {\n if (verbose) {\n console.log('[discovery] Cache invalid: discovery version changed');\n }\n return null;\n }\n\n const currentLockfileHash = getLockfileHash(baseDir);\n const currentPackageJsonHash = getPackageJsonHash(baseDir);\n\n // Check lockfile hash\n if (cache.lockfileHash !== currentLockfileHash) {\n if (verbose) {\n console.log('[discovery] Cache invalid: lockfile changed');\n }\n return null;\n }\n\n if (cache.packageJsonHash !== currentPackageJsonHash) {\n if (verbose) {\n console.log('[discovery] Cache invalid: package.json changed');\n }\n return null;\n }\n\n // Check manifest timestamps (only if we have cached packages)\n if (cache.packages.length > 0) {\n const currentManifestsHash = getManifestTimestampsHash(\n baseDir,\n cache.packages,\n );\n if (cache.manifestsHash !== currentManifestsHash) {\n if (verbose) {\n console.log('[discovery] Cache invalid: manifest(s) changed');\n }\n return null;\n }\n }\n\n return { packages: cache.packages };\n } catch (error) {\n if (verbose) {\n console.warn(\n '[discovery] Failed to read cache:',\n (error as Error).message,\n );\n }\n return null;\n }\n}\n\n/**\n * Save discovery results to cache\n */\nfunction saveCachedDiscovery(\n baseDir: string,\n packages: string[],\n verbose: boolean,\n): void {\n const cache: DiscoveryCache = {\n version: CACHE_VERSION,\n lockfileHash: getLockfileHash(baseDir),\n packageJsonHash: getPackageJsonHash(baseDir),\n manifestsHash: getManifestTimestampsHash(baseDir, packages),\n timestamp: Date.now(),\n packages: packages,\n };\n\n try {\n mkdirSync(join(baseDir, CACHE_DIR), { recursive: true });\n writeFileSync(\n join(baseDir, CACHE_DIR, CACHE_FILE),\n JSON.stringify(cache, null, 2),\n );\n if (verbose) {\n console.log(`[discovery] Saved cache with ${packages.length} package(s)`);\n }\n } catch (error) {\n if (verbose) {\n console.warn(\n '[discovery] Failed to save cache:',\n (error as Error).message,\n );\n }\n }\n}\n\n/**\n * Check if a package provides a SMRT manifest\n *\n * Supports both regular npm dependencies and workspace: symlinks\n */\nfunction hasManifestExport(packageName: string, baseDir: string): boolean {\n return resolveManifestPath(packageName, baseDir) !== null;\n}\n\nfunction getDeclaredSmrtPackages(baseDir: string, verbose: boolean): string[] {\n const packageJsonPath = join(baseDir, 'package.json');\n if (!existsSync(packageJsonPath)) {\n return [];\n }\n\n try {\n const packageJson = parse<{\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n }>(readFileSync(packageJsonPath, 'utf-8'));\n\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n return Object.keys(allDeps).filter((pkgName) => {\n if (!pkgName.startsWith('@happyvertical/smrt-')) {\n return false;\n }\n\n const hasManifest = hasManifestExport(pkgName, baseDir);\n if (verbose && hasManifest) {\n console.log(`[discovery] ✅ Found declared SMRT package: ${pkgName}`);\n }\n\n return hasManifest;\n });\n } catch (error) {\n if (verbose) {\n console.warn(\n '[discovery] Failed to read declared dependencies:',\n (error as Error).message,\n );\n }\n return [];\n }\n}\n\n/**\n * Scan node_modules recursively for packages\n */\nfunction* scanNodeModules(baseDir: string): Generator<string> {\n const nodeModulesPath = join(baseDir, 'node_modules');\n\n if (!existsSync(nodeModulesPath)) {\n return;\n }\n\n try {\n const entries = readdirSync(nodeModulesPath);\n\n for (const entry of entries) {\n if (entry === '.bin' || entry === '.pnpm' || entry === '.cache') {\n continue;\n }\n\n const entryPath = join(nodeModulesPath, entry);\n\n try {\n const stats = statSync(entryPath);\n\n if (stats.isDirectory() || stats.isSymbolicLink()) {\n // Scoped packages (e.g., @happyvertical/smrt-core)\n if (entry.startsWith('@')) {\n const scopeEntries = readdirSync(entryPath);\n for (const scopedPkg of scopeEntries) {\n yield `${entry}/${scopedPkg}`;\n }\n } else {\n // Regular packages\n yield entry;\n }\n }\n } catch {}\n }\n } catch (error) {\n // node_modules doesn't exist or can't be read\n return;\n }\n}\n\n/**\n * Perform fresh discovery of SMRT packages\n */\nfunction performDiscovery(baseDir: string, verbose: boolean): string[] {\n if (verbose) {\n console.log('[discovery] Scanning node_modules for SMRT packages...');\n }\n\n try {\n const smrtPackages = new Set<string>();\n\n // Scan node_modules for all packages\n for (const pkgName of scanNodeModules(baseDir)) {\n if (hasManifestExport(pkgName, baseDir)) {\n smrtPackages.add(pkgName);\n if (verbose) {\n console.log(`[discovery] ✅ Found SMRT package: ${pkgName}`);\n }\n }\n }\n\n for (const pkgName of getDeclaredSmrtPackages(baseDir, verbose)) {\n smrtPackages.add(pkgName);\n }\n\n if (verbose) {\n console.log(\n `[discovery] Discovered ${smrtPackages.size} SMRT package(s)`,\n );\n }\n\n return Array.from(smrtPackages);\n } catch (error) {\n console.error(\n '[discovery] Failed to discover packages:',\n (error as Error).message,\n );\n return [];\n }\n}\n\nexport interface DiscoveryOptions {\n /** Override project root for discovery/cache */\n baseDir?: string;\n /** Force fresh discovery, ignoring cache */\n noCache?: boolean;\n /** Show verbose output */\n verbose?: boolean;\n /** Record timing data */\n timing?: boolean;\n}\n\n/**\n * Main discovery function\n *\n * Cache ENABLED by default (5-50x faster startup)\n * - Automatically invalidates when lockfile changes (dependencies updated)\n * - Automatically invalidates when any manifest.json changes (packages rebuilt)\n *\n * Disable with SMRT_DISABLE_DISCOVERY_CACHE=true for debugging\n *\n * Intentional split (#1579): this is the **build-time** discovery path —\n * synchronous, scans `node_modules` for `manifest.json` files with\n * `moduleType: \"smrt\"`, and caches by lockfile/manifest hash for fast manifest\n * generation. It is deliberately distinct from the consumer-plugin's\n * `discoverSmrtPackages(projectRoot)` (`src/consumer-plugin/index.ts`), which is\n * **async**, reads a downstream app's `package.json` dependency names with a\n * lightweight `@have/`/`smrt` heuristic, and runs inside the Vite consumer\n * plugin. Different inputs, contexts, and lifecycles — not duplicated logic to\n * consolidate.\n */\nexport function discoverSmrtPackages(options: DiscoveryOptions = {}): string[] {\n const startTime = options.timing ? performance.now() : 0;\n lastTimingData = {};\n const baseDir = options.baseDir || process.cwd();\n\n const cacheDisabled =\n options.noCache || process.env.SMRT_DISABLE_DISCOVERY_CACHE === 'true';\n\n const verbose: boolean =\n options.verbose === true ||\n process.env.SMRT_VERBOSE === 'true' ||\n !!process.env.DEBUG?.includes('smrt');\n\n if (cacheDisabled) {\n if (verbose) {\n console.log('[discovery] Cache disabled, performing fresh discovery...');\n }\n\n const packages = performDiscovery(baseDir, verbose);\n\n if (options.timing) {\n lastTimingData.discovery = performance.now() - startTime;\n lastTimingData.total = lastTimingData.discovery;\n }\n\n return packages;\n }\n\n // Try cache first\n const cacheCheckStart = options.timing ? performance.now() : 0;\n const cached = getCachedDiscovery(baseDir, verbose);\n\n if (options.timing) {\n lastTimingData.cacheCheck = performance.now() - cacheCheckStart;\n }\n\n if (cached) {\n if (verbose) {\n console.log(\n `[discovery] ✅ Using cached SMRT packages (${cached.packages.length} package(s))`,\n );\n }\n\n if (options.timing) {\n lastTimingData.total = performance.now() - startTime;\n }\n\n return cached.packages;\n }\n\n // No valid cache - perform fresh discovery\n if (verbose) {\n console.log('[discovery] Cache miss, performing discovery...');\n }\n\n const discoveryStart = options.timing ? performance.now() : 0;\n const packages = performDiscovery(baseDir, verbose);\n\n if (options.timing) {\n lastTimingData.discovery = performance.now() - discoveryStart;\n }\n\n // Save to cache\n saveCachedDiscovery(baseDir, packages, verbose);\n\n if (options.timing) {\n lastTimingData.total = performance.now() - startTime;\n }\n\n return packages;\n}\n\n// Run if called directly\nif (import.meta.url === `file://${process.argv[1]}`) {\n const noCache = process.argv.includes('--no-cache');\n const verbose =\n process.argv.includes('--verbose') || process.argv.includes('-v');\n const timing = process.argv.includes('--timing');\n\n const packages = discoverSmrtPackages({ noCache, verbose, timing });\n\n console.log('\\nDiscovered SMRT packages:');\n console.log(JSON.stringify(packages, null, 2));\n\n if (timing) {\n const timingData = getDiscoveryTiming();\n console.log('\\nTiming:');\n if (timingData.cacheCheck !== undefined) {\n console.log(` Cache check: ${timingData.cacheCheck.toFixed(2)}ms`);\n }\n if (timingData.discovery !== undefined) {\n console.log(` Discovery: ${timingData.discovery.toFixed(2)}ms`);\n }\n if (timingData.total !== undefined) {\n console.log(` Total: ${timingData.total.toFixed(2)}ms`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAM,YAAY;AAClB,IAAM,aAAa;;;;;;;;;;AAUnB,IAAM,gBAAgB;;AAUtB,IAAI,iBAA6B,CAAC;;;;AAKlC,SAAgB,qBAAiC;CAC/C,OAAO,EAAE,GAAG,eAAe;AAC7B;;;;AAKA,SAAS,gBAAgB,SAAgC;CAEvD,MAAM,WAAW,WAAW,KAAK,SAAS,gBAAgB,CAAC,IACvD,KAAK,SAAS,gBAAgB,IA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