@happyvertical/smrt-core 0.51.29 → 0.51.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agents/schema-paths.md +9 -0
- package/dist/browser.d.ts +1 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +2 -1
- package/dist/class.d.ts +33 -0
- package/dist/class.d.ts.map +1 -1
- package/dist/class.js +77 -0
- package/dist/class.js.map +1 -1
- package/dist/collection.d.ts.map +1 -1
- package/dist/collection.js +5 -1
- package/dist/collection.js.map +1 -1
- package/dist/config.d.ts +3 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/decisions.d.ts +89 -0
- package/dist/decisions.d.ts.map +1 -0
- package/dist/decisions.js +78 -0
- package/dist/decisions.js.map +1 -0
- package/dist/generators/custom-action.d.ts.map +1 -1
- package/dist/generators/custom-action.js +2 -1
- package/dist/generators/custom-action.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/manifest/static-manifest.d.ts.map +1 -1
- package/dist/manifest/static-manifest.js +17 -1
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/store.js.map +1 -1
- package/dist/manifest.json +20 -1
- package/dist/migrations/differ.d.ts +43 -1
- package/dist/migrations/differ.d.ts.map +1 -1
- package/dist/migrations/differ.js +69 -0
- package/dist/migrations/differ.js.map +1 -1
- package/dist/object.d.ts +11 -0
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +96 -2
- package/dist/object.js.map +1 -1
- package/dist/registry/shared-state.js +1 -1
- package/dist/schema/bounded-concurrency.d.ts +31 -0
- package/dist/schema/bounded-concurrency.d.ts.map +1 -0
- package/dist/schema/bounded-concurrency.js +43 -0
- package/dist/schema/bounded-concurrency.js.map +1 -0
- package/dist/schema/foreign-key-orphan-report.d.ts +21 -0
- package/dist/schema/foreign-key-orphan-report.d.ts.map +1 -1
- package/dist/schema/foreign-key-orphan-report.js +90 -55
- package/dist/schema/foreign-key-orphan-report.js.map +1 -1
- package/dist/smrt-knowledge.json +15 -5
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","names":[],"sources":["../../src/manifest/store.ts"],"sourcesContent":["/**\n * Leaf manifest storage + pure fs/URL helpers.\n *\n * This module has **no dependency on ObjectRegistry, registry.ts, or\n * class-registration.ts**. It owns the globalThis manifest caches and the\n * filesystem helpers that resolve and read manifest.json files from the\n * workspace, installed node_modules, and smrt-core's own bundle.\n *\n * Breaking the cycle: Before this module existed, `registry.ts` and\n * `manifest-loader.ts` both maintained their own copies of these helpers\n * (`registry.ts` had its own because `registerPackageManifest` needed them\n * and could not import `manifest-loader.ts` due to a module cycle —\n * `registry.ts → class-registration.ts → manifest-loader.ts → registry.ts`).\n * Centralizing them here lets both files import from a leaf, so the cycle\n * goes away and Release B's `ManifestSource` abstraction can live above\n * this leaf without re-creating it.\n *\n * @see https://github.com/happyvertical/smrt/issues/1133\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { recordRegistryDiagnostic } from '../registry/diagnostics.js';\nimport {\n bumpRegistryGeneration,\n createGenerationTrackedMap,\n isGenerationTrackedMap,\n} from '../registry/generation.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport type { ColumnDefinition } from '../schema/types.js';\nimport {\n createQualifiedName,\n isQualifiedName,\n parseQualifiedName,\n} from '../utils/qualified-names.js';\n\nconst logger = createLogger({ level: 'info' });\n\nexport type ManifestLoadOptions = {\n warn?: boolean;\n};\n\n// ── Runtime environment detection ────────────────────────────────────────\n\n/**\n * Detect whether we're running inside a test runner. Test manifests must\n * never load in production to avoid test classes colliding with real ones.\n */\nexport function isTestEnvironment(): boolean {\n return (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n process.env.JEST_WORKER_ID !== undefined\n );\n}\n\n/**\n * Best-effort detection of the current package under test.\n *\n * In workspace consumers, `process.cwd()` points at the consuming app/package,\n * while in smrt-core's own tests it points at `packages/core`. We use that\n * distinction to keep smrt-core's internal test manifest scoped to its own\n * test suite instead of leaking those fixtures into every consumer test run.\n */\nexport function getCurrentPackageName(): string | null {\n const explicitPackageName = process.env.npm_package_name;\n if (explicitPackageName) {\n return explicitPackageName;\n }\n\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n let currentDir = process.cwd();\n\n while (true) {\n const packageJsonPath = builtins.path.join(currentDir, 'package.json');\n if (builtins.fs.existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(\n builtins.fs.readFileSync(packageJsonPath, 'utf-8'),\n ) as { name?: string };\n return packageJson.name ?? null;\n } catch {\n return null;\n }\n }\n\n const parentDir = builtins.path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n}\n\n/**\n * smrt-core's committed test manifest is for smrt-core's own tests only.\n * Consumer packages should expose only their local test manifest plus real\n * published manifests from dependencies.\n */\nexport function shouldLoadCoreTestManifest(): boolean {\n if (!isTestEnvironment()) {\n return false;\n }\n\n const currentPackageName = getCurrentPackageName();\n if (currentPackageName) {\n return currentPackageName === '@happyvertical/smrt-core';\n }\n\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return false;\n }\n\n const moduleDir = builtins.path.dirname(\n builtins.url.fileURLToPath(import.meta.url),\n );\n const workspaceRoot = findWorkspaceRootSync(moduleDir);\n if (!workspaceRoot) {\n return false;\n }\n\n const corePackageDir = builtins.path.join(workspaceRoot, 'packages', 'core');\n const relative = builtins.path.relative(corePackageDir, process.cwd());\n return (\n relative === '' ||\n (!relative.startsWith('..') && !builtins.path.isAbsolute(relative))\n );\n}\n\n// ── Node builtins access ─────────────────────────────────────────────────\n\n/**\n * Resolve Node's built-in `fs`/`path`/`url` modules without a static import.\n *\n * `process.getBuiltinModule()` is a Node 22+ API that returns the live\n * built-in without going through the module loader. This avoids Vite's\n * static-import analysis flagging these builtins and simulated\n * \"externalized for browser\" warnings in bundled browser builds.\n */\nexport function getNodeBuiltins() {\n const getBuiltinModule = (\n process as typeof process & {\n getBuiltinModule?: (id: string) => unknown;\n }\n ).getBuiltinModule;\n if (typeof getBuiltinModule !== 'function') {\n return null;\n }\n\n const fs = getBuiltinModule('node:fs') as\n | typeof import('node:fs')\n | undefined;\n const path = getBuiltinModule('node:path') as\n | typeof import('node:path')\n | undefined;\n const url = getBuiltinModule('node:url') as\n | typeof import('node:url')\n | undefined;\n\n if (!fs || !path || !url) {\n return null;\n }\n\n return { fs, path, url };\n}\n\n// ── globalThis cache accessors ───────────────────────────────────────────\n\ntype ManifestGlobals = typeof globalThis & {\n __smrtManifestStatic?: SmartObjectManifest | null;\n __smrtManifestStaticLoadAttempted?: boolean;\n __smrtManifestTest?: SmartObjectManifest | null;\n __smrtManifestLocalTest?: SmartObjectManifest | null;\n __smrtManifestCache?: Map<string, SmartObjectManifest>;\n};\n\nfunction getManifestGlobals(): ManifestGlobals {\n return globalThis as ManifestGlobals;\n}\n\n/**\n * Return the mutable external-manifest cache, creating it if absent.\n *\n * Writers: `registerPackageManifest()` (Release A, each package's shim),\n * `loadExternalManifestSyncWithNode()`, `loadManifestFromPathSyncWithNode()`.\n * Readers: all discovery paths.\n */\nexport function getManifestCache(): Map<string, SmartObjectManifest> {\n const globals = getManifestGlobals();\n const current = globals.__smrtManifestCache;\n if (current && isGenerationTrackedMap(current)) {\n return current;\n }\n // A newly cached manifest can change what manifest discovery returns, so\n // it invalidates the generation-keyed registry memos (#3047).\n const tracked = createGenerationTrackedMap<string, SmartObjectManifest>(\n current,\n );\n globals.__smrtManifestCache = tracked;\n return tracked;\n}\n\n/** Read-only snapshot of the static manifest, if cached. */\nexport function getStaticManifestCache(): SmartObjectManifest | null {\n return getManifestGlobals().__smrtManifestStatic ?? null;\n}\n\n/** Read-only snapshot of the core test manifest, if cached. */\nexport function getTestManifestCache(): SmartObjectManifest | null {\n return getManifestGlobals().__smrtManifestTest ?? null;\n}\n\n/**\n * Read-only snapshot of the local (domain package) test manifest.\n *\n * Preserves the three-state semantics that `discoverManifestEntry()` relies\n * on: `undefined` means \"never attempted to load\" and triggers the lazy\n * loader; `null` means \"attempted but no local test manifest in this\n * package\"; a manifest object means \"loaded\". Do not collapse `undefined`\n * to `null` here — the async-discovery lazy-load path keys off the\n * distinction (see manifest-loader.ts:`if (getLocalTestManifestCache() === undefined) loadLocalTestManifestSync()`).\n */\nexport function getLocalTestManifestCache():\n | SmartObjectManifest\n | null\n | undefined {\n return getManifestGlobals().__smrtManifestLocalTest;\n}\n\n// ── Manifest shape helpers ───────────────────────────────────────────────\n\nexport function createEmptyStaticManifest(): SmartObjectManifest {\n return {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n packageName: '@happyvertical/smrt-core',\n };\n}\n\n/**\n * Deep-clone a manifest's schema column map so downstream mutators don't\n * corrupt the cached manifest. Foreign-key descriptors get their own copy\n * because manifest-loader.ts and registerFromManifest() both splice them\n * into live schema entries.\n */\nexport function cloneManifestSchemaColumns(\n columns: Record<string, unknown> | undefined,\n): Record<string, ColumnDefinition> {\n return Object.fromEntries(\n Object.entries(columns || {}).map(([columnName, column]) => {\n const clonedColumn = {\n ...(column as ColumnDefinition & Record<string, unknown>),\n } as ColumnDefinition;\n const manifestDefault = (\n clonedColumn as ColumnDefinition & {\n default?: unknown;\n }\n ).default;\n\n if (\n clonedColumn.defaultValue === undefined &&\n manifestDefault !== undefined\n ) {\n clonedColumn.defaultValue = manifestDefault;\n }\n\n if (clonedColumn.foreignKey) {\n clonedColumn.foreignKey = { ...clonedColumn.foreignKey };\n }\n\n return [columnName, clonedColumn];\n }),\n ) as Record<string, ColumnDefinition>;\n}\n\n/**\n * Look up a class definition inside a single manifest.\n *\n * Tries qualified-key, simple-name, and lowercase-name lookups, then falls\n * back to iterating every entry in the manifest comparing lowered names.\n * This is the low-level primitive used by every sync discovery path.\n */\nexport function lookupCachedManifestEntry(\n manifest: SmartObjectManifest | null | undefined,\n className: string,\n): SmartObjectDefinition | undefined {\n if (!manifest?.objects) {\n return undefined;\n }\n\n const requestedQualifiedName = isQualifiedName(className)\n ? className\n : undefined;\n const requestedClassName = requestedQualifiedName\n ? parseQualifiedName(requestedQualifiedName).className\n : className;\n const lowerClassName = requestedClassName.toLowerCase();\n const packageName = manifest.packageName;\n const qualifiedKey =\n requestedQualifiedName ||\n (packageName\n ? createQualifiedName(packageName, requestedClassName)\n : undefined);\n\n // A qualified request names one package's class. Another package's\n // manifest can only answer it by an exact qualified key (aggregated\n // manifests); a simple-name hit there is a different class (#3098).\n const requestedPackage = requestedQualifiedName\n ? parseQualifiedName(requestedQualifiedName).packageName\n : undefined;\n if (\n requestedQualifiedName &&\n packageName !== undefined &&\n packageName !== requestedPackage\n ) {\n const direct = manifest.objects[requestedQualifiedName];\n return direct &&\n (direct.packageName === undefined ||\n direct.packageName === requestedPackage)\n ? direct\n : undefined;\n }\n\n return (\n (qualifiedKey ? manifest.objects[qualifiedKey] : undefined) ||\n manifest.objects[requestedClassName] ||\n manifest.objects[lowerClassName] ||\n Object.values(manifest.objects).find((entry) => {\n if (!entry) {\n return false;\n }\n\n if (entry.className?.toLowerCase() === lowerClassName) {\n return true;\n }\n\n return (\n requestedQualifiedName !== undefined &&\n packageName !== undefined &&\n createQualifiedName(packageName, entry.className || '') ===\n requestedQualifiedName\n );\n })\n );\n}\n\n// ── Filesystem helpers ───────────────────────────────────────────────────\n\nexport function findWorkspaceRootSync(startDir: string): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n let currentDir = startDir;\n\n while (true) {\n if (\n builtins.fs.existsSync(\n builtins.path.join(currentDir, 'pnpm-workspace.yaml'),\n )\n ) {\n return currentDir;\n }\n\n const parentDir = builtins.path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n}\n\nexport function resolveInstalledPackageJsonPathSync(\n packageName: string,\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n let currentDir = process.cwd();\n\n while (true) {\n const packageJsonPath = builtins.path.join(\n currentDir,\n 'node_modules',\n packageName,\n 'package.json',\n );\n\n if (builtins.fs.existsSync(packageJsonPath)) {\n return packageJsonPath;\n }\n\n const parentDir = builtins.path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n}\n\nexport function resolveWorkspacePackageJsonPathSync(\n packageName: string,\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const workspaceRoot = findWorkspaceRootSync(process.cwd());\n if (!workspaceRoot) {\n return null;\n }\n\n const workspacePackagesDir = builtins.path.join(workspaceRoot, 'packages');\n if (!builtins.fs.existsSync(workspacePackagesDir)) {\n return null;\n }\n\n for (const packageDirName of builtins.fs.readdirSync(workspacePackagesDir)) {\n const packageJsonPath = builtins.path.join(\n workspacePackagesDir,\n packageDirName,\n 'package.json',\n );\n if (!builtins.fs.existsSync(packageJsonPath)) {\n continue;\n }\n\n try {\n const packageJson = JSON.parse(\n builtins.fs.readFileSync(packageJsonPath, 'utf-8'),\n ) as { name?: string };\n if (packageJson.name === packageName) {\n return packageJsonPath;\n }\n } catch {\n // Ignore unreadable workspace package metadata and continue scanning.\n }\n }\n\n return null;\n}\n\nexport function resolveWorkspaceSourceManifestPathSync(\n packageDir: string,\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const candidates = [\n builtins.path.join(packageDir, 'src', 'manifest', 'manifest.json'),\n builtins.path.join(packageDir, '.smrt', 'manifest.json'),\n ];\n\n for (const candidate of candidates) {\n if (builtins.fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return null;\n}\n\nexport function resolveManifestExportPathSync(\n packageName: string,\n options: ManifestLoadOptions = {},\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const shouldWarn = options.warn ?? true;\n const packageJsonPath =\n resolveInstalledPackageJsonPathSync(packageName) ||\n resolveWorkspacePackageJsonPathSync(packageName);\n\n if (!packageJsonPath) {\n return null;\n }\n\n const packageDir = builtins.path.dirname(packageJsonPath);\n const packageJson = JSON.parse(\n builtins.fs.readFileSync(packageJsonPath, 'utf-8'),\n ) as {\n exports?: Record<\n string,\n string | { default?: string; import?: string; require?: string }\n >;\n };\n const manifestExports = ['./manifest.json', './manifest'];\n\n for (const exportKey of manifestExports) {\n const manifestExport = packageJson.exports?.[exportKey];\n if (!manifestExport) {\n continue;\n }\n\n const manifestRelativePath =\n typeof manifestExport === 'string'\n ? manifestExport\n : manifestExport.import ||\n manifestExport.default ||\n manifestExport.require;\n\n if (!manifestRelativePath) {\n recordRegistryDiagnostic(\n 'error',\n 'MANIFEST_EXPORT_INVALID',\n `Package ${packageName} has invalid manifest export configuration for ${exportKey}`,\n { packageName, exportKey },\n );\n if (shouldWarn) {\n logger.warn(\n `Package ${packageName} has invalid manifest export configuration for ${exportKey}`,\n );\n }\n return null;\n }\n\n if (!manifestRelativePath.endsWith('.json')) {\n recordRegistryDiagnostic(\n 'error',\n 'MANIFEST_EXPORT_NOT_JSON',\n `Package ${packageName} must export a JSON manifest for ${exportKey}, received ${manifestRelativePath}`,\n { packageName, exportKey, manifestRelativePath },\n );\n if (shouldWarn) {\n logger.warn(\n `Package ${packageName} must export a JSON manifest for ${exportKey}, received ${manifestRelativePath}`,\n );\n }\n return null;\n }\n\n const manifestPath = builtins.path.join(packageDir, manifestRelativePath);\n if (builtins.fs.existsSync(manifestPath)) {\n return manifestPath;\n }\n\n const workspaceSourceManifest =\n resolveWorkspaceSourceManifestPathSync(packageDir);\n if (workspaceSourceManifest) {\n return workspaceSourceManifest;\n }\n\n recordRegistryDiagnostic(\n 'error',\n 'MANIFEST_EXPORT_NOT_FOUND',\n `Package ${packageName} declares manifest export ${manifestRelativePath}, but no manifest file was found.`,\n { packageName, exportKey, manifestRelativePath },\n );\n if (shouldWarn) {\n logger.warn(\n `Package ${packageName} declares manifest export ${manifestRelativePath}, but no manifest file was found.`,\n );\n }\n return null;\n }\n\n return null;\n}\n\n// ── Manifest reading (seeds caches) ──────────────────────────────────────\n\n/**\n * Load smrt-core's own bundled manifest from disk, caching in\n * `__smrtManifestStatic`. Resolves against this module's own `import.meta.url`\n * so paths work whether the code is running from `dist/` or `src/`.\n */\nexport function loadStaticManifestSyncWithNode(): SmartObjectManifest | null {\n const globals = getManifestGlobals();\n\n if (globals.__smrtManifestStatic !== undefined) {\n return globals.__smrtManifestStatic ?? null;\n }\n\n const builtins = getNodeBuiltins();\n globals.__smrtManifestStaticLoadAttempted = true;\n if (!builtins) {\n const fallbackManifest = createEmptyStaticManifest();\n globals.__smrtManifestStatic = fallbackManifest;\n bumpRegistryGeneration();\n return fallbackManifest;\n }\n\n // store.ts lives at src/manifest/store.ts (source) → dist/manifest/store.js\n // (compiled). In src, the static manifest is a sibling JSON; in dist, it is\n // the package's dist/manifest.json one level up.\n const candidates = import.meta.url.endsWith('.ts')\n ? [\n new URL('./static-manifest.json', import.meta.url),\n new URL('../../dist/manifest.json', import.meta.url),\n ]\n : [new URL('../manifest.json', import.meta.url)];\n\n for (const candidate of candidates) {\n try {\n if (!builtins.fs.existsSync(candidate)) {\n continue;\n }\n\n const manifest = JSON.parse(\n builtins.fs.readFileSync(candidate, 'utf-8'),\n ) as SmartObjectManifest;\n\n if (!manifest.objects || typeof manifest.objects !== 'object') {\n continue;\n }\n\n const cachedManifest = manifest.packageName\n ? manifest\n : { ...manifest, packageName: '@happyvertical/smrt-core' };\n globals.__smrtManifestStatic = cachedManifest;\n bumpRegistryGeneration();\n return cachedManifest;\n } catch {\n // Try the next candidate and fall back to the empty manifest if needed.\n }\n }\n\n const fallbackManifest = createEmptyStaticManifest();\n globals.__smrtManifestStatic = fallbackManifest;\n bumpRegistryGeneration();\n return fallbackManifest;\n}\n\n/**\n * Load a package's published manifest by package name, caching in\n * `__smrtManifestCache` under the package key. Returns null on miss or\n * invalid shape; records a diagnostic instead of throwing.\n */\nexport function loadExternalManifestSyncWithNode(\n packageName: string,\n options: ManifestLoadOptions = {},\n): SmartObjectManifest | null {\n const cache = getManifestCache();\n\n if (cache.has(packageName)) {\n return cache.get(packageName) || null;\n }\n\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const manifestPath = resolveManifestExportPathSync(packageName, options);\n if (!manifestPath) {\n return null;\n }\n\n try {\n const manifest = JSON.parse(\n builtins.fs.readFileSync(manifestPath, 'utf-8'),\n ) as SmartObjectManifest;\n\n if (!manifest.objects || typeof manifest.objects !== 'object') {\n if (options.warn ?? true) {\n logger.warn(`Invalid manifest structure for package ${packageName}`);\n }\n return null;\n }\n\n const cachedManifest = manifest.packageName\n ? manifest\n : { ...manifest, packageName };\n\n cache.set(packageName, cachedManifest);\n\n return cachedManifest;\n } catch (error) {\n if (options.warn ?? true) {\n logger.warn(\n `Failed to load manifest for package ${packageName}: ${error instanceof Error ? error.message : error}`,\n );\n }\n return null;\n }\n}\n\n/**\n * Load a manifest from an explicit filesystem path, caching in\n * `__smrtManifestCache` under the manifest's packageName (or the path as a\n * fallback key). Used by `loadAllManifests({ manifestPaths })` in registry.ts\n * and by the Release B `ExplicitPathsManifestSource`.\n */\nexport function loadManifestFromPathSyncWithNode(\n manifestPath: string,\n): SmartObjectManifest | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n try {\n const manifest = JSON.parse(\n builtins.fs.readFileSync(manifestPath, 'utf-8'),\n ) as SmartObjectManifest;\n\n if (!manifest.objects || typeof manifest.objects !== 'object') {\n logger.warn(`Invalid manifest structure at ${manifestPath}`);\n return null;\n }\n\n getManifestCache().set(manifest.packageName || manifestPath, manifest);\n\n return manifest;\n } catch (error) {\n logger.warn(\n `Failed to load manifest from path ${manifestPath}: ${error instanceof Error ? error.message : error}`,\n );\n return null;\n }\n}\n\n/**\n * Synchronous lookup across every cached manifest source, in priority order.\n *\n * Matches the historical order from manifest-loader.ts and registry.ts:\n * local test → core test → static (smrt-core bundled) → external cache.\n * The Release B `CompositeManifestSource` wraps the same priority behind a\n * higher-level abstraction.\n */\nexport function discoverCachedManifestSync(\n className: string,\n): SmartObjectDefinition | undefined {\n const manifests: Array<SmartObjectManifest | null | undefined> = [\n getLocalTestManifestCache(),\n getTestManifestCache(),\n loadStaticManifestSyncWithNode(),\n ...getManifestCache().values(),\n ];\n\n for (const manifest of manifests) {\n const entry = lookupCachedManifestEntry(manifest, className);\n if (entry) {\n return entry;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;;;;AAY7C,SAAgB,oBAA6B;CAC3C,OAAA,QAAA,IAAA,aAC2B,UACzB,QAAQ,IAAI,WAAW,UACvB,QAAQ,IAAI,mBAAmB,KAAA;AAEnC;;;;;;;;;AAUA,SAAgB,wBAAuC;CACrD,MAAM,sBAAsB,QAAQ,IAAI;CACxC,IAAI,qBACF,OAAO;CAGT,MAAM,WAAW,gBAAgB;CACjC,IAAI,CAAC,UACH,OAAO;CAGT,IAAI,aAAa,QAAQ,IAAI;CAE7B,OAAO,MAAM;EACX,MAAM,kBAAkB,SAAS,KAAK,KAAK,YAAY,cAAc;EACrE,IAAI,SAAS,GAAG,WAAW,eAAe,GACxC,IAAI;GAIF,OAHoB,KAAK,MACvB,SAAS,GAAG,aAAa,iBAAiB,OAAO,CAE5C,CAAA,CAAY,QAAQ;EAC7B,QAAQ;GACN,OAAO;EACT;EAGF,MAAM,YAAY,SAAS,KAAK,QAAQ,UAAU;EAClD,IAAI,cAAc,YAChB,OAAO;EAGT,aAAa;CACf;AACF;;;;;;AAOA,SAAgB,6BAAsC;CACpD,IAAI,CAAC,kBAAkB,GACrB,OAAO;CAGT,MAAM,qBAAqB,sBAAsB;CACjD,IAAI,oBACF,OAAO,uBAAuB;CA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iBAAiB,CAAC,CAAC,OAAO;CAC/B;CAEA,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,QAAQ,0BAA0B,UAAU,SAAS;EAC3D,IAAI,OACF,OAAO;CAEX;AAGF"}
|
|
1
|
+
{"version":3,"file":"store.js","names":[],"sources":["../../src/manifest/store.ts"],"sourcesContent":["/**\n * Leaf manifest storage + pure fs/URL helpers.\n *\n * This module has **no dependency on ObjectRegistry, registry.ts, or\n * class-registration.ts**. It owns the globalThis manifest caches and the\n * filesystem helpers that resolve and read manifest.json files from the\n * workspace, installed node_modules, and smrt-core's own bundle.\n *\n * Breaking the cycle: Before this module existed, `registry.ts` and\n * `manifest-loader.ts` both maintained their own copies of these helpers\n * (`registry.ts` had its own because `registerPackageManifest` needed them\n * and could not import `manifest-loader.ts` due to a module cycle —\n * `registry.ts → class-registration.ts → manifest-loader.ts → registry.ts`).\n * Centralizing them here lets both files import from a leaf, so the cycle\n * goes away and Release B's `ManifestSource` abstraction can live above\n * this leaf without re-creating it.\n *\n * @see https://github.com/happyvertical/smrt/issues/1133\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { recordRegistryDiagnostic } from '../registry/diagnostics.js';\nimport {\n bumpRegistryGeneration,\n createGenerationTrackedMap,\n isGenerationTrackedMap,\n} from '../registry/generation.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport type { ColumnDefinition } from '../schema/types.js';\nimport {\n createQualifiedName,\n isQualifiedName,\n parseQualifiedName,\n} from '../utils/qualified-names.js';\n\nconst logger = createLogger({ level: 'info' });\n\nexport type ManifestLoadOptions = {\n warn?: boolean;\n};\n\n// ── Runtime environment detection ────────────────────────────────────────\n\n/**\n * Detect whether we're running inside a test runner. Test manifests must\n * never load in production to avoid test classes colliding with real ones.\n */\nexport function isTestEnvironment(): boolean {\n return (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n process.env.JEST_WORKER_ID !== undefined\n );\n}\n\n/**\n * Best-effort detection of the current package under test.\n *\n * In workspace consumers, `process.cwd()` points at the consuming app/package,\n * while in smrt-core's own tests it points at `packages/core`. We use that\n * distinction to keep smrt-core's internal test manifest scoped to its own\n * test suite instead of leaking those fixtures into every consumer test run.\n */\nexport function getCurrentPackageName(): string | null {\n const explicitPackageName = process.env.npm_package_name;\n if (explicitPackageName) {\n return explicitPackageName;\n }\n\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n let currentDir = process.cwd();\n\n while (true) {\n const packageJsonPath = builtins.path.join(currentDir, 'package.json');\n if (builtins.fs.existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(\n builtins.fs.readFileSync(packageJsonPath, 'utf-8'),\n ) as { name?: string };\n return packageJson.name ?? null;\n } catch {\n return null;\n }\n }\n\n const parentDir = builtins.path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n}\n\n/**\n * smrt-core's committed test manifest is for smrt-core's own tests only.\n * Consumer packages should expose only their local test manifest plus real\n * published manifests from dependencies.\n */\nexport function shouldLoadCoreTestManifest(): boolean {\n if (!isTestEnvironment()) {\n return false;\n }\n\n const currentPackageName = getCurrentPackageName();\n if (currentPackageName) {\n return currentPackageName === '@happyvertical/smrt-core';\n }\n\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return false;\n }\n\n const moduleDir = builtins.path.dirname(\n builtins.url.fileURLToPath(import.meta.url),\n );\n const workspaceRoot = findWorkspaceRootSync(moduleDir);\n if (!workspaceRoot) {\n return false;\n }\n\n const corePackageDir = builtins.path.join(workspaceRoot, 'packages', 'core');\n const relative = builtins.path.relative(corePackageDir, process.cwd());\n return (\n relative === '' ||\n (!relative.startsWith('..') && !builtins.path.isAbsolute(relative))\n );\n}\n\n// ── Node builtins access ─────────────────────────────────────────────────\n\n/**\n * Resolve Node's built-in `fs`/`path`/`url` modules without a static import.\n *\n * `process.getBuiltinModule()` is a Node 22+ API that returns the live\n * built-in without going through the module loader. This avoids Vite's\n * static-import analysis flagging these builtins and simulated\n * \"externalized for browser\" warnings in bundled browser builds.\n */\nexport function getNodeBuiltins() {\n const getBuiltinModule = (\n process as typeof process & {\n getBuiltinModule?: (id: string) => unknown;\n }\n ).getBuiltinModule;\n if (typeof getBuiltinModule !== 'function') {\n return null;\n }\n\n const fs = getBuiltinModule('node:fs') as\n | typeof import('node:fs')\n | undefined;\n const path = getBuiltinModule('node:path') as\n | typeof import('node:path')\n | undefined;\n const url = getBuiltinModule('node:url') as\n | typeof import('node:url')\n | undefined;\n\n if (!fs || !path || !url) {\n return null;\n }\n\n return { fs, path, url };\n}\n\n// ── globalThis cache accessors ───────────────────────────────────────────\n\ntype ManifestGlobals = typeof globalThis & {\n __smrtManifestStatic?: SmartObjectManifest | null;\n __smrtManifestStaticLoadAttempted?: boolean;\n __smrtManifestTest?: SmartObjectManifest | null;\n __smrtManifestLocalTest?: SmartObjectManifest | null;\n __smrtManifestCache?: Map<string, SmartObjectManifest>;\n};\n\nfunction getManifestGlobals(): ManifestGlobals {\n return globalThis as ManifestGlobals;\n}\n\n/**\n * Return the mutable external-manifest cache, creating it if absent.\n *\n * Writers: `registerPackageManifest()` (Release A, each package's shim),\n * `loadExternalManifestSyncWithNode()`, `loadManifestFromPathSyncWithNode()`.\n * Readers: all discovery paths.\n */\nexport function getManifestCache(): Map<string, SmartObjectManifest> {\n const globals = getManifestGlobals();\n const current = globals.__smrtManifestCache;\n if (current && isGenerationTrackedMap(current)) {\n return current;\n }\n // A newly cached manifest can change what manifest discovery returns, so\n // it invalidates the generation-keyed registry memos (#3047).\n const tracked = createGenerationTrackedMap<string, SmartObjectManifest>(\n current,\n );\n globals.__smrtManifestCache = tracked;\n return tracked;\n}\n\n/** Read-only snapshot of the static manifest, if cached. */\nexport function getStaticManifestCache(): SmartObjectManifest | null {\n return getManifestGlobals().__smrtManifestStatic ?? null;\n}\n\n/** Read-only snapshot of the core test manifest, if cached. */\nexport function getTestManifestCache(): SmartObjectManifest | null {\n return getManifestGlobals().__smrtManifestTest ?? null;\n}\n\n/**\n * Read-only snapshot of the local (domain package) test manifest.\n *\n * Preserves the three-state semantics that `discoverManifestEntry()` relies\n * on: `undefined` means \"never attempted to load\" and triggers the lazy\n * loader; `null` means \"attempted but no local test manifest in this\n * package\"; a manifest object means \"loaded\". Do not collapse `undefined`\n * to `null` here — the async-discovery lazy-load path keys off the\n * distinction (see manifest-loader.ts:`if (getLocalTestManifestCache() === undefined) loadLocalTestManifestSync()`).\n */\nexport function getLocalTestManifestCache():\n | SmartObjectManifest\n | null\n | undefined {\n return getManifestGlobals().__smrtManifestLocalTest;\n}\n\n// ── Manifest shape helpers ───────────────────────────────────────────────\n\nexport function createEmptyStaticManifest(): SmartObjectManifest {\n return {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n packageName: '@happyvertical/smrt-core',\n };\n}\n\n/**\n * Deep-clone a manifest's schema column map so downstream mutators don't\n * corrupt the cached manifest. Foreign-key descriptors get their own copy\n * because manifest-loader.ts and registerFromManifest() both splice them\n * into live schema entries.\n */\nexport function cloneManifestSchemaColumns(\n columns: Record<string, unknown> | undefined,\n): Record<string, ColumnDefinition> {\n return Object.fromEntries(\n Object.entries(columns || {}).map(([columnName, column]) => {\n const clonedColumn = {\n ...(column as ColumnDefinition & Record<string, unknown>),\n } as ColumnDefinition;\n const manifestDefault = (\n clonedColumn as ColumnDefinition & {\n default?: unknown;\n }\n ).default;\n\n if (\n clonedColumn.defaultValue === undefined &&\n manifestDefault !== undefined\n ) {\n clonedColumn.defaultValue = manifestDefault;\n }\n\n if (clonedColumn.foreignKey) {\n clonedColumn.foreignKey = { ...clonedColumn.foreignKey };\n }\n\n return [columnName, clonedColumn];\n }),\n ) as Record<string, ColumnDefinition>;\n}\n\n/**\n * Look up a class definition inside a single manifest.\n *\n * Tries qualified-key, simple-name, and lowercase-name lookups, then falls\n * back to iterating every entry in the manifest comparing lowered names.\n * This is the low-level primitive used by every sync discovery path.\n */\nexport function lookupCachedManifestEntry(\n manifest: SmartObjectManifest | null | undefined,\n className: string,\n): SmartObjectDefinition | undefined {\n if (!manifest?.objects) {\n return undefined;\n }\n\n const requestedQualifiedName = isQualifiedName(className)\n ? className\n : undefined;\n const requestedClassName = requestedQualifiedName\n ? parseQualifiedName(requestedQualifiedName).className\n : className;\n const lowerClassName = requestedClassName.toLowerCase();\n const packageName = manifest.packageName;\n const qualifiedKey =\n requestedQualifiedName ||\n (packageName\n ? createQualifiedName(packageName, requestedClassName)\n : undefined);\n\n // A qualified request names one package's class. Another package's\n // manifest can only answer it by an exact qualified key (aggregated\n // manifests); a simple-name hit there is a different class (#3098).\n const requestedPackage = requestedQualifiedName\n ? parseQualifiedName(requestedQualifiedName).packageName\n : undefined;\n if (\n requestedQualifiedName &&\n packageName !== undefined &&\n packageName !== requestedPackage\n ) {\n const direct = manifest.objects[requestedQualifiedName];\n return direct &&\n (direct.packageName === undefined ||\n direct.packageName === requestedPackage)\n ? direct\n : undefined;\n }\n\n return (\n (qualifiedKey ? manifest.objects[qualifiedKey] : undefined) ||\n manifest.objects[requestedClassName] ||\n manifest.objects[lowerClassName] ||\n Object.values(manifest.objects).find((entry) => {\n if (!entry) {\n return false;\n }\n\n if (entry.className?.toLowerCase() === lowerClassName) {\n return true;\n }\n\n return (\n requestedQualifiedName !== undefined &&\n packageName !== undefined &&\n createQualifiedName(packageName, entry.className || '') ===\n requestedQualifiedName\n );\n })\n );\n}\n\n// ── Filesystem helpers ───────────────────────────────────────────────────\n\nexport function findWorkspaceRootSync(startDir: string): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n let currentDir = startDir;\n\n while (true) {\n if (\n builtins.fs.existsSync(\n builtins.path.join(currentDir, 'pnpm-workspace.yaml'),\n )\n ) {\n return currentDir;\n }\n\n const parentDir = builtins.path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n}\n\nexport function resolveInstalledPackageJsonPathSync(\n packageName: string,\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n let currentDir = process.cwd();\n\n while (true) {\n const packageJsonPath = builtins.path.join(\n currentDir,\n 'node_modules',\n packageName,\n 'package.json',\n );\n\n if (builtins.fs.existsSync(packageJsonPath)) {\n return packageJsonPath;\n }\n\n const parentDir = builtins.path.dirname(currentDir);\n if (parentDir === currentDir) {\n return null;\n }\n\n currentDir = parentDir;\n }\n}\n\nexport function resolveWorkspacePackageJsonPathSync(\n packageName: string,\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const workspaceRoot = findWorkspaceRootSync(process.cwd());\n if (!workspaceRoot) {\n return null;\n }\n\n const workspacePackagesDir = builtins.path.join(workspaceRoot, 'packages');\n if (!builtins.fs.existsSync(workspacePackagesDir)) {\n return null;\n }\n\n for (const packageDirName of builtins.fs.readdirSync(workspacePackagesDir)) {\n const packageJsonPath = builtins.path.join(\n workspacePackagesDir,\n packageDirName,\n 'package.json',\n );\n if (!builtins.fs.existsSync(packageJsonPath)) {\n continue;\n }\n\n try {\n const packageJson = JSON.parse(\n builtins.fs.readFileSync(packageJsonPath, 'utf-8'),\n ) as { name?: string };\n if (packageJson.name === packageName) {\n return packageJsonPath;\n }\n } catch {\n // Ignore unreadable workspace package metadata and continue scanning.\n }\n }\n\n return null;\n}\n\nexport function resolveWorkspaceSourceManifestPathSync(\n packageDir: string,\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const candidates = [\n builtins.path.join(packageDir, 'src', 'manifest', 'manifest.json'),\n builtins.path.join(packageDir, '.smrt', 'manifest.json'),\n ];\n\n for (const candidate of candidates) {\n if (builtins.fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return null;\n}\n\nexport function resolveManifestExportPathSync(\n packageName: string,\n options: ManifestLoadOptions = {},\n): string | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const shouldWarn = options.warn ?? true;\n const packageJsonPath =\n resolveInstalledPackageJsonPathSync(packageName) ||\n resolveWorkspacePackageJsonPathSync(packageName);\n\n if (!packageJsonPath) {\n return null;\n }\n\n const packageDir = builtins.path.dirname(packageJsonPath);\n const packageJson = JSON.parse(\n builtins.fs.readFileSync(packageJsonPath, 'utf-8'),\n ) as {\n exports?: Record<\n string,\n string | { default?: string; import?: string; require?: string }\n >;\n };\n const manifestExports = ['./manifest.json', './manifest'];\n\n for (const exportKey of manifestExports) {\n const manifestExport = packageJson.exports?.[exportKey];\n if (!manifestExport) {\n continue;\n }\n\n const manifestRelativePath =\n typeof manifestExport === 'string'\n ? manifestExport\n : manifestExport.import ||\n manifestExport.default ||\n manifestExport.require;\n\n if (!manifestRelativePath) {\n recordRegistryDiagnostic(\n 'error',\n 'MANIFEST_EXPORT_INVALID',\n `Package ${packageName} has invalid manifest export configuration for ${exportKey}`,\n { packageName, exportKey },\n );\n if (shouldWarn) {\n logger.warn(\n `Package ${packageName} has invalid manifest export configuration for ${exportKey}`,\n );\n }\n return null;\n }\n\n if (!manifestRelativePath.endsWith('.json')) {\n recordRegistryDiagnostic(\n 'error',\n 'MANIFEST_EXPORT_NOT_JSON',\n `Package ${packageName} must export a JSON manifest for ${exportKey}, received ${manifestRelativePath}`,\n { packageName, exportKey, manifestRelativePath },\n );\n if (shouldWarn) {\n logger.warn(\n `Package ${packageName} must export a JSON manifest for ${exportKey}, received ${manifestRelativePath}`,\n );\n }\n return null;\n }\n\n const manifestPath = builtins.path.join(packageDir, manifestRelativePath);\n if (builtins.fs.existsSync(manifestPath)) {\n return manifestPath;\n }\n\n const workspaceSourceManifest =\n resolveWorkspaceSourceManifestPathSync(packageDir);\n if (workspaceSourceManifest) {\n return workspaceSourceManifest;\n }\n\n recordRegistryDiagnostic(\n 'error',\n 'MANIFEST_EXPORT_NOT_FOUND',\n `Package ${packageName} declares manifest export ${manifestRelativePath}, but no manifest file was found.`,\n { packageName, exportKey, manifestRelativePath },\n );\n if (shouldWarn) {\n logger.warn(\n `Package ${packageName} declares manifest export ${manifestRelativePath}, but no manifest file was found.`,\n );\n }\n return null;\n }\n\n return null;\n}\n\n// ── Manifest reading (seeds caches) ──────────────────────────────────────\n\n/**\n * Load smrt-core's own bundled manifest from disk, caching in\n * `__smrtManifestStatic`. Resolves against this module's own `import.meta.url`\n * so paths work whether the code is running from `dist/` or `src/`.\n */\nexport function loadStaticManifestSyncWithNode(): SmartObjectManifest | null {\n const globals = getManifestGlobals();\n\n if (globals.__smrtManifestStatic !== undefined) {\n return globals.__smrtManifestStatic ?? null;\n }\n\n const builtins = getNodeBuiltins();\n globals.__smrtManifestStaticLoadAttempted = true;\n if (!builtins) {\n const fallbackManifest = createEmptyStaticManifest();\n globals.__smrtManifestStatic = fallbackManifest;\n bumpRegistryGeneration();\n return fallbackManifest;\n }\n\n // store.ts lives at src/manifest/store.ts (source) → dist/manifest/store.js\n // (compiled). In src, the static manifest is a sibling JSON; in dist, it is\n // the package's dist/manifest.json one level up.\n const candidates = import.meta.url.endsWith('.ts')\n ? [\n new URL('./static-manifest.json', import.meta.url),\n new URL('../../dist/manifest.json', import.meta.url),\n ]\n : [new URL('../manifest.json', import.meta.url)];\n\n for (const candidate of candidates) {\n try {\n if (!builtins.fs.existsSync(candidate)) {\n continue;\n }\n\n const manifest = JSON.parse(\n builtins.fs.readFileSync(candidate, 'utf-8'),\n ) as SmartObjectManifest;\n\n if (!manifest.objects || typeof manifest.objects !== 'object') {\n continue;\n }\n\n const cachedManifest = manifest.packageName\n ? manifest\n : { ...manifest, packageName: '@happyvertical/smrt-core' };\n globals.__smrtManifestStatic = cachedManifest;\n bumpRegistryGeneration();\n return cachedManifest;\n } catch {\n // Try the next candidate and fall back to the empty manifest if needed.\n }\n }\n\n const fallbackManifest = createEmptyStaticManifest();\n globals.__smrtManifestStatic = fallbackManifest;\n bumpRegistryGeneration();\n return fallbackManifest;\n}\n\n/**\n * Load a package's published manifest by package name, caching in\n * `__smrtManifestCache` under the package key. Returns null on miss or\n * invalid shape; records a diagnostic instead of throwing.\n */\nexport function loadExternalManifestSyncWithNode(\n packageName: string,\n options: ManifestLoadOptions = {},\n): SmartObjectManifest | null {\n const cache = getManifestCache();\n\n if (cache.has(packageName)) {\n return cache.get(packageName) || null;\n }\n\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n const manifestPath = resolveManifestExportPathSync(packageName, options);\n if (!manifestPath) {\n return null;\n }\n\n try {\n const manifest = JSON.parse(\n builtins.fs.readFileSync(manifestPath, 'utf-8'),\n ) as SmartObjectManifest;\n\n if (!manifest.objects || typeof manifest.objects !== 'object') {\n if (options.warn ?? true) {\n logger.warn(`Invalid manifest structure for package ${packageName}`);\n }\n return null;\n }\n\n const cachedManifest = manifest.packageName\n ? manifest\n : { ...manifest, packageName };\n\n cache.set(packageName, cachedManifest);\n\n return cachedManifest;\n } catch (error) {\n if (options.warn ?? true) {\n logger.warn(\n `Failed to load manifest for package ${packageName}: ${error instanceof Error ? error.message : error}`,\n );\n }\n return null;\n }\n}\n\n/**\n * Load a manifest from an explicit filesystem path, caching in\n * `__smrtManifestCache` under the manifest's packageName (or the path as a\n * fallback key). Used by `loadAllManifests({ manifestPaths })` in registry.ts\n * and by the Release B `ExplicitPathsManifestSource`.\n */\nexport function loadManifestFromPathSyncWithNode(\n manifestPath: string,\n): SmartObjectManifest | null {\n const builtins = getNodeBuiltins();\n if (!builtins) {\n return null;\n }\n\n try {\n const manifest = JSON.parse(\n builtins.fs.readFileSync(manifestPath, 'utf-8'),\n ) as SmartObjectManifest;\n\n if (!manifest.objects || typeof manifest.objects !== 'object') {\n logger.warn(`Invalid manifest structure at ${manifestPath}`);\n return null;\n }\n\n getManifestCache().set(manifest.packageName || manifestPath, manifest);\n\n return manifest;\n } catch (error) {\n logger.warn(\n `Failed to load manifest from path ${manifestPath}: ${error instanceof Error ? error.message : error}`,\n );\n return null;\n }\n}\n\n/**\n * Synchronous lookup across every cached manifest source, in priority order.\n *\n * Matches the historical order from manifest-loader.ts and registry.ts:\n * local test → core test → static (smrt-core bundled) → external cache.\n * The Release B `CompositeManifestSource` wraps the same priority behind a\n * higher-level abstraction.\n */\nexport function discoverCachedManifestSync(\n className: string,\n): SmartObjectDefinition | undefined {\n const manifests: Array<SmartObjectManifest | null | undefined> = [\n getLocalTestManifestCache(),\n getTestManifestCache(),\n loadStaticManifestSyncWithNode(),\n ...getManifestCache().values(),\n ];\n\n for (const manifest of manifests) {\n const entry = lookupCachedManifestEntry(manifest, className);\n if (entry) {\n return entry;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;;;;AAY7C,SAAgB,oBAA6B;CAC3C,OAAA,QAAA,IAAA,aAC2B,UACzB,QAAQ,IAAI,WAAW,UACvB,QAAQ,IAAI,mBAAmB,KAAA;AAEnC;;;;;;;;;AAUA,SAAgB,wBAAuC;CACrD,MAAM,sBAAsB,QAAQ,IAAI;CACxC,IAAI,qBACF,OAAO;CAGT,MAAM,WAAW,gBAAgB;CACjC,IAAI,CAAC,UACH,OAAO;CAGT,IAAI,aAAa,QAAQ,IAAI;CAE7B,OAAO,MAAM;EACX,MAAM,kBAAkB,SAAS,KAAK,KAAK,YAAY,cAAc;EACrE,IAAI,SAAS,GAAG,WAAW,eAAe,GACxC,IAAI;GAIF,OAHoB,KAAK,MACvB,SAAS,GAAG,aAAa,iBAAiB,OAAO,CAE5C,CAAA,CAAY,QAAQ;EAC7B,QAAQ;GACN,OAAO;EACT;EAGF,MAAM,YAAY,SAAS,KAAK,QAAQ,UAAU;EAClD,IAAI,cAAc,YAChB,OAAO;EAGT,aAAa;CACf;AACF;;;;;;AAOA,SAAgB,6BAAsC;CACpD,IAAI,CAAC,kBAAkB,GACrB,OAAO;CAGT,MAAM,qBAAqB,sBAAsB;CACjD,IAAI,oBACF,OAAO,uBAAuB;CAGhC,MA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C,CAAC,OAAO;CAC/B;CAEA,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,QAAQ,0BAA0B,UAAU,SAAS;EAC3D,IAAI,OACF,OAAO;CAEX;AAGF"}
|
package/dist/manifest.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": "1.0.0",
|
|
3
3
|
"timestamp": 0,
|
|
4
4
|
"packageName": "@happyvertical/smrt-core",
|
|
5
|
-
"packageVersion": "0.51.
|
|
5
|
+
"packageVersion": "0.51.32",
|
|
6
6
|
"objects": {
|
|
7
7
|
"@happyvertical/smrt-core:SmrtClass": {
|
|
8
8
|
"name": "smrtclass",
|
|
@@ -1280,6 +1280,25 @@
|
|
|
1280
1280
|
"isStatic": false,
|
|
1281
1281
|
"isPublic": true
|
|
1282
1282
|
},
|
|
1283
|
+
"evaluate": {
|
|
1284
|
+
"name": "evaluate",
|
|
1285
|
+
"async": true,
|
|
1286
|
+
"parameters": [
|
|
1287
|
+
{
|
|
1288
|
+
"name": "criteria",
|
|
1289
|
+
"type": "string",
|
|
1290
|
+
"optional": false
|
|
1291
|
+
},
|
|
1292
|
+
{
|
|
1293
|
+
"name": "options",
|
|
1294
|
+
"type": "EvaluateOptions",
|
|
1295
|
+
"optional": true
|
|
1296
|
+
}
|
|
1297
|
+
],
|
|
1298
|
+
"returnType": "Promise<EvaluationResult>",
|
|
1299
|
+
"isStatic": false,
|
|
1300
|
+
"isPublic": true
|
|
1301
|
+
},
|
|
1283
1302
|
"do": {
|
|
1284
1303
|
"name": "do",
|
|
1285
1304
|
"async": true,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ColumnDefinition, SchemaChange, SchemaDefinition, SchemaDiff, SQLDataType } from '../schema/types.js';
|
|
2
|
-
import { DatabaseInterface } from './types.js';
|
|
2
|
+
import { DatabaseInterface, SqlTableSchemaInfo } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* `mismatch.actual` of the manual change reported when a required column
|
|
5
5
|
* could not be added to a populated table (#3008): the column is absent.
|
|
@@ -66,6 +66,15 @@ export interface DiffOptions {
|
|
|
66
66
|
postgresTimestampMigration?: {
|
|
67
67
|
legacyTimezone: 'UTC';
|
|
68
68
|
};
|
|
69
|
+
/**
|
|
70
|
+
* How many live-table introspections `compare()` runs concurrently while
|
|
71
|
+
* prefetching every existing manifest table's schema. Defaults to
|
|
72
|
+
* {@link POSTGRES_INTROSPECTION_CONCURRENCY} on PostgreSQL (each
|
|
73
|
+
* `getTableSchema()` is several catalog round trips, so a wide schema over a
|
|
74
|
+
* high-latency link is otherwise dominated by sequential RTTs) and to 1 —
|
|
75
|
+
* the original sequential behavior — on every other engine.
|
|
76
|
+
*/
|
|
77
|
+
introspectionConcurrency?: number;
|
|
69
78
|
}
|
|
70
79
|
/**
|
|
71
80
|
* Name of the unique index that backs a `unique: true` column. Mirrors the
|
|
@@ -186,6 +195,16 @@ export declare class SchemaComparer {
|
|
|
186
195
|
* needed because nothing survives past one `compare()` call).
|
|
187
196
|
*/
|
|
188
197
|
private renameDataPendingCache;
|
|
198
|
+
/**
|
|
199
|
+
* Partial-index predicates for every `public` table, read in one catalog
|
|
200
|
+
* query per `compare()` run instead of one `pg_indexes` query per table.
|
|
201
|
+
* Same lifetime as {@link renameDataPendingCache}: set inside `compare()`,
|
|
202
|
+
* cleared in its `finally`. `null` means "not precomputed" (standalone
|
|
203
|
+
* `compareTable()`, a non-PostgreSQL engine, or the batched read failed),
|
|
204
|
+
* in which case {@link getDbIndexPredicates} falls back to the per-table
|
|
205
|
+
* query.
|
|
206
|
+
*/
|
|
207
|
+
private indexPredicateCache;
|
|
189
208
|
/**
|
|
190
209
|
* Cross-table batch queries stay bounded regardless of schema shape: this
|
|
191
210
|
* caps how many scalar-subquery columns one probe statement packs into a
|
|
@@ -217,6 +236,29 @@ export declare class SchemaComparer {
|
|
|
217
236
|
* introspect it.
|
|
218
237
|
*/
|
|
219
238
|
private getLiveSchema;
|
|
239
|
+
/**
|
|
240
|
+
* The live table schemas read by the most recent `compare()` run, keyed by
|
|
241
|
+
* table name. Lets a caller that runs further read-only diagnostics over
|
|
242
|
+
* the same connection in the same command (e.g. `smrt db:status`'s orphan
|
|
243
|
+
* report) reuse them instead of re-introspecting every table. Entries are
|
|
244
|
+
* successful reads only (`getTableSchema()` failures propagate out of
|
|
245
|
+
* `compare()`); `null`/`undefined` mean the adapter reported no table.
|
|
246
|
+
*/
|
|
247
|
+
getLiveSchemaSnapshot(): ReadonlyMap<string, SqlTableSchemaInfo | null | undefined>;
|
|
248
|
+
/**
|
|
249
|
+
* Memoize several tables' live schemas with bounded concurrency. Same
|
|
250
|
+
* reads, same failure behavior as calling {@link getLiveSchema} for each
|
|
251
|
+
* in turn (the first failure rejects), but PostgreSQL keeps up to
|
|
252
|
+
* `introspectionConcurrency` introspections in flight on the pool.
|
|
253
|
+
*/
|
|
254
|
+
private prefetchLiveSchemas;
|
|
255
|
+
/**
|
|
256
|
+
* Read every `public` table's partial-index predicates in one query
|
|
257
|
+
* (PostgreSQL only). On failure the cache stays `null` and
|
|
258
|
+
* {@link getDbIndexPredicates} keeps its per-table behavior, including its
|
|
259
|
+
* own fallback to predicate-unaware comparison.
|
|
260
|
+
*/
|
|
261
|
+
private precomputeIndexPredicates;
|
|
220
262
|
/**
|
|
221
263
|
* Plan the pre-R11 `text` -> `uuid` convergence (#2608).
|
|
222
264
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"differ.d.ts","sourceRoot":"","sources":["../../src/migrations/differ.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;
|
|
1
|
+
{"version":3,"file":"differ.d.ts","sourceRoot":"","sources":["../../src/migrations/differ.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAuCH,OAAO,KAAK,EAEV,gBAAgB,EAEhB,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,WAAW,EACZ,MAAM,oBAAoB,CAAC;AAoB5B,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,M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AUD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,EAAE,CAIzD;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,EAAE,CAU5E"}
|
|
@@ -4,6 +4,7 @@ import { foreignKeyConstraintName, foreignKeyRelationshipKey, renderForeignKeyAd
|
|
|
4
4
|
import { renderNullEqualConflictIndex } from "../schema/ddl/null-equal-index.js";
|
|
5
5
|
import { detectEngine, getDDLStrategy } from "../schema/ddl/index.js";
|
|
6
6
|
import { conflictIndexName } from "../schema/conflict-target.js";
|
|
7
|
+
import { mapWithConcurrency } from "../schema/bounded-concurrency.js";
|
|
7
8
|
import { columnsAllValuesUuidShapedBatch, columnsHaveNonEmptyValueBatch, nonEmptyValuePredicate, resolveRenameDataPendingCandidates, uuidInvalidShapePredicate } from "../schema/column-data-probes.js";
|
|
8
9
|
import { maskSampleValue, probeCastSafety, renderJsonbColumnConversion, renderTimestamptzColumnConversion } from "../schema/text-cast-probe.js";
|
|
9
10
|
import { describeForeignKeyTypeConflict, planUuidConvergence, renderUuidConvergenceRepairHint, renderUuidShapeProbe } from "../schema/uuid-convergence.js";
|
|
@@ -348,6 +349,16 @@ var SchemaComparer = class SchemaComparer {
|
|
|
348
349
|
*/
|
|
349
350
|
renameDataPendingCache = null;
|
|
350
351
|
/**
|
|
352
|
+
* Partial-index predicates for every `public` table, read in one catalog
|
|
353
|
+
* query per `compare()` run instead of one `pg_indexes` query per table.
|
|
354
|
+
* Same lifetime as {@link renameDataPendingCache}: set inside `compare()`,
|
|
355
|
+
* cleared in its `finally`. `null` means "not precomputed" (standalone
|
|
356
|
+
* `compareTable()`, a non-PostgreSQL engine, or the batched read failed),
|
|
357
|
+
* in which case {@link getDbIndexPredicates} falls back to the per-table
|
|
358
|
+
* query.
|
|
359
|
+
*/
|
|
360
|
+
indexPredicateCache = null;
|
|
361
|
+
/**
|
|
351
362
|
* Cross-table batch queries stay bounded regardless of schema shape: this
|
|
352
363
|
* caps how many scalar-subquery columns one probe statement packs into a
|
|
353
364
|
* single row. Conservative relative to PostgreSQL's ~1600 column limit
|
|
@@ -387,8 +398,11 @@ var SchemaComparer = class SchemaComparer {
|
|
|
387
398
|
};
|
|
388
399
|
this.liveSchemas.clear();
|
|
389
400
|
this.renameDataPendingCache = null;
|
|
401
|
+
this.indexPredicateCache = null;
|
|
390
402
|
try {
|
|
391
403
|
const existingTables = await this.getExistingTables();
|
|
404
|
+
await this.prefetchLiveSchemas(Object.keys(manifestSchemas).filter((tableName) => existingTables.has(tableName)));
|
|
405
|
+
await this.precomputeIndexPredicates();
|
|
392
406
|
await this.precomputeRenameDataPending(manifestSchemas, existingTables);
|
|
393
407
|
this.uuidConvergence = await this.buildUuidConvergencePlan(manifestSchemas, existingTables);
|
|
394
408
|
for (const change of this.uuidConvergenceChanges(manifestSchemas)) {
|
|
@@ -419,6 +433,7 @@ var SchemaComparer = class SchemaComparer {
|
|
|
419
433
|
return diff;
|
|
420
434
|
} finally {
|
|
421
435
|
this.renameDataPendingCache = null;
|
|
436
|
+
this.indexPredicateCache = null;
|
|
422
437
|
}
|
|
423
438
|
}
|
|
424
439
|
/**
|
|
@@ -504,6 +519,59 @@ var SchemaComparer = class SchemaComparer {
|
|
|
504
519
|
return schema ?? void 0;
|
|
505
520
|
}
|
|
506
521
|
/**
|
|
522
|
+
* The live table schemas read by the most recent `compare()` run, keyed by
|
|
523
|
+
* table name. Lets a caller that runs further read-only diagnostics over
|
|
524
|
+
* the same connection in the same command (e.g. `smrt db:status`'s orphan
|
|
525
|
+
* report) reuse them instead of re-introspecting every table. Entries are
|
|
526
|
+
* successful reads only (`getTableSchema()` failures propagate out of
|
|
527
|
+
* `compare()`); `null`/`undefined` mean the adapter reported no table.
|
|
528
|
+
*/
|
|
529
|
+
getLiveSchemaSnapshot() {
|
|
530
|
+
return new Map(this.liveSchemas);
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Memoize several tables' live schemas with bounded concurrency. Same
|
|
534
|
+
* reads, same failure behavior as calling {@link getLiveSchema} for each
|
|
535
|
+
* in turn (the first failure rejects), but PostgreSQL keeps up to
|
|
536
|
+
* `introspectionConcurrency` introspections in flight on the pool.
|
|
537
|
+
*/
|
|
538
|
+
async prefetchLiveSchemas(tableNames) {
|
|
539
|
+
if (typeof this.db.getTableSchema !== "function") return;
|
|
540
|
+
const pending = tableNames.filter((tableName) => !this.liveSchemas.has(tableName));
|
|
541
|
+
const schemas = await mapWithConcurrency(pending, this.options.introspectionConcurrency ?? (this.engine === "postgres" ? 8 : 1), (tableName) => Promise.resolve(this.db.getTableSchema?.(tableName)));
|
|
542
|
+
pending.forEach((tableName, index) => {
|
|
543
|
+
this.liveSchemas.set(tableName, schemas[index]);
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Read every `public` table's partial-index predicates in one query
|
|
548
|
+
* (PostgreSQL only). On failure the cache stays `null` and
|
|
549
|
+
* {@link getDbIndexPredicates} keeps its per-table behavior, including its
|
|
550
|
+
* own fallback to predicate-unaware comparison.
|
|
551
|
+
*/
|
|
552
|
+
async precomputeIndexPredicates() {
|
|
553
|
+
this.indexPredicateCache = null;
|
|
554
|
+
if (this.engine !== "postgres") return;
|
|
555
|
+
try {
|
|
556
|
+
const result = await this.db.query(`SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname = 'public'`);
|
|
557
|
+
const cache = /* @__PURE__ */ new Map();
|
|
558
|
+
for (const row of result.rows) {
|
|
559
|
+
if (!row.tablename || !row.indexname || !row.indexdef) continue;
|
|
560
|
+
const predicate = extractIndexPredicate(row.indexdef);
|
|
561
|
+
if (!predicate) continue;
|
|
562
|
+
let predicates = cache.get(row.tablename);
|
|
563
|
+
if (!predicates) {
|
|
564
|
+
predicates = /* @__PURE__ */ new Map();
|
|
565
|
+
cache.set(row.tablename, predicates);
|
|
566
|
+
}
|
|
567
|
+
predicates.set(row.indexname, predicate);
|
|
568
|
+
}
|
|
569
|
+
this.indexPredicateCache = cache;
|
|
570
|
+
} catch (err) {
|
|
571
|
+
logger.debug("[SchemaComparer] Batched partial-index predicate introspection failed; falling back to per-table reads", { error: err instanceof Error ? err.message : String(err) });
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
507
575
|
* Plan the pre-R11 `text` -> `uuid` convergence (#2608).
|
|
508
576
|
*
|
|
509
577
|
* PostgreSQL only: SQLite stores UUIDs as text by design and DuckDB cannot
|
|
@@ -2036,6 +2104,7 @@ var SchemaComparer = class SchemaComparer {
|
|
|
2036
2104
|
*/
|
|
2037
2105
|
async getDbIndexPredicates(tableName) {
|
|
2038
2106
|
if (!this.supportsPartialIndexes()) return null;
|
|
2107
|
+
if (this.engine === "postgres" && this.indexPredicateCache) return new Map(this.indexPredicateCache.get(tableName) ?? []);
|
|
2039
2108
|
const predicates = /* @__PURE__ */ new Map();
|
|
2040
2109
|
try {
|
|
2041
2110
|
if (this.engine === "postgres") {
|