@typicalday/firegraph 0.8.0 → 0.10.0

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 (72) hide show
  1. package/dist/backend-73p5Blx7.d.cts +97 -0
  2. package/dist/backend-BrqFkbid.d.ts +97 -0
  3. package/dist/backend.cjs +222 -0
  4. package/dist/backend.cjs.map +1 -0
  5. package/dist/backend.d.cts +122 -0
  6. package/dist/backend.d.ts +122 -0
  7. package/dist/backend.js +136 -0
  8. package/dist/backend.js.map +1 -0
  9. package/dist/{chunk-6OQW5OKO.js → chunk-5753Y42M.js} +12 -4
  10. package/dist/chunk-5753Y42M.js.map +1 -0
  11. package/dist/{chunk-YUXOALMR.js → chunk-LZOIQHYN.js} +69 -92
  12. package/dist/chunk-LZOIQHYN.js.map +1 -0
  13. package/dist/chunk-R7CRGYY4.js +94 -0
  14. package/dist/chunk-R7CRGYY4.js.map +1 -0
  15. package/dist/{chunk-KFA7G37W.js → chunk-SU4FNLC3.js} +32 -30
  16. package/dist/chunk-SU4FNLC3.js.map +1 -0
  17. package/dist/chunk-TYYPRVIE.js +57 -0
  18. package/dist/chunk-TYYPRVIE.js.map +1 -0
  19. package/dist/{do-sqlite.cjs → cloudflare/index.cjs} +1538 -1420
  20. package/dist/cloudflare/index.cjs.map +1 -0
  21. package/dist/cloudflare/index.d.cts +454 -0
  22. package/dist/cloudflare/index.d.ts +454 -0
  23. package/dist/cloudflare/index.js +822 -0
  24. package/dist/cloudflare/index.js.map +1 -0
  25. package/dist/codegen/index.d.cts +1 -1
  26. package/dist/codegen/index.d.ts +1 -1
  27. package/dist/editor/client/assets/index-Bq2bfzeY.js +411 -0
  28. package/dist/editor/client/index.html +1 -1
  29. package/dist/editor/server/index.mjs +6481 -6327
  30. package/dist/index.cjs +165 -44
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +14 -138
  33. package/dist/index.d.ts +14 -138
  34. package/dist/index.js +31 -22
  35. package/dist/index.js.map +1 -1
  36. package/dist/query-client/index.cjs +30 -28
  37. package/dist/query-client/index.cjs.map +1 -1
  38. package/dist/query-client/index.d.cts +2 -2
  39. package/dist/query-client/index.d.ts +2 -2
  40. package/dist/query-client/index.js +1 -1
  41. package/dist/react.cjs +0 -1
  42. package/dist/react.cjs.map +1 -1
  43. package/dist/react.js +0 -1
  44. package/dist/react.js.map +1 -1
  45. package/dist/scope-path-B1G3YiA7.d.cts +139 -0
  46. package/dist/scope-path-B1G3YiA7.d.ts +139 -0
  47. package/dist/{serialization-C6JNNOCS.js → serialization-ZZ7RSDRX.js} +2 -2
  48. package/dist/svelte.cjs +0 -2
  49. package/dist/svelte.cjs.map +1 -1
  50. package/dist/svelte.js +0 -2
  51. package/dist/svelte.js.map +1 -1
  52. package/dist/{types-BVtx9zLv.d.cts → types-DOemdlVA.d.cts} +20 -2
  53. package/dist/{types-BVtx9zLv.d.ts → types-DOemdlVA.d.ts} +20 -2
  54. package/package.json +39 -40
  55. package/dist/chunk-6OQW5OKO.js.map +0 -1
  56. package/dist/chunk-KFA7G37W.js.map +0 -1
  57. package/dist/chunk-WOAJRVHD.js +0 -699
  58. package/dist/chunk-WOAJRVHD.js.map +0 -1
  59. package/dist/chunk-YUXOALMR.js.map +0 -1
  60. package/dist/d1.cjs +0 -2416
  61. package/dist/d1.cjs.map +0 -1
  62. package/dist/d1.d.cts +0 -54
  63. package/dist/d1.d.ts +0 -54
  64. package/dist/d1.js +0 -75
  65. package/dist/d1.js.map +0 -1
  66. package/dist/do-sqlite.cjs.map +0 -1
  67. package/dist/do-sqlite.d.cts +0 -41
  68. package/dist/do-sqlite.d.ts +0 -41
  69. package/dist/do-sqlite.js +0 -78
  70. package/dist/do-sqlite.js.map +0 -1
  71. package/dist/editor/client/assets/index-tyFcX6qG.js +0 -411
  72. /package/dist/{serialization-C6JNNOCS.js.map → serialization-ZZ7RSDRX.js.map} +0 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config.ts","../src/cross-graph.ts","../src/discover.ts","../src/internal/firestore-backend.ts","../src/bulk.ts","../src/internal/firestore-adapter.ts","../src/internal/pipeline-adapter.ts","../src/firestore.ts","../src/id.ts","../src/indexes.ts","../src/record.ts","../src/traverse.ts","../src/views.ts"],"sourcesContent":["/**\n * Firegraph Configuration — project-level config file support.\n *\n * Projects create a `firegraph.config.ts` (or `.js`/`.mjs`) in their root:\n *\n * @example\n * ```ts\n * import { defineConfig } from 'firegraph';\n *\n * export default defineConfig({\n * entities: './entities',\n * project: 'my-project',\n * collection: 'graph',\n * });\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// View Resolution Types\n// ---------------------------------------------------------------------------\n\n/** Display contexts where views can appear. */\nexport type ViewContext = 'listing' | 'detail' | 'inline';\n\n/** View resolution configuration for a single entity type. */\nexport interface ViewResolverConfig {\n /** Default view name (e.g. 'card'). Falls back to 'json' if unset. */\n default?: string;\n /** View to use in NodeBrowser listing rows. */\n listing?: string;\n /** View to use on the NodeDetail page. */\n detail?: string;\n /** View to use for inline/embedded previews (edge rows, traversal). */\n inline?: string;\n}\n\n/** Declarative view defaults, keyed by entity type. */\nexport interface ViewDefaultsConfig {\n /** Node view defaults keyed by aType (e.g. 'user', 'task'). */\n nodes?: Record<string, ViewResolverConfig>;\n /** Edge view defaults keyed by axbType (e.g. 'hasDeparture'). */\n edges?: Record<string, ViewResolverConfig>;\n}\n\n// ---------------------------------------------------------------------------\n// Config Shape\n// ---------------------------------------------------------------------------\n\n/** Project-level firegraph configuration. */\nexport interface FiregraphConfig {\n /** Path to entities directory (per-entity folder convention). */\n entities?: string;\n /** GCP project ID. */\n project?: string;\n /** Firestore collection path (default: 'graph'). */\n collection?: string;\n /** Firestore emulator address (e.g. '127.0.0.1:8080'). */\n emulator?: string;\n /**\n * Query execution backend.\n *\n * - `'pipeline'` (default) — Uses Firestore Pipeline API. Requires Enterprise\n * Firestore. Enables indexless queries on `data.*` fields.\n * - `'standard'` — Uses standard Firestore `.where().get()` queries. Not\n * recommended for production. See README for risk details.\n *\n * When the emulator is active, always falls back to `'standard'`.\n */\n queryMode?: import('./types.js').QueryMode;\n\n /**\n * AI chat configuration. Auto-detects `claude` CLI on PATH by default.\n * Set to `false` to disable chat even if claude is available.\n */\n chat?: false | {\n /** Claude model to use (default: 'sonnet'). */\n model?: string;\n /** Maximum concurrent claude processes (default: 2). */\n maxConcurrency?: number;\n };\n\n /** Editor-specific settings. */\n editor?: {\n /** Server port (default: 3883). */\n port?: number;\n /** Force read-only mode. */\n readonly?: boolean;\n };\n\n /** Declarative view defaults per entity type (overrides per-entity meta.json). */\n viewDefaults?: ViewDefaultsConfig;\n\n /**\n * Dynamic registry mode. When set, the editor loads type definitions\n * from Firestore meta-nodes in addition to filesystem entities.\n * Filesystem types take precedence on name conflicts.\n */\n registryMode?: import('./types.js').DynamicRegistryConfig;\n}\n\n// ---------------------------------------------------------------------------\n// defineConfig()\n// ---------------------------------------------------------------------------\n\n/**\n * Identity function providing type-checking and autocomplete for config files.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'firegraph';\n * export default defineConfig({ entities: './entities' });\n * ```\n */\nexport function defineConfig(config: FiregraphConfig): FiregraphConfig {\n return config;\n}\n\n// ---------------------------------------------------------------------------\n// View Resolution (pure — works client-side and server-side)\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve which view to show for a given entity.\n *\n * 1. If `context` is provided and a context-specific default exists, use it.\n * 2. Falls back to `resolverConfig.default`.\n * 3. Ultimate fallback: `'json'`.\n *\n * Only returns view names that exist in `availableViewNames`.\n */\nexport function resolveView(\n resolverConfig: ViewResolverConfig | undefined,\n availableViewNames: string[],\n context?: ViewContext,\n): string {\n if (!resolverConfig) return 'json';\n\n const available = new Set(availableViewNames);\n\n if (context) {\n const contextDefault = resolverConfig[context];\n if (contextDefault && available.has(contextDefault)) {\n return contextDefault;\n }\n }\n\n if (resolverConfig.default && available.has(resolverConfig.default)) {\n return resolverConfig.default;\n }\n\n return 'json';\n}\n","/**\n * Cross-graph edge resolution utilities.\n *\n * Provides path-scanning resolution for determining whether an edge's source\n * (aUid) is an ancestor node by checking if the UID appears in the Firestore\n * collection path.\n *\n * Firestore paths have a rigid alternating structure:\n * collection / docId / collection / docId / collection\n *\n * Given a path like `graph/A/workspace/B/context`, segments at even indices\n * are collection names and odd indices are document IDs. When we find a UID\n * at an odd index, the collection containing that document is the path up to\n * (and including) the preceding even-index segment.\n */\n\n/**\n * Parse a Firestore collection path and determine the collection path\n * where a given UID's document lives, if that UID is an ancestor in the path.\n *\n * @param collectionPath - The full Firestore collection path of the current client\n * @param uid - The UID to search for in the path\n * @returns The collection path containing the UID, or `null` if not found in the path\n *\n * @example\n * ```ts\n * // Path: graph/A/workspace/B/context\n * resolveAncestorCollection('graph/A/workspace/B/context', 'A')\n * // → 'graph'\n *\n * resolveAncestorCollection('graph/A/workspace/B/context', 'B')\n * // → 'graph/A/workspace'\n *\n * resolveAncestorCollection('graph/A/workspace/B/context', 'unknown')\n * // → null\n * ```\n */\nexport function resolveAncestorCollection(\n collectionPath: string,\n uid: string,\n): string | null {\n const segments = collectionPath.split('/');\n\n // Walk odd-indexed segments (document IDs in Firestore's alternating path structure)\n for (let i = 1; i < segments.length; i += 2) {\n if (segments[i] === uid) {\n // The collection containing this doc is everything up to index i-1\n return segments.slice(0, i).join('/');\n }\n }\n\n return null;\n}\n\n/**\n * Check whether a UID belongs to an ancestor node by scanning the collection path.\n *\n * @param collectionPath - The full Firestore collection path of the current client\n * @param uid - The UID to check\n * @returns `true` if the UID appears as a document segment in the path\n */\nexport function isAncestorUid(\n collectionPath: string,\n uid: string,\n): boolean {\n return resolveAncestorCollection(collectionPath, uid) !== null;\n}\n","/**\n * Entity Discovery — convention-based auto-discovery of entities from\n * a per-entity folder structure.\n *\n * Scans `entitiesDir/nodes/` and `entitiesDir/edges/` subdirectories.\n * Each subfolder is treated as an entity type.\n *\n * Schema files can be either `schema.json` (plain JSON Schema) or\n * `schema.ts` / `schema.js` (a module whose default export is a JSON Schema\n * object). When both exist, the TS/JS file takes precedence so that authors\n * can compose schemas programmatically while keeping a JSON fallback.\n *\n * @example\n * ```\n * entities/\n * nodes/\n * task/\n * schema.json | schema.ts (required — one or both)\n * views.ts (optional)\n * sample.json (optional)\n * meta.json (optional)\n * edges/\n * hasStep/\n * schema.json | schema.ts (required — one or both)\n * edge.json (required — topology)\n * views.ts (optional)\n * sample.json (optional)\n * meta.json (optional)\n * ```\n */\n\nimport { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join, resolve } from 'node:path';\nimport type { DiscoveredEntity, DiscoveryResult, EdgeTopology, MigrationStep, MigrationWriteBack } from './types.js';\nimport type { ViewResolverConfig } from './config.js';\nimport { FiregraphError } from './errors.js';\n\nexport class DiscoveryError extends FiregraphError {\n constructor(message: string) {\n super(message, 'DISCOVERY_ERROR');\n this.name = 'DiscoveryError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// JSON parsing helpers\n// ---------------------------------------------------------------------------\n\nfunction readJson(filePath: string): unknown {\n try {\n const raw = readFileSync(filePath, 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n const msg = err instanceof SyntaxError\n ? `Invalid JSON in ${filePath}: ${err.message}`\n : `Cannot read ${filePath}: ${(err as Error).message}`;\n throw new DiscoveryError(msg);\n }\n}\n\nfunction readJsonIfExists(filePath: string): unknown | undefined {\n if (!existsSync(filePath)) return undefined;\n return readJson(filePath);\n}\n\n// ---------------------------------------------------------------------------\n// Schema file loading (JSON or TS/JS via jiti)\n// ---------------------------------------------------------------------------\n\nconst SCHEMA_SCRIPT_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\n/**\n * Attempt to load a schema from a TS/JS module (default export) or fall back\n * to schema.json. Returns the parsed schema object or throws.\n */\nfunction loadSchema(dir: string, entityLabel: string): object {\n // Prefer TS/JS schema — allows programmatic composition & shared definitions\n for (const ext of SCHEMA_SCRIPT_EXTENSIONS) {\n const candidate = join(dir, `schema${ext}`);\n if (existsSync(candidate)) {\n return loadSchemaModule(candidate, entityLabel);\n }\n }\n\n // Fall back to schema.json\n const jsonPath = join(dir, 'schema.json');\n if (existsSync(jsonPath)) {\n return readJson(jsonPath) as object;\n }\n\n throw new DiscoveryError(\n `Missing schema for ${entityLabel} in ${dir}. ` +\n 'Provide a schema.ts (or .js/.mts/.mjs) or schema.json file.',\n );\n}\n\nlet _jiti: ((id: string) => unknown) | undefined;\n\nfunction getJiti(): (id: string) => unknown {\n if (!_jiti) {\n const base = typeof __filename !== 'undefined' ? __filename : import.meta.url;\n const esmRequire = createRequire(base);\n const { createJiti } = esmRequire('jiti') as typeof import('jiti');\n _jiti = createJiti(base, { interopDefault: true });\n }\n return _jiti;\n}\n\nfunction loadSchemaModule(filePath: string, entityLabel: string): object {\n try {\n const jiti = getJiti();\n const mod = jiti(filePath) as { default?: unknown } | unknown;\n const schema = (mod && typeof mod === 'object' && 'default' in mod)\n ? (mod as { default: unknown }).default\n : mod;\n\n if (!schema || typeof schema !== 'object') {\n throw new DiscoveryError(\n `Schema file ${filePath} for ${entityLabel} must default-export a JSON Schema object.`,\n );\n }\n return schema as object;\n } catch (err: unknown) {\n if (err instanceof DiscoveryError) throw err;\n throw new DiscoveryError(\n `Failed to load schema module ${filePath} for ${entityLabel}: ${(err as Error).message}`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// View file detection\n// ---------------------------------------------------------------------------\n\nconst VIEW_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\nfunction findViewsFile(dir: string): string | undefined {\n for (const ext of VIEW_EXTENSIONS) {\n const candidate = join(dir, `views${ext}`);\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Migration file detection & loading\n// ---------------------------------------------------------------------------\n\nconst MIGRATION_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\nfunction findMigrationsFile(dir: string): string | undefined {\n for (const ext of MIGRATION_EXTENSIONS) {\n const candidate = join(dir, `migrations${ext}`);\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\nfunction loadMigrations(filePath: string, entityLabel: string): MigrationStep[] {\n try {\n const jiti = getJiti();\n const mod = jiti(filePath) as { default?: unknown } | unknown;\n const migrations = (mod && typeof mod === 'object' && 'default' in mod)\n ? (mod as { default: unknown }).default\n : mod;\n\n if (!Array.isArray(migrations)) {\n throw new DiscoveryError(\n `Migrations file ${filePath} for ${entityLabel} must default-export an array of MigrationStep.`,\n );\n }\n return migrations as MigrationStep[];\n } catch (err: unknown) {\n if (err instanceof DiscoveryError) throw err;\n throw new DiscoveryError(\n `Failed to load migrations ${filePath} for ${entityLabel}: ${(err as Error).message}`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Entity loaders\n// ---------------------------------------------------------------------------\n\nfunction loadNodeEntity(dir: string, name: string): DiscoveredEntity {\n const schema = loadSchema(dir, `node type \"${name}\"`);\n const meta = readJsonIfExists(join(dir, 'meta.json')) as\n | { description?: string; titleField?: string; subtitleField?: string; viewDefaults?: ViewResolverConfig; allowedIn?: string[]; migrationWriteBack?: MigrationWriteBack }\n | undefined;\n const sampleData = readJsonIfExists(join(dir, 'sample.json')) as\n | Record<string, unknown>\n | undefined;\n const viewsPath = findViewsFile(dir);\n const migrationsPath = findMigrationsFile(dir);\n const migrations = migrationsPath\n ? loadMigrations(migrationsPath, `node type \"${name}\"`)\n : undefined;\n\n return {\n kind: 'node',\n name,\n schema,\n description: meta?.description,\n titleField: meta?.titleField,\n subtitleField: meta?.subtitleField,\n viewDefaults: meta?.viewDefaults,\n viewsPath,\n sampleData,\n allowedIn: meta?.allowedIn,\n migrations,\n migrationWriteBack: meta?.migrationWriteBack,\n };\n}\n\nfunction loadEdgeEntity(dir: string, name: string): DiscoveredEntity {\n const schema = loadSchema(dir, `edge type \"${name}\"`);\n\n const edgePath = join(dir, 'edge.json');\n if (!existsSync(edgePath)) {\n throw new DiscoveryError(\n `Missing edge.json for edge type \"${name}\" in ${dir}. ` +\n 'Edge entities must declare topology (from/to node types).',\n );\n }\n const topology = readJson(edgePath) as EdgeTopology;\n\n // Validate topology shape\n if (!topology.from) {\n throw new DiscoveryError(\n `edge.json for \"${name}\" is missing required \"from\" field`,\n );\n }\n if (!topology.to) {\n throw new DiscoveryError(\n `edge.json for \"${name}\" is missing required \"to\" field`,\n );\n }\n\n const meta = readJsonIfExists(join(dir, 'meta.json')) as\n | { description?: string; titleField?: string; subtitleField?: string; viewDefaults?: ViewResolverConfig; allowedIn?: string[]; targetGraph?: string; migrationWriteBack?: MigrationWriteBack }\n | undefined;\n const sampleData = readJsonIfExists(join(dir, 'sample.json')) as\n | Record<string, unknown>\n | undefined;\n const viewsPath = findViewsFile(dir);\n const migrationsPath = findMigrationsFile(dir);\n const migrations = migrationsPath\n ? loadMigrations(migrationsPath, `edge type \"${name}\"`)\n : undefined;\n\n return {\n kind: 'edge',\n name,\n schema,\n topology,\n description: meta?.description,\n titleField: meta?.titleField,\n subtitleField: meta?.subtitleField,\n viewDefaults: meta?.viewDefaults,\n viewsPath,\n sampleData,\n allowedIn: meta?.allowedIn,\n targetGraph: topology.targetGraph ?? (meta as { targetGraph?: string } | undefined)?.targetGraph,\n migrations,\n migrationWriteBack: meta?.migrationWriteBack,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Directory scanner\n// ---------------------------------------------------------------------------\n\nfunction getSubdirectories(dir: string): string[] {\n if (!existsSync(dir)) return [];\n return readdirSync(dir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface DiscoveryWarning {\n code: 'DANGLING_TOPOLOGY_REF';\n message: string;\n}\n\nexport interface DiscoverResult {\n result: DiscoveryResult;\n warnings: DiscoveryWarning[];\n}\n\n/**\n * Scan an entities directory and return all discovered nodes and edges.\n *\n * @param entitiesDir - Path to the entities directory (absolute or relative to cwd)\n * @returns Discovery result with nodes and edges maps, plus any warnings\n */\nexport function discoverEntities(entitiesDir: string): DiscoverResult {\n const absDir = resolve(entitiesDir);\n\n if (!existsSync(absDir) || !statSync(absDir).isDirectory()) {\n throw new DiscoveryError(`Entities directory not found: ${entitiesDir}`);\n }\n\n const nodes = new Map<string, DiscoveredEntity>();\n const edges = new Map<string, DiscoveredEntity>();\n const warnings: DiscoveryWarning[] = [];\n\n // Discover nodes\n const nodesDir = join(absDir, 'nodes');\n for (const name of getSubdirectories(nodesDir)) {\n nodes.set(name, loadNodeEntity(join(nodesDir, name), name));\n }\n\n // Discover edges\n const edgesDir = join(absDir, 'edges');\n for (const name of getSubdirectories(edgesDir)) {\n edges.set(name, loadEdgeEntity(join(edgesDir, name), name));\n }\n\n // Validate topology references\n const nodeNames = new Set(nodes.keys());\n for (const [axbType, entity] of edges) {\n const topology = entity.topology!;\n const fromTypes = Array.isArray(topology.from) ? topology.from : [topology.from];\n const toTypes = Array.isArray(topology.to) ? topology.to : [topology.to];\n\n for (const ref of [...fromTypes, ...toTypes]) {\n if (!nodeNames.has(ref)) {\n warnings.push({\n code: 'DANGLING_TOPOLOGY_REF',\n message: `Edge \"${axbType}\" references node type \"${ref}\" which was not found in the nodes directory`,\n });\n }\n }\n }\n\n return {\n result: { nodes, edges },\n warnings,\n };\n}\n","/**\n * Firestore implementation of `StorageBackend`.\n *\n * Wraps the existing `FirestoreAdapter`, `TransactionAdapter`, and\n * `BatchAdapter` so the Firestore code path keeps the exact behavior it\n * had before the backend abstraction landed.\n */\n\nimport type { Firestore, Query, Transaction } from '@google-cloud/firestore';\nimport { FieldValue } from '@google-cloud/firestore';\n\nimport {\n bulkRemoveEdges as bulkRemoveEdgesImpl,\n removeNodeCascade as removeNodeCascadeImpl,\n} from '../bulk.js';\nimport { FiregraphError } from '../errors.js';\nimport { buildEdgeQueryPlan } from '../query.js';\nimport { deserializeFirestoreTypes } from '../serialization.js';\nimport type {\n BulkOptions,\n BulkResult,\n CascadeResult,\n FindEdgesParams,\n GraphReader,\n QueryFilter,\n QueryMode,\n QueryOptions,\n StoredGraphRecord,\n} from '../types.js';\nimport type {\n BatchBackend,\n StorageBackend,\n TransactionBackend,\n UpdatePayload,\n WritableRecord,\n} from './backend.js';\nimport type { BatchAdapter, FirestoreAdapter, TransactionAdapter } from './firestore-adapter.js';\nimport {\n createBatchAdapter,\n createFirestoreAdapter,\n createTransactionAdapter,\n} from './firestore-adapter.js';\nimport type { PipelineQueryAdapter } from './pipeline-adapter.js';\nimport { createPipelineQueryAdapter } from './pipeline-adapter.js';\n\nexport interface FirestoreBackendOptions {\n queryMode?: QueryMode;\n scopePath?: string;\n}\n\n/**\n * Build the patch payload Firestore expects from an `UpdatePayload`.\n *\n * - `replaceData` sets the whole `data` field at once. Tagged Firestore\n * types from the migration sandbox are reconstructed here.\n * - `dataFields` uses Firestore's `data.<key>` dotted-path syntax.\n * - `updatedAt` is always stamped with `FieldValue.serverTimestamp()`.\n * - `v` is stamped at the root when provided.\n */\nfunction buildFirestoreUpdate(update: UpdatePayload, db: Firestore): Record<string, unknown> {\n const out: Record<string, unknown> = {\n updatedAt: FieldValue.serverTimestamp(),\n };\n if (update.replaceData) {\n out.data = deserializeFirestoreTypes(update.replaceData, db);\n }\n if (update.dataFields) {\n for (const [k, v] of Object.entries(update.dataFields)) {\n out[`data.${k}`] = v;\n }\n }\n if (update.v !== undefined) {\n out.v = update.v;\n }\n return out;\n}\n\n/**\n * Stamp `createdAt`/`updatedAt` server-timestamp sentinels on a\n * timestampless record. Used for `setDoc`.\n */\nfunction stampWritableRecord(record: WritableRecord): Record<string, unknown> {\n const now = FieldValue.serverTimestamp();\n const out: Record<string, unknown> = {\n aType: record.aType,\n aUid: record.aUid,\n axbType: record.axbType,\n bType: record.bType,\n bUid: record.bUid,\n data: record.data,\n createdAt: now,\n updatedAt: now,\n };\n if (record.v !== undefined) out.v = record.v;\n return out;\n}\n\nclass FirestoreTransactionBackend implements TransactionBackend {\n constructor(\n private readonly adapter: TransactionAdapter,\n private readonly db: Firestore,\n ) {}\n\n getDoc(docId: string): Promise<StoredGraphRecord | null> {\n return this.adapter.getDoc(docId);\n }\n\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n return this.adapter.query(filters, options);\n }\n\n async setDoc(docId: string, record: WritableRecord): Promise<void> {\n this.adapter.setDoc(docId, stampWritableRecord(record));\n }\n\n async updateDoc(docId: string, update: UpdatePayload): Promise<void> {\n this.adapter.updateDoc(docId, buildFirestoreUpdate(update, this.db));\n }\n\n async deleteDoc(docId: string): Promise<void> {\n this.adapter.deleteDoc(docId);\n }\n}\n\nclass FirestoreBatchBackend implements BatchBackend {\n constructor(\n private readonly adapter: BatchAdapter,\n private readonly db: Firestore,\n ) {}\n\n setDoc(docId: string, record: WritableRecord): void {\n this.adapter.setDoc(docId, stampWritableRecord(record));\n }\n\n updateDoc(docId: string, update: UpdatePayload): void {\n this.adapter.updateDoc(docId, buildFirestoreUpdate(update, this.db));\n }\n\n deleteDoc(docId: string): void {\n this.adapter.deleteDoc(docId);\n }\n\n commit(): Promise<void> {\n return this.adapter.commit();\n }\n}\n\nclass FirestoreBackendImpl implements StorageBackend {\n readonly collectionPath: string;\n readonly scopePath: string;\n private readonly adapter: FirestoreAdapter;\n private readonly pipelineAdapter?: PipelineQueryAdapter;\n\n constructor(\n private readonly db: Firestore,\n collectionPath: string,\n private readonly queryMode: QueryMode,\n scopePath: string,\n ) {\n this.collectionPath = collectionPath;\n this.scopePath = scopePath;\n this.adapter = createFirestoreAdapter(db, collectionPath);\n if (queryMode === 'pipeline') {\n this.pipelineAdapter = createPipelineQueryAdapter(db, collectionPath);\n }\n }\n\n // --- Reads ---\n\n getDoc(docId: string): Promise<StoredGraphRecord | null> {\n return this.adapter.getDoc(docId);\n }\n\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n if (this.pipelineAdapter) {\n return this.pipelineAdapter.query(filters, options);\n }\n return this.adapter.query(filters, options);\n }\n\n // --- Writes ---\n\n setDoc(docId: string, record: WritableRecord): Promise<void> {\n return this.adapter.setDoc(docId, stampWritableRecord(record));\n }\n\n updateDoc(docId: string, update: UpdatePayload): Promise<void> {\n return this.adapter.updateDoc(docId, buildFirestoreUpdate(update, this.db));\n }\n\n deleteDoc(docId: string): Promise<void> {\n return this.adapter.deleteDoc(docId);\n }\n\n // --- Transactions / Batches ---\n\n runTransaction<T>(fn: (tx: TransactionBackend) => Promise<T>): Promise<T> {\n return this.db.runTransaction(async (firestoreTx: Transaction) => {\n const txAdapter = createTransactionAdapter(this.db, this.collectionPath, firestoreTx);\n return fn(new FirestoreTransactionBackend(txAdapter, this.db));\n });\n }\n\n createBatch(): BatchBackend {\n const batchAdapter = createBatchAdapter(this.db, this.collectionPath);\n return new FirestoreBatchBackend(batchAdapter, this.db);\n }\n\n // --- Subgraphs ---\n\n subgraph(parentNodeUid: string, name: string): StorageBackend {\n const subPath = `${this.collectionPath}/${parentNodeUid}/${name}`;\n const newScope = this.scopePath ? `${this.scopePath}/${name}` : name;\n return new FirestoreBackendImpl(this.db, subPath, this.queryMode, newScope);\n }\n\n // --- Cascade & bulk ---\n\n removeNodeCascade(\n uid: string,\n reader: GraphReader,\n options?: BulkOptions,\n ): Promise<CascadeResult> {\n return removeNodeCascadeImpl(this.db, this.collectionPath, reader, uid, options);\n }\n\n bulkRemoveEdges(\n params: FindEdgesParams,\n reader: GraphReader,\n options?: BulkOptions,\n ): Promise<BulkResult> {\n return bulkRemoveEdgesImpl(this.db, this.collectionPath, reader, params, options);\n }\n\n // --- Cross-collection ---\n\n async findEdgesGlobal(\n params: FindEdgesParams,\n collectionName?: string,\n ): Promise<StoredGraphRecord[]> {\n const name = collectionName ?? this.collectionPath.split('/').pop()!;\n const plan = buildEdgeQueryPlan(params);\n\n if (plan.strategy === 'get') {\n throw new FiregraphError(\n 'findEdgesGlobal() requires a query, not a direct document lookup. ' +\n 'Omit one of aUid/axbType/bUid to force a query strategy.',\n 'INVALID_QUERY',\n );\n }\n\n const collectionGroupRef = this.db.collectionGroup(name);\n let q: Query = collectionGroupRef;\n for (const f of plan.filters) {\n q = q.where(f.field, f.op, f.value);\n }\n if (plan.options?.orderBy) {\n q = q.orderBy(plan.options.orderBy.field, plan.options.orderBy.direction ?? 'asc');\n }\n if (plan.options?.limit !== undefined) {\n q = q.limit(plan.options.limit);\n }\n const snap = await q.get();\n return snap.docs.map((doc) => doc.data() as StoredGraphRecord);\n }\n}\n\n/**\n * Create a Firestore-backed `StorageBackend`.\n *\n * The query-mode auto-fallback for the emulator (`FIRESTORE_EMULATOR_HOST`)\n * is performed at the call site (`createGraphClient`) so that the backend\n * itself doesn't reach into `process.env`.\n */\nexport function createFirestoreBackend(\n db: Firestore,\n collectionPath: string,\n options: FirestoreBackendOptions = {},\n): StorageBackend {\n const queryMode = options.queryMode ?? 'pipeline';\n const scopePath = options.scopePath ?? '';\n return new FirestoreBackendImpl(db, collectionPath, queryMode, scopePath);\n}\n","import type { Firestore } from '@google-cloud/firestore';\nimport { computeEdgeDocId, computeNodeDocId } from './docid.js';\nimport { NODE_RELATION } from './internal/constants.js';\nimport type {\n StoredGraphRecord,\n FindEdgesParams,\n BulkOptions,\n BulkResult,\n BulkBatchError,\n CascadeResult,\n GraphReader,\n} from './types.js';\n\nconst MAX_BATCH_SIZE = 500;\nconst DEFAULT_MAX_RETRIES = 3;\nconst BASE_DELAY_MS = 200;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Splits an array into chunks of at most `size` elements.\n */\nfunction chunk<T>(arr: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < arr.length; i += size) {\n chunks.push(arr.slice(i, i + size));\n }\n return chunks;\n}\n\n/**\n * Deletes a list of document IDs in chunked Firestore batches with retries.\n */\nexport async function bulkDeleteDocIds(\n db: Firestore,\n collectionPath: string,\n docIds: string[],\n options?: BulkOptions,\n): Promise<BulkResult> {\n if (docIds.length === 0) {\n return { deleted: 0, batches: 0, errors: [] };\n }\n\n const batchSize = Math.min(options?.batchSize ?? MAX_BATCH_SIZE, MAX_BATCH_SIZE);\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const onProgress = options?.onProgress;\n\n const chunks = chunk(docIds, batchSize);\n const errors: BulkBatchError[] = [];\n let deleted = 0;\n let completedBatches = 0;\n\n for (let i = 0; i < chunks.length; i++) {\n const ids = chunks[i];\n let committed = false;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const batch = db.batch();\n const collectionRef = db.collection(collectionPath);\n for (const id of ids) {\n batch.delete(collectionRef.doc(id));\n }\n await batch.commit();\n committed = true;\n deleted += ids.length;\n break;\n } catch (err) {\n if (attempt < maxRetries) {\n const delay = BASE_DELAY_MS * Math.pow(2, attempt);\n await sleep(delay);\n } else {\n errors.push({\n batchIndex: i,\n error: err instanceof Error ? err : new Error(String(err)),\n operationCount: ids.length,\n });\n }\n }\n }\n\n if (committed) {\n completedBatches++;\n }\n\n if (onProgress) {\n onProgress({\n completedBatches,\n totalBatches: chunks.length,\n deletedSoFar: deleted,\n });\n }\n }\n\n return { deleted, batches: completedBatches, errors };\n}\n\n/**\n * Finds all edges matching `params`, then deletes them in chunked batches.\n */\nexport async function bulkRemoveEdges(\n db: Firestore,\n collectionPath: string,\n reader: GraphReader,\n params: FindEdgesParams,\n options?: BulkOptions,\n): Promise<BulkResult> {\n // Override default query limit for bulk deletion — we need all matching edges.\n // limit: 0 bypasses DEFAULT_QUERY_LIMIT; an explicit user limit is preserved.\n // allowCollectionScan: true — bulk deletion inherently implies scanning.\n const effectiveParams = params.limit !== undefined\n ? { ...params, allowCollectionScan: params.allowCollectionScan ?? true }\n : { ...params, limit: 0, allowCollectionScan: params.allowCollectionScan ?? true };\n const edges = await reader.findEdges(effectiveParams);\n const docIds = edges.map((e) => computeEdgeDocId(e.aUid, e.axbType, e.bUid));\n return bulkDeleteDocIds(db, collectionPath, docIds, options);\n}\n\n/** Result from recursive subcollection deletion. */\ninterface SubcollectionDeleteResult {\n deleted: number;\n errors: BulkBatchError[];\n}\n\n/**\n * Recursively delete all documents in all subcollections under a given document.\n * Uses `listCollections()` (Admin SDK) to discover subcollections, then for each\n * subcollection: recurse into each document's subcollections first (depth-first),\n * then bulk delete all documents in the subcollection.\n *\n * The `onProgress` callback is intentionally NOT forwarded to subcollection\n * deletes to avoid confusing callers with interleaved progress from different\n * collection depths.\n */\nasync function deleteSubcollectionsRecursive(\n db: Firestore,\n collectionPath: string,\n docId: string,\n options?: BulkOptions,\n): Promise<SubcollectionDeleteResult> {\n const docRef = db.collection(collectionPath).doc(docId);\n const subcollections = await docRef.listCollections();\n\n if (subcollections.length === 0) return { deleted: 0, errors: [] };\n\n let totalDeleted = 0;\n const allErrors: BulkBatchError[] = [];\n\n // Strip onProgress for subcollection deletes — callers should only see\n // top-level progress, not interleaved reports from nested depths.\n const subOptions: BulkOptions | undefined = options\n ? { batchSize: options.batchSize, maxRetries: options.maxRetries }\n : undefined;\n\n for (const subCollRef of subcollections) {\n const subCollPath = subCollRef.path;\n // List all documents in this subcollection\n const snapshot = await subCollRef.select().get();\n const subDocIds = snapshot.docs.map((d) => d.id);\n\n // Depth-first: recurse into each document's subcollections\n for (const subDocId of subDocIds) {\n const subResult = await deleteSubcollectionsRecursive(db, subCollPath, subDocId, subOptions);\n totalDeleted += subResult.deleted;\n allErrors.push(...subResult.errors);\n }\n\n // Now delete all documents in this subcollection\n if (subDocIds.length > 0) {\n const result = await bulkDeleteDocIds(db, subCollPath, subDocIds, subOptions);\n totalDeleted += result.deleted;\n allErrors.push(...result.errors);\n }\n }\n\n return { deleted: totalDeleted, errors: allErrors };\n}\n\n/**\n * Deletes a node and all of its outgoing and incoming edges.\n *\n * Edges are deleted first in chunked batches, then the node document\n * is deleted in the final batch. This is NOT atomic across batches —\n * if a batch fails after retries, remaining batches still execute.\n *\n * By default, subcollections (subgraphs) under the node's document are\n * recursively deleted. Set `options.deleteSubcollections` to `false` to skip.\n */\nexport async function removeNodeCascade(\n db: Firestore,\n collectionPath: string,\n reader: GraphReader,\n uid: string,\n options?: BulkOptions,\n): Promise<CascadeResult> {\n // Find all edges touching this node (outgoing + incoming).\n // Filter out the node's own self-loop record (axbType === 'is').\n // These queries intentionally scan broadly — allowCollectionScan bypasses safety checks.\n // limit: 0 bypasses the DEFAULT_QUERY_LIMIT to ensure we find all edges.\n const [outgoingRaw, incomingRaw] = await Promise.all([\n reader.findEdges({ aUid: uid, allowCollectionScan: true, limit: 0 }),\n reader.findEdges({ bUid: uid, allowCollectionScan: true, limit: 0 }),\n ]);\n const outgoing = outgoingRaw.filter((e) => e.axbType !== NODE_RELATION);\n const incoming = incomingRaw.filter((e) => e.axbType !== NODE_RELATION);\n\n // Deduplicate: a self-referencing edge could appear in both lists.\n const edgeDocIdSet = new Set<string>();\n const allEdges: StoredGraphRecord[] = [];\n for (const edge of [...outgoing, ...incoming]) {\n const docId = computeEdgeDocId(edge.aUid, edge.axbType, edge.bUid);\n if (!edgeDocIdSet.has(docId)) {\n edgeDocIdSet.add(docId);\n allEdges.push(edge);\n }\n }\n\n // Delete subcollections (subgraphs) under this node's document (depth-first).\n const shouldDeleteSubcollections = options?.deleteSubcollections !== false;\n const nodeDocId = computeNodeDocId(uid);\n let subcollectionResult: SubcollectionDeleteResult = { deleted: 0, errors: [] };\n\n if (shouldDeleteSubcollections) {\n subcollectionResult = await deleteSubcollectionsRecursive(\n db, collectionPath, nodeDocId, options,\n );\n }\n\n // Build doc IDs: edges first, then the node last.\n const edgeDocIds = allEdges.map((e) => computeEdgeDocId(e.aUid, e.axbType, e.bUid));\n const allDocIds = [...edgeDocIds, nodeDocId];\n\n // Wrap the progress callback to track overall progress.\n const batchSize = Math.min(options?.batchSize ?? MAX_BATCH_SIZE, MAX_BATCH_SIZE);\n const result = await bulkDeleteDocIds(db, collectionPath, allDocIds, {\n ...options,\n batchSize,\n });\n\n // Determine if the node doc was in a failed batch.\n // The node is always in the last doc ID. If the last batch errored, node wasn't deleted.\n const totalChunks = Math.ceil(allDocIds.length / batchSize);\n const nodeChunkIndex = totalChunks - 1;\n const nodeDeleted = !result.errors.some((e) => e.batchIndex === nodeChunkIndex);\n\n // edgesDeleted counts only top-level edges (not subcollection docs).\n // deleted includes everything: top-level edges + node + subcollection docs.\n const topLevelEdgesDeleted = nodeDeleted ? result.deleted - 1 : result.deleted;\n\n return {\n deleted: result.deleted + subcollectionResult.deleted,\n batches: result.batches,\n errors: [...result.errors, ...subcollectionResult.errors],\n edgesDeleted: topLevelEdgesDeleted,\n nodeDeleted,\n };\n}\n","import type { Firestore, Query, Transaction } from '@google-cloud/firestore';\nimport type { StoredGraphRecord, QueryFilter, QueryOptions } from '../types.js';\n\nexport interface FirestoreAdapter {\n collectionPath: string;\n getDoc(docId: string): Promise<StoredGraphRecord | null>;\n setDoc(docId: string, data: Record<string, unknown>): Promise<void>;\n updateDoc(docId: string, data: Record<string, unknown>): Promise<void>;\n deleteDoc(docId: string): Promise<void>;\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]>;\n}\n\nexport function createFirestoreAdapter(\n db: Firestore,\n collectionPath: string,\n): FirestoreAdapter {\n const collectionRef = db.collection(collectionPath);\n\n return {\n collectionPath,\n\n async getDoc(docId: string): Promise<StoredGraphRecord | null> {\n const snap = await collectionRef.doc(docId).get();\n if (!snap.exists) return null;\n return snap.data() as StoredGraphRecord;\n },\n\n async setDoc(docId: string, data: Record<string, unknown>): Promise<void> {\n await collectionRef.doc(docId).set(data);\n },\n\n async updateDoc(docId: string, data: Record<string, unknown>): Promise<void> {\n await collectionRef.doc(docId).update(data);\n },\n\n async deleteDoc(docId: string): Promise<void> {\n await collectionRef.doc(docId).delete();\n },\n\n async query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n let q: Query = collectionRef;\n for (const f of filters) {\n q = q.where(f.field, f.op, f.value);\n }\n if (options?.orderBy) {\n q = q.orderBy(options.orderBy.field, options.orderBy.direction ?? 'asc');\n }\n if (options?.limit !== undefined) {\n q = q.limit(options.limit);\n }\n const snap = await q.get();\n return snap.docs.map((doc) => doc.data() as StoredGraphRecord);\n },\n };\n}\n\nexport interface TransactionAdapter {\n getDoc(docId: string): Promise<StoredGraphRecord | null>;\n setDoc(docId: string, data: Record<string, unknown>): void;\n updateDoc(docId: string, data: Record<string, unknown>): void;\n deleteDoc(docId: string): void;\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]>;\n}\n\nexport function createTransactionAdapter(\n db: Firestore,\n collectionPath: string,\n tx: Transaction,\n): TransactionAdapter {\n const collectionRef = db.collection(collectionPath);\n\n return {\n async getDoc(docId: string): Promise<StoredGraphRecord | null> {\n const snap = await tx.get(collectionRef.doc(docId));\n if (!snap.exists) return null;\n return snap.data() as StoredGraphRecord;\n },\n\n setDoc(docId: string, data: Record<string, unknown>): void {\n tx.set(collectionRef.doc(docId), data);\n },\n\n updateDoc(docId: string, data: Record<string, unknown>): void {\n tx.update(collectionRef.doc(docId), data);\n },\n\n deleteDoc(docId: string): void {\n tx.delete(collectionRef.doc(docId));\n },\n\n async query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n let q: Query = collectionRef;\n for (const f of filters) {\n q = q.where(f.field, f.op, f.value);\n }\n if (options?.orderBy) {\n q = q.orderBy(options.orderBy.field, options.orderBy.direction ?? 'asc');\n }\n if (options?.limit !== undefined) {\n q = q.limit(options.limit);\n }\n const snap = await tx.get(q);\n return snap.docs.map((doc) => doc.data() as StoredGraphRecord);\n },\n };\n}\n\nexport interface BatchAdapter {\n setDoc(docId: string, data: Record<string, unknown>): void;\n updateDoc(docId: string, data: Record<string, unknown>): void;\n deleteDoc(docId: string): void;\n commit(): Promise<void>;\n}\n\nexport function createBatchAdapter(\n db: Firestore,\n collectionPath: string,\n): BatchAdapter {\n const collectionRef = db.collection(collectionPath);\n const batch = db.batch();\n\n return {\n setDoc(docId: string, data: Record<string, unknown>): void {\n batch.set(collectionRef.doc(docId), data);\n },\n\n updateDoc(docId: string, data: Record<string, unknown>): void {\n batch.update(collectionRef.doc(docId), data);\n },\n\n deleteDoc(docId: string): void {\n batch.delete(collectionRef.doc(docId));\n },\n\n async commit(): Promise<void> {\n await batch.commit();\n },\n };\n}\n","/**\n * Pipeline query adapter — translates QueryFilter[] to Firestore Pipeline\n * expressions and executes them via db.pipeline().\n *\n * Only handles query() — doc-level operations (get/set/update/delete) stay\n * on the standard FirestoreAdapter.\n */\nimport type { Firestore } from '@google-cloud/firestore';\nimport type { StoredGraphRecord, QueryFilter, QueryOptions } from '../types.js';\n\n/**\n * Minimal interface for the Pipeline query adapter.\n * Only implements the query path — doc operations are handled by FirestoreAdapter.\n */\nexport interface PipelineQueryAdapter {\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]>;\n}\n\n/**\n * Lazily loaded Pipelines module. We use dynamic import so that standard-mode\n * users (and the emulator) don't pull in pipeline-related code at module load.\n */\nlet _Pipelines: typeof import('@google-cloud/firestore').Pipelines | null = null;\n\nasync function getPipelines(): Promise<typeof import('@google-cloud/firestore').Pipelines> {\n if (!_Pipelines) {\n const mod = await import('@google-cloud/firestore');\n _Pipelines = mod.Pipelines;\n }\n return _Pipelines;\n}\n\ntype PipelinesType = typeof import('@google-cloud/firestore').Pipelines;\ntype BooleanExpr = import('@google-cloud/firestore').Pipelines.BooleanExpression;\n\n/**\n * Maps a QueryFilter to a Pipeline BooleanExpression.\n *\n * Uses the string-based overloads (e.g. `equal(fieldName, value)`) which\n * accept `unknown` values, avoiding type issues with `constant()` overloads.\n */\nfunction buildFilterExpression(\n P: PipelinesType,\n filter: QueryFilter,\n): BooleanExpr {\n const { field: fieldName, op, value } = filter;\n\n switch (op) {\n case '==':\n return P.equal(fieldName, value);\n case '!=':\n return P.notEqual(fieldName, value);\n case '<':\n return P.lessThan(fieldName, value);\n case '<=':\n return P.lessThanOrEqual(fieldName, value);\n case '>':\n return P.greaterThan(fieldName, value);\n case '>=':\n return P.greaterThanOrEqual(fieldName, value);\n case 'in':\n return P.equalAny(fieldName, value as Array<unknown>);\n case 'not-in':\n return P.notEqualAny(fieldName, value as Array<unknown>);\n case 'array-contains':\n return P.arrayContains(fieldName, value);\n case 'array-contains-any':\n return P.arrayContainsAny(fieldName, value as Array<unknown>);\n default:\n throw new Error(`Unsupported filter op for pipeline mode: ${op}`);\n }\n}\n\nexport function createPipelineQueryAdapter(\n db: Firestore,\n collectionPath: string,\n): PipelineQueryAdapter {\n return {\n async query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n const P = await getPipelines();\n\n // Build pipeline\n let pipeline = db.pipeline().collection(collectionPath);\n\n // Apply filters\n if (filters.length === 1) {\n pipeline = pipeline.where(buildFilterExpression(P, filters[0]));\n } else if (filters.length > 1) {\n const [first, second, ...rest] = filters.map(f => buildFilterExpression(P, f));\n pipeline = pipeline.where(P.and(first, second, ...rest));\n }\n\n // Apply sort\n if (options?.orderBy) {\n const f = P.field(options.orderBy.field);\n const ordering = options.orderBy.direction === 'desc'\n ? f.descending()\n : f.ascending();\n pipeline = pipeline.sort(ordering);\n }\n\n // Apply limit\n if (options?.limit !== undefined) {\n pipeline = pipeline.limit(options.limit);\n }\n\n const snap = await pipeline.execute();\n return snap.results.map(r => r.data() as StoredGraphRecord);\n },\n };\n}\n","/**\n * Firestore-specific client factory.\n *\n * Kept in its own module so that bundlers don't pull\n * `@google-cloud/firestore` into SQLite-only entry points\n * (`firegraph/d1`, `firegraph/do-sqlite`).\n */\n\nimport type { Firestore } from '@google-cloud/firestore';\n\nimport { GraphClientImpl } from './client.js';\nimport type { StorageBackend } from './internal/backend.js';\nimport { createFirestoreBackend } from './internal/firestore-backend.js';\nimport type {\n DynamicGraphClient,\n DynamicRegistryConfig,\n GraphClient,\n GraphClientOptions,\n QueryMode,\n} from './types.js';\n\nlet _standardModeWarned = false;\n\nexport function createGraphClient(\n db: Firestore,\n collectionPath: string,\n options: GraphClientOptions & { registryMode: DynamicRegistryConfig },\n): DynamicGraphClient;\nexport function createGraphClient(\n db: Firestore,\n collectionPath: string,\n options?: GraphClientOptions,\n): GraphClient;\nexport function createGraphClient(\n db: Firestore,\n collectionPath: string,\n options?: GraphClientOptions,\n): GraphClient | DynamicGraphClient {\n const requestedMode = options?.queryMode ?? 'pipeline';\n const isEmulator = !!process.env.FIRESTORE_EMULATOR_HOST;\n const effectiveMode: QueryMode = isEmulator ? 'standard' : requestedMode;\n\n if (\n effectiveMode === 'standard' &&\n !isEmulator &&\n requestedMode === 'standard' &&\n !_standardModeWarned\n ) {\n _standardModeWarned = true;\n console.warn(\n '[firegraph] Standard query mode enabled. This is NOT recommended for production:\\n' +\n ' - Enterprise Firestore: data.* filters cause full collection scans (high billing)\\n' +\n ' - Standard Firestore: data.* filters without composite indexes will fail\\n' +\n ' See: https://github.com/typicalday/firegraph#query-modes',\n );\n }\n\n const backend = createFirestoreBackend(db, collectionPath, { queryMode: effectiveMode });\n\n let metaBackend: StorageBackend | undefined;\n if (options?.registryMode?.collection && options.registryMode.collection !== collectionPath) {\n metaBackend = createFirestoreBackend(db, options.registryMode.collection, {\n queryMode: effectiveMode,\n });\n }\n\n return new GraphClientImpl(backend, options, metaBackend) as GraphClient | DynamicGraphClient;\n}\n","import { nanoid } from 'nanoid';\n\nexport function generateId(): string {\n return nanoid();\n}\n","import type { DiscoveryResult, RegistryEntry } from './types.js';\n\nexport interface FirestoreIndexField {\n fieldPath: string;\n order: 'ASCENDING' | 'DESCENDING';\n}\n\nexport interface FirestoreIndex {\n collectionGroup: string;\n queryScope: 'COLLECTION' | 'COLLECTION_GROUP';\n fields: FirestoreIndexField[];\n}\n\nexport interface FirestoreIndexConfig {\n indexes: FirestoreIndex[];\n fieldOverrides: unknown[];\n}\n\n/**\n * Base composite indexes required for all firegraph collections.\n * These cover the standard query patterns:\n * - Forward edge lookup: (aUid, axbType)\n * - Reverse edge lookup: (axbType, bUid)\n * - Type-scoped queries: (aType, axbType) — also covers findNodes\n * - Edge type + target: (axbType, bType)\n */\nfunction baseIndexes(collection: string): FirestoreIndex[] {\n return [\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aUid', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bUid', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aType', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bType', order: 'ASCENDING' },\n ],\n },\n ];\n}\n\n/**\n * Extracts top-level field names from a JSON Schema object.\n * Only returns fields from schemas with type: \"object\" and properties.\n */\nfunction extractSchemaFields(schema: object): string[] {\n const s = schema as Record<string, unknown>;\n if (s.type !== 'object' || !s.properties) return [];\n return Object.keys(s.properties as Record<string, unknown>);\n}\n\n/**\n * Collection group indexes for `findEdgesGlobal()` queries.\n *\n * These mirror the base collection indexes but with `COLLECTION_GROUP` scope,\n * which allows querying across all subcollections with the given name.\n * Only generated when the registry has edge types with `targetGraph` set,\n * indicating cross-graph edges exist and global queries are likely.\n */\nfunction collectionGroupIndexes(collectionName: string): FirestoreIndex[] {\n return [\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'aUid', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bUid', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'aType', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bType', order: 'ASCENDING' },\n ],\n },\n ];\n}\n\n/**\n * Generates a Firestore index configuration for a firegraph collection.\n *\n * Always includes the 4 base composite indexes. If an entity discovery result\n * is provided, generates additional data-field indexes for common query\n * patterns on node data fields:\n * (aType, axbType, data.{field})\n *\n * When registry entries with `targetGraph` are provided, also generates\n * collection group indexes for `findEdgesGlobal()` queries. The collection\n * group name defaults to `'graph'` (the standard subgraph name) but can be\n * overridden per `targetGraph` value.\n *\n * @param collection - Firestore collection name (e.g. 'graph')\n * @param entities - Optional discovery result for per-entity data field indexes\n * @param registryEntries - Optional registry entries; when any have `targetGraph`,\n * collection group indexes are generated for the distinct subgraph names\n */\nexport function generateIndexConfig(\n collection: string,\n entities?: DiscoveryResult,\n registryEntries?: ReadonlyArray<RegistryEntry>,\n): FirestoreIndexConfig {\n const indexes = baseIndexes(collection);\n\n if (entities) {\n // Generate data-field indexes for node types.\n // Pattern: (aType, axbType, data.{field}) — covers findNodes with where clauses\n // and findEdges scoped by aType + axbType + data filter.\n for (const [, entity] of entities.nodes) {\n const fields = extractSchemaFields(entity.schema);\n for (const field of fields) {\n indexes.push({\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aType', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: `data.${field}`, order: 'ASCENDING' },\n ],\n });\n }\n }\n\n // Generate data-field indexes for edge types.\n // Pattern: (aUid, axbType, data.{field}) — covers forward edge lookups with data filters.\n for (const [, entity] of entities.edges) {\n const fields = extractSchemaFields(entity.schema);\n for (const field of fields) {\n indexes.push({\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aUid', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: `data.${field}`, order: 'ASCENDING' },\n ],\n });\n }\n }\n }\n\n // Generate collection group indexes when cross-graph edges exist.\n // Each distinct targetGraph value gets its own set of collection group indexes.\n if (registryEntries) {\n const targetGraphNames = new Set<string>();\n for (const entry of registryEntries) {\n if (entry.targetGraph) {\n targetGraphNames.add(entry.targetGraph);\n }\n }\n for (const name of targetGraphNames) {\n indexes.push(...collectionGroupIndexes(name));\n }\n }\n\n return { indexes, fieldOverrides: [] };\n}\n","import { FieldValue } from '@google-cloud/firestore';\nimport { NODE_RELATION } from './internal/constants.js';\nimport type { GraphRecord } from './types.js';\n\nexport function buildNodeRecord(\n aType: string,\n uid: string,\n data: Record<string, unknown>,\n): GraphRecord {\n const now = FieldValue.serverTimestamp();\n return {\n aType,\n aUid: uid,\n axbType: NODE_RELATION,\n bType: aType,\n bUid: uid,\n data,\n createdAt: now,\n updatedAt: now,\n };\n}\n\nexport function buildEdgeRecord(\n aType: string,\n aUid: string,\n axbType: string,\n bType: string,\n bUid: string,\n data: Record<string, unknown>,\n): GraphRecord {\n const now = FieldValue.serverTimestamp();\n return {\n aType,\n aUid,\n axbType,\n bType,\n bUid,\n data,\n createdAt: now,\n updatedAt: now,\n };\n}\n","import { TraversalError } from './errors.js';\nimport type {\n GraphReader,\n GraphClient,\n GraphRegistry,\n StoredGraphRecord,\n FindEdgesParams,\n HopDefinition,\n TraversalOptions,\n HopResult,\n TraversalResult,\n TraversalBuilder,\n} from './types.js';\n\nconst DEFAULT_LIMIT = 10;\nconst DEFAULT_MAX_READS = 100;\nconst DEFAULT_CONCURRENCY = 5;\n\n/** One-time warning flag: emitted when cross-graph hop is silently skipped. */\nlet _crossGraphWarned = false;\n\n/** Type guard to check if a reader is a GraphClient (has subgraph method). */\nfunction isGraphClient(reader: GraphReader): reader is GraphClient {\n return 'subgraph' in reader && typeof (reader as GraphClient).subgraph === 'function';\n}\n\nclass Semaphore {\n private queue: Array<() => void> = [];\n private active = 0;\n\n constructor(private readonly slots: number) {}\n\n async acquire(): Promise<void> {\n if (this.active < this.slots) {\n this.active++;\n return;\n }\n return new Promise<void>((resolve) => {\n this.queue.push(resolve);\n });\n }\n\n release(): void {\n this.active--;\n const next = this.queue.shift();\n if (next) {\n this.active++;\n next();\n }\n }\n}\n\nclass TraversalBuilderImpl implements TraversalBuilder {\n private readonly hops: HopDefinition[] = [];\n\n constructor(\n private readonly reader: GraphReader,\n private readonly startUid: string,\n private readonly registry?: GraphRegistry,\n ) {}\n\n follow(axbType: string, options?: Omit<HopDefinition, 'axbType'>): TraversalBuilder {\n this.hops.push({ axbType, ...options });\n return this;\n }\n\n async run(options?: TraversalOptions): Promise<TraversalResult> {\n if (this.hops.length === 0) {\n throw new TraversalError('Traversal requires at least one follow() hop');\n }\n\n const maxReads = options?.maxReads ?? DEFAULT_MAX_READS;\n const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY;\n const returnIntermediates = options?.returnIntermediates ?? false;\n const semaphore = new Semaphore(concurrency);\n\n let totalReads = 0;\n let truncated = false;\n // Track (uid, reader) pairs to support context carry-forward across hops.\n // When a hop crosses into a subgraph, the resulting UIDs carry the subgraph\n // reader so subsequent hops without targetGraph stay in that subgraph.\n let sources: Array<{ uid: string; reader: GraphReader }> = [\n { uid: this.startUid, reader: this.reader },\n ];\n const hopResults: HopResult[] = [];\n\n for (let depth = 0; depth < this.hops.length; depth++) {\n const hop = this.hops[depth];\n\n if (sources.length === 0) {\n hopResults.push({\n axbType: hop.axbType,\n depth,\n edges: [],\n sourceCount: 0,\n truncated: false,\n });\n continue;\n }\n\n const hopEdges: Array<{ edge: StoredGraphRecord; reader: GraphReader }> = [];\n const sourceCount = sources.length;\n let hopTruncated = false;\n\n // Resolve targetGraph for this hop:\n // 1. Explicit on the hop definition takes precedence\n // 2. Otherwise check the registry for the axbType\n const resolvedTargetGraph = this.resolveTargetGraph(hop);\n const direction = hop.direction ?? 'forward';\n const isCrossGraph = direction === 'forward' && !!resolvedTargetGraph;\n\n const tasks = sources.map(({ uid, reader: sourceReader }) => async () => {\n if (totalReads >= maxReads) {\n hopTruncated = true;\n return;\n }\n\n await semaphore.acquire();\n try {\n if (totalReads >= maxReads) {\n hopTruncated = true;\n return;\n }\n\n totalReads++;\n\n const params: FindEdgesParams = { axbType: hop.axbType };\n\n if (direction === 'forward') {\n params.aUid = uid;\n if (hop.bType) params.bType = hop.bType;\n } else {\n params.bUid = uid;\n if (hop.aType) params.aType = hop.aType;\n }\n\n if (direction === 'forward' && hop.aType) {\n params.aType = hop.aType;\n }\n if (direction === 'reverse' && hop.bType) {\n params.bType = hop.bType;\n }\n\n if (hop.orderBy) params.orderBy = hop.orderBy;\n\n const limit = hop.limit ?? DEFAULT_LIMIT;\n if (hop.filter) {\n params.limit = 0;\n } else {\n params.limit = limit;\n }\n\n // Choose the reader for this hop:\n // - Cross-graph hop: create a subgraph reader from the ROOT client\n // (targetGraph is always relative to root)\n // - No cross-graph: use the carried-forward reader from previous hop\n // (context tracking — stay in whatever subgraph we're already in)\n let hopReader: GraphReader;\n let nextReader: GraphReader;\n if (isCrossGraph) {\n if (isGraphClient(this.reader)) {\n hopReader = this.reader.subgraph(uid, resolvedTargetGraph!);\n nextReader = hopReader;\n } else {\n hopReader = sourceReader;\n nextReader = sourceReader;\n if (!_crossGraphWarned) {\n _crossGraphWarned = true;\n console.warn(\n `[firegraph] Traversal hop \"${hop.axbType}\" has targetGraph \"${resolvedTargetGraph}\" ` +\n 'but the reader does not support subgraph(). Cross-graph hop will query the current ' +\n 'collection instead. Pass a GraphClient to createTraversal() to enable cross-graph traversal.',\n );\n }\n }\n } else {\n // No targetGraph — carry forward context from previous hop\n hopReader = sourceReader;\n nextReader = sourceReader;\n }\n\n let edges = await hopReader.findEdges(params);\n\n if (hop.filter) {\n edges = edges.filter(hop.filter);\n edges = edges.slice(0, limit);\n }\n\n for (const edge of edges) {\n hopEdges.push({ edge, reader: nextReader });\n }\n } finally {\n semaphore.release();\n }\n });\n\n await Promise.all(tasks.map((task) => task()));\n\n const edges = hopEdges.map((h) => h.edge);\n\n hopResults.push({\n axbType: hop.axbType,\n depth,\n edges: returnIntermediates ? [...edges] : edges,\n sourceCount,\n truncated: hopTruncated,\n });\n\n if (hopTruncated) {\n truncated = true;\n }\n\n // Build next sources with deduplication by UID.\n // When the same UID appears from multiple source readers, the first one wins.\n const seen = new Map<string, GraphReader>();\n for (const { edge, reader: edgeReader } of hopEdges) {\n const nextUid = direction === 'forward' ? edge.bUid : edge.aUid;\n if (!seen.has(nextUid)) {\n seen.set(nextUid, edgeReader);\n }\n }\n sources = [...seen.entries()].map(([uid, reader]) => ({ uid, reader }));\n }\n\n const lastHop = hopResults[hopResults.length - 1];\n\n return {\n nodes: lastHop.edges,\n hops: hopResults,\n totalReads,\n truncated,\n };\n }\n\n /**\n * Resolve the targetGraph for a hop. Priority:\n * 1. Explicit `hop.targetGraph` (user override)\n * 2. Registry `targetGraph` for the axbType (if registry available)\n * 3. undefined (no cross-graph)\n */\n private resolveTargetGraph(hop: HopDefinition): string | undefined {\n if (hop.targetGraph) return hop.targetGraph;\n\n if (this.registry) {\n const entries = this.registry.lookupByAxbType(hop.axbType);\n // All entries for the same axbType should share targetGraph; use the first non-undefined\n for (const entry of entries) {\n if (entry.targetGraph) return entry.targetGraph;\n }\n }\n\n return undefined;\n }\n}\n\n/** @internal Reset the one-time cross-graph warning flag (for testing). */\nexport function _resetCrossGraphWarning(): void {\n _crossGraphWarned = false;\n}\n\n/**\n * Create a traversal builder for multi-hop graph traversal.\n *\n * Accepts either a `GraphReader` (backwards compatible) or a `GraphClient`.\n * When a `GraphClient` is provided, cross-graph traversal via `targetGraph`\n * is supported — the traversal can follow edges into subgraphs.\n *\n * @param reader - A `GraphClient` or `GraphReader` to execute queries against\n * @param startUid - UID of the starting node\n * @param registry - Optional registry for automatic `targetGraph` resolution\n */\nexport function createTraversal(\n reader: GraphClient | GraphReader,\n startUid: string,\n registry?: GraphRegistry,\n): TraversalBuilder {\n return new TraversalBuilderImpl(reader, startUid, registry);\n}\n","/**\n * Model Views — framework-agnostic view definitions for graph entities.\n *\n * Projects define Web Components that render entity data in purpose-driven\n * ways. Each view class declares a static `viewName`, and receives the\n * entity's `data` payload via a `data` property setter.\n *\n * @example\n * ```ts\n * import { defineViews } from 'firegraph';\n *\n * class UserCard extends HTMLElement {\n * static viewName = 'card';\n * static description = 'Compact user card';\n * private _data: Record<string, unknown> = {};\n * set data(v: Record<string, unknown>) { this._data = v; this.render(); }\n * connectedCallback() { this.render(); }\n * private render() {\n * this.innerHTML = `<strong>${this._data.displayName ?? ''}</strong>`;\n * }\n * }\n *\n * export default defineViews({\n * nodes: { user: { views: [UserCard] } },\n * });\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A Web Component class used as a view. The class must have a static\n * `viewName` and must be constructable. It will be registered as a custom\n * element via `customElements.define()` in browser environments.\n *\n * Note: this interface avoids referencing `HTMLElement` directly so the\n * library can compile without DOM lib types. Consumer code (which has DOM)\n * will satisfy this constraint naturally.\n */\nexport interface ViewComponentClass {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (...args: any[]): { data: Record<string, unknown> };\n /** Short identifier for this view (e.g. 'card', 'profile'). */\n viewName: string;\n /** Optional human-readable description. */\n description?: string;\n}\n\n/** Configuration for all views of a single entity type. */\nexport interface EntityViewConfig {\n /** View component classes to register. */\n views: ViewComponentClass[];\n /**\n * Optional sample data for the gallery. A single object matching\n * the entity's JSON Schema — shared across all views.\n */\n sampleData?: Record<string, unknown>;\n}\n\n/** Input shape accepted by `defineViews()`. */\nexport interface ViewRegistryInput {\n /** Node views keyed by aType (e.g. 'user', 'tour'). */\n nodes?: Record<string, EntityViewConfig>;\n /** Edge views keyed by axbType (e.g. 'hasDeparture'). */\n edges?: Record<string, EntityViewConfig>;\n}\n\n/** Serialisable metadata for a single view. */\nexport interface ViewMeta {\n /** Custom element tag name (e.g. 'fg-user-card'). */\n tagName: string;\n /** Short identifier matching the component's static viewName. */\n viewName: string;\n /** Optional human-readable description. */\n description?: string;\n}\n\n/** Serialisable metadata for all views of a single entity type. */\nexport interface EntityViewMeta {\n views: ViewMeta[];\n sampleData?: Record<string, unknown>;\n}\n\n/** The resolved view registry returned by `defineViews()`. */\nexport interface ViewRegistry {\n nodes: Record<string, EntityViewMeta>;\n edges: Record<string, EntityViewMeta>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Sanitise a string for use as part of a custom element tag name. */\nfunction sanitizeTagPart(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n}\n\n/** Minimal interface for CustomElementRegistry (avoids depending on DOM lib). */\ninterface CustomElementRegistryLike {\n get(name: string): unknown;\n define(name: string, constructor: unknown): void;\n}\n\n/**\n * Try to access the browser's `customElements` registry.\n * Returns `null` in Node.js or environments without Web Components support.\n */\nfunction getCustomElements(): CustomElementRegistryLike | null {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const g = globalThis as any;\n if (g.customElements && typeof g.customElements.define === 'function') {\n return g.customElements as CustomElementRegistryLike;\n }\n return null;\n}\n\n/**\n * Wrap a view class so that errors in connectedCallback, disconnectedCallback,\n * and the data setter are caught and logged rather than crashing the page.\n * Shows an inline error message when the view fails to render.\n */\nfunction resilientView(ViewClass: ViewComponentClass, tagName: string): ViewComponentClass {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const g = globalThis as any;\n if (!g.HTMLElement) return ViewClass; // Node.js — no wrapping needed\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Base = g.HTMLElement as any;\n\n const Wrapped = class extends (ViewClass as unknown as typeof Base) {\n connectedCallback() {\n try {\n super.connectedCallback?.();\n } catch (err) {\n console.warn(`[firegraph] <${tagName}> connectedCallback error:`, err);\n this._showError(err);\n }\n }\n\n disconnectedCallback() {\n try {\n super.disconnectedCallback?.();\n } catch (err) {\n console.warn(`[firegraph] <${tagName}> disconnectedCallback error:`, err);\n }\n }\n\n set data(v: Record<string, unknown>) {\n try {\n super.data = v;\n } catch (err) {\n console.warn(`[firegraph] <${tagName}> data setter error:`, err);\n this._showError(err);\n }\n }\n\n get data(): Record<string, unknown> {\n try {\n return super.data;\n } catch {\n return {};\n }\n }\n\n _showError(err: unknown) {\n try {\n this.innerHTML = `<div style=\"padding:6px;color:#f87171;font-size:11px;font-family:monospace;\">` +\n `View error in &lt;${tagName}&gt;: ${err instanceof Error ? err.message : String(err)}</div>`;\n } catch { /* last resort — don't throw from error handler */ }\n }\n };\n\n // Preserve static metadata\n (Wrapped as unknown as ViewComponentClass).viewName = ViewClass.viewName;\n (Wrapped as unknown as ViewComponentClass).description = ViewClass.description;\n\n return Wrapped as unknown as ViewComponentClass;\n}\n\n// ---------------------------------------------------------------------------\n// defineViews()\n// ---------------------------------------------------------------------------\n\n/**\n * Build a `ViewRegistry` from component classes.\n *\n * In the browser the components are registered as custom elements with\n * deterministic tag names (`fg-{entityType}-{viewName}`). On the server\n * (Node.js) only metadata is returned — no custom element registration.\n */\nexport function defineViews(input: ViewRegistryInput): ViewRegistry {\n const nodes: Record<string, EntityViewMeta> = {};\n const edges: Record<string, EntityViewMeta> = {};\n const registry = getCustomElements();\n\n // --- nodes ---\n for (const [entityType, config] of Object.entries(input.nodes ?? {})) {\n const viewMetas: ViewMeta[] = [];\n for (const ViewClass of config.views) {\n const tagName = `fg-${sanitizeTagPart(entityType)}-${sanitizeTagPart(ViewClass.viewName)}`;\n viewMetas.push({\n tagName,\n viewName: ViewClass.viewName,\n description: ViewClass.description,\n });\n if (registry && !registry.get(tagName)) {\n registry.define(tagName, resilientView(ViewClass, tagName));\n }\n }\n nodes[entityType] = {\n views: viewMetas,\n sampleData: config.sampleData,\n };\n }\n\n // --- edges ---\n for (const [axbType, config] of Object.entries(input.edges ?? {})) {\n const viewMetas: ViewMeta[] = [];\n for (const ViewClass of config.views) {\n const tagName = `fg-edge-${sanitizeTagPart(axbType)}-${sanitizeTagPart(ViewClass.viewName)}`;\n viewMetas.push({\n tagName,\n viewName: ViewClass.viewName,\n description: ViewClass.description,\n });\n if (registry && !registry.get(tagName)) {\n registry.define(tagName, resilientView(ViewClass, tagName));\n }\n }\n edges[axbType] = {\n views: viewMetas,\n sampleData: config.sampleData,\n };\n }\n\n return { nodes, edges };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHO,SAAS,aAAa,QAA0C;AACrE,SAAO;AACT;AAeO,SAAS,YACd,gBACA,oBACA,SACQ;AACR,MAAI,CAAC,eAAgB,QAAO;AAE5B,QAAM,YAAY,IAAI,IAAI,kBAAkB;AAE5C,MAAI,SAAS;AACX,UAAM,iBAAiB,eAAe,OAAO;AAC7C,QAAI,kBAAkB,UAAU,IAAI,cAAc,GAAG;AACnD,aAAO;AAAA,IACT;AAAA,EACF;AAEA,MAAI,eAAe,WAAW,UAAU,IAAI,eAAe,OAAO,GAAG;AACnE,WAAO,eAAe;AAAA,EACxB;AAEA,SAAO;AACT;;;AClHO,SAAS,0BACd,gBACA,KACe;AACf,QAAM,WAAW,eAAe,MAAM,GAAG;AAGzC,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,GAAG;AAC3C,QAAI,SAAS,CAAC,MAAM,KAAK;AAEvB,aAAO,SAAS,MAAM,GAAG,CAAC,EAAE,KAAK,GAAG;AAAA,IACtC;AAAA,EACF;AAEA,SAAO;AACT;AASO,SAAS,cACd,gBACA,KACS;AACT,SAAO,0BAA0B,gBAAgB,GAAG,MAAM;AAC5D;;;ACnCA,SAAS,cAAc,aAAa,YAAY,gBAAgB;AAChE,SAAS,qBAAqB;AAC9B,SAAS,MAAM,eAAe;AAKvB,IAAM,iBAAN,cAA6B,eAAe;AAAA,EACjD,YAAY,SAAiB;AAC3B,UAAM,SAAS,iBAAiB;AAChC,SAAK,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CAAC;AACD,UAAI,YAAY,CAAC,SAAS,IAAI,OAAO,GAAG;AACtC,iBAAS,OAAO,SAAS,cAAc,WAAW,OAAO,CAAC;AAAA,MAC5D;AAAA,IACF;AACA,UAAM,UAAU,IAAI;AAAA,MAClB,OAAO;AAAA,MACP,YAAY,OAAO;AAAA,IACrB;AAAA,EACF;AAGA,aAAW,CAAC,SAAS,MAAM,KAAK,OAAO,QAAQ,MAAM,SAAS,CAAC,CAAC,GAAG;AACjE,UAAM,YAAwB,CAAC;AAC/B,eAAW,aAAa,OAAO,OAAO;AACpC,YAAM,UAAU,WAAW,gBAAgB,OAAO,CAAC,IAAI,gBAAgB,UAAU,QAAQ,CAAC;AAC1F,gBAAU,KAAK;AAAA,QACb;AAAA,QACA,UAAU,UAAU;AAAA,QACpB,aAAa,UAAU;AAAA,MACzB,CAAC;AACD,UAAI,YAAY,CAAC,SAAS,IAAI,OAAO,GAAG;AACtC,iBAAS,OAAO,SAAS,cAAc,WAAW,OAAO,CAAC;AAAA,MAC5D;AAAA,IACF;AACA,UAAM,OAAO,IAAI;AAAA,MACf,OAAO;AAAA,MACP,YAAY,OAAO;AAAA,IACrB;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,MAAM;AACxB;","names":["resolve","FieldValue","FieldValue","resolve","edges"]}
1
+ {"version":3,"sources":["../src/config.ts","../src/cross-graph.ts","../src/discover.ts","../src/internal/firestore-backend.ts","../src/bulk.ts","../src/internal/firestore-adapter.ts","../src/internal/pipeline-adapter.ts","../src/firestore.ts","../src/id.ts","../src/indexes.ts","../src/record.ts","../src/traverse.ts","../src/views.ts"],"sourcesContent":["/**\n * Firegraph Configuration — project-level config file support.\n *\n * Projects create a `firegraph.config.ts` (or `.js`/`.mjs`) in their root:\n *\n * @example\n * ```ts\n * import { defineConfig } from 'firegraph';\n *\n * export default defineConfig({\n * entities: './entities',\n * project: 'my-project',\n * collection: 'graph',\n * });\n * ```\n */\n\nimport type { DynamicRegistryConfig, QueryMode } from './types.js';\n\n// ---------------------------------------------------------------------------\n// View Resolution Types\n// ---------------------------------------------------------------------------\n\n/** Display contexts where views can appear. */\nexport type ViewContext = 'listing' | 'detail' | 'inline';\n\n/** View resolution configuration for a single entity type. */\nexport interface ViewResolverConfig {\n /** Default view name (e.g. 'card'). Falls back to 'json' if unset. */\n default?: string;\n /** View to use in NodeBrowser listing rows. */\n listing?: string;\n /** View to use on the NodeDetail page. */\n detail?: string;\n /** View to use for inline/embedded previews (edge rows, traversal). */\n inline?: string;\n}\n\n/** Declarative view defaults, keyed by entity type. */\nexport interface ViewDefaultsConfig {\n /** Node view defaults keyed by aType (e.g. 'user', 'task'). */\n nodes?: Record<string, ViewResolverConfig>;\n /** Edge view defaults keyed by axbType (e.g. 'hasDeparture'). */\n edges?: Record<string, ViewResolverConfig>;\n}\n\n// ---------------------------------------------------------------------------\n// Config Shape\n// ---------------------------------------------------------------------------\n\n/** Project-level firegraph configuration. */\nexport interface FiregraphConfig {\n /** Path to entities directory (per-entity folder convention). */\n entities?: string;\n /** GCP project ID. */\n project?: string;\n /** Firestore collection path (default: 'graph'). */\n collection?: string;\n /** Firestore emulator address (e.g. '127.0.0.1:8080'). */\n emulator?: string;\n /**\n * Query execution backend.\n *\n * - `'pipeline'` (default) — Uses Firestore Pipeline API. Requires Enterprise\n * Firestore. Enables indexless queries on `data.*` fields.\n * - `'standard'` — Uses standard Firestore `.where().get()` queries. Not\n * recommended for production. See README for risk details.\n *\n * When the emulator is active, always falls back to `'standard'`.\n */\n queryMode?: QueryMode;\n\n /**\n * AI chat configuration. Auto-detects `claude` CLI on PATH by default.\n * Set to `false` to disable chat even if claude is available.\n */\n chat?:\n | false\n | {\n /** Claude model to use (default: 'sonnet'). */\n model?: string;\n /** Maximum concurrent claude processes (default: 2). */\n maxConcurrency?: number;\n };\n\n /** Editor-specific settings. */\n editor?: {\n /** Server port (default: 3883). */\n port?: number;\n /** Force read-only mode. */\n readonly?: boolean;\n };\n\n /** Declarative view defaults per entity type (overrides per-entity meta.json). */\n viewDefaults?: ViewDefaultsConfig;\n\n /**\n * Dynamic registry mode. When set, the editor loads type definitions\n * from Firestore meta-nodes in addition to filesystem entities.\n * Filesystem types take precedence on name conflicts.\n */\n registryMode?: DynamicRegistryConfig;\n}\n\n// ---------------------------------------------------------------------------\n// defineConfig()\n// ---------------------------------------------------------------------------\n\n/**\n * Identity function providing type-checking and autocomplete for config files.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'firegraph';\n * export default defineConfig({ entities: './entities' });\n * ```\n */\nexport function defineConfig(config: FiregraphConfig): FiregraphConfig {\n return config;\n}\n\n// ---------------------------------------------------------------------------\n// View Resolution (pure — works client-side and server-side)\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve which view to show for a given entity.\n *\n * 1. If `context` is provided and a context-specific default exists, use it.\n * 2. Falls back to `resolverConfig.default`.\n * 3. Ultimate fallback: `'json'`.\n *\n * Only returns view names that exist in `availableViewNames`.\n */\nexport function resolveView(\n resolverConfig: ViewResolverConfig | undefined,\n availableViewNames: string[],\n context?: ViewContext,\n): string {\n if (!resolverConfig) return 'json';\n\n const available = new Set(availableViewNames);\n\n if (context) {\n const contextDefault = resolverConfig[context];\n if (contextDefault && available.has(contextDefault)) {\n return contextDefault;\n }\n }\n\n if (resolverConfig.default && available.has(resolverConfig.default)) {\n return resolverConfig.default;\n }\n\n return 'json';\n}\n","/**\n * Cross-graph edge resolution utilities.\n *\n * Provides path-scanning resolution for determining whether an edge's source\n * (aUid) is an ancestor node by checking if the UID appears in the Firestore\n * collection path.\n *\n * Firestore paths have a rigid alternating structure:\n * collection / docId / collection / docId / collection\n *\n * Given a path like `graph/A/workspace/B/context`, segments at even indices\n * are collection names and odd indices are document IDs. When we find a UID\n * at an odd index, the collection containing that document is the path up to\n * (and including) the preceding even-index segment.\n */\n\n/**\n * Parse a Firestore collection path and determine the collection path\n * where a given UID's document lives, if that UID is an ancestor in the path.\n *\n * @param collectionPath - The full Firestore collection path of the current client\n * @param uid - The UID to search for in the path\n * @returns The collection path containing the UID, or `null` if not found in the path\n *\n * @example\n * ```ts\n * // Path: graph/A/workspace/B/context\n * resolveAncestorCollection('graph/A/workspace/B/context', 'A')\n * // → 'graph'\n *\n * resolveAncestorCollection('graph/A/workspace/B/context', 'B')\n * // → 'graph/A/workspace'\n *\n * resolveAncestorCollection('graph/A/workspace/B/context', 'unknown')\n * // → null\n * ```\n */\nexport function resolveAncestorCollection(\n collectionPath: string,\n uid: string,\n): string | null {\n const segments = collectionPath.split('/');\n\n // Walk odd-indexed segments (document IDs in Firestore's alternating path structure)\n for (let i = 1; i < segments.length; i += 2) {\n if (segments[i] === uid) {\n // The collection containing this doc is everything up to index i-1\n return segments.slice(0, i).join('/');\n }\n }\n\n return null;\n}\n\n/**\n * Check whether a UID belongs to an ancestor node by scanning the collection path.\n *\n * @param collectionPath - The full Firestore collection path of the current client\n * @param uid - The UID to check\n * @returns `true` if the UID appears as a document segment in the path\n */\nexport function isAncestorUid(\n collectionPath: string,\n uid: string,\n): boolean {\n return resolveAncestorCollection(collectionPath, uid) !== null;\n}\n","/**\n * Entity Discovery — convention-based auto-discovery of entities from\n * a per-entity folder structure.\n *\n * Scans `entitiesDir/nodes/` and `entitiesDir/edges/` subdirectories.\n * Each subfolder is treated as an entity type.\n *\n * Schema files can be either `schema.json` (plain JSON Schema) or\n * `schema.ts` / `schema.js` (a module whose default export is a JSON Schema\n * object). When both exist, the TS/JS file takes precedence so that authors\n * can compose schemas programmatically while keeping a JSON fallback.\n *\n * @example\n * ```\n * entities/\n * nodes/\n * task/\n * schema.json | schema.ts (required — one or both)\n * views.ts (optional)\n * sample.json (optional)\n * meta.json (optional)\n * edges/\n * hasStep/\n * schema.json | schema.ts (required — one or both)\n * edge.json (required — topology)\n * views.ts (optional)\n * sample.json (optional)\n * meta.json (optional)\n * ```\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join, resolve } from 'node:path';\n\nimport type * as jitiNS from 'jiti';\n\nimport type { ViewResolverConfig } from './config.js';\nimport { FiregraphError } from './errors.js';\nimport type {\n DiscoveredEntity,\n DiscoveryResult,\n EdgeTopology,\n MigrationStep,\n MigrationWriteBack,\n} from './types.js';\n\nexport class DiscoveryError extends FiregraphError {\n constructor(message: string) {\n super(message, 'DISCOVERY_ERROR');\n this.name = 'DiscoveryError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// JSON parsing helpers\n// ---------------------------------------------------------------------------\n\nfunction readJson(filePath: string): unknown {\n try {\n const raw = readFileSync(filePath, 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n const msg =\n err instanceof SyntaxError\n ? `Invalid JSON in ${filePath}: ${err.message}`\n : `Cannot read ${filePath}: ${(err as Error).message}`;\n throw new DiscoveryError(msg);\n }\n}\n\nfunction readJsonIfExists(filePath: string): unknown | undefined {\n if (!existsSync(filePath)) return undefined;\n return readJson(filePath);\n}\n\n// ---------------------------------------------------------------------------\n// Schema file loading (JSON or TS/JS via jiti)\n// ---------------------------------------------------------------------------\n\nconst SCHEMA_SCRIPT_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\n/**\n * Attempt to load a schema from a TS/JS module (default export) or fall back\n * to schema.json. Returns the parsed schema object or throws.\n */\nfunction loadSchema(dir: string, entityLabel: string): object {\n // Prefer TS/JS schema — allows programmatic composition & shared definitions\n for (const ext of SCHEMA_SCRIPT_EXTENSIONS) {\n const candidate = join(dir, `schema${ext}`);\n if (existsSync(candidate)) {\n return loadSchemaModule(candidate, entityLabel);\n }\n }\n\n // Fall back to schema.json\n const jsonPath = join(dir, 'schema.json');\n if (existsSync(jsonPath)) {\n return readJson(jsonPath) as object;\n }\n\n throw new DiscoveryError(\n `Missing schema for ${entityLabel} in ${dir}. ` +\n 'Provide a schema.ts (or .js/.mts/.mjs) or schema.json file.',\n );\n}\n\nlet _jiti: ((id: string) => unknown) | undefined;\n\nfunction getJiti(): (id: string) => unknown {\n if (!_jiti) {\n const base = typeof __filename !== 'undefined' ? __filename : import.meta.url;\n const esmRequire = createRequire(base);\n const { createJiti } = esmRequire('jiti') as typeof jitiNS;\n _jiti = createJiti(base, { interopDefault: true });\n }\n return _jiti;\n}\n\nfunction loadSchemaModule(filePath: string, entityLabel: string): object {\n try {\n const jiti = getJiti();\n const mod = jiti(filePath) as { default?: unknown } | unknown;\n const schema =\n mod && typeof mod === 'object' && 'default' in mod\n ? (mod as { default: unknown }).default\n : mod;\n\n if (!schema || typeof schema !== 'object') {\n throw new DiscoveryError(\n `Schema file ${filePath} for ${entityLabel} must default-export a JSON Schema object.`,\n );\n }\n return schema as object;\n } catch (err: unknown) {\n if (err instanceof DiscoveryError) throw err;\n throw new DiscoveryError(\n `Failed to load schema module ${filePath} for ${entityLabel}: ${(err as Error).message}`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// View file detection\n// ---------------------------------------------------------------------------\n\nconst VIEW_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\nfunction findViewsFile(dir: string): string | undefined {\n for (const ext of VIEW_EXTENSIONS) {\n const candidate = join(dir, `views${ext}`);\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Migration file detection & loading\n// ---------------------------------------------------------------------------\n\nconst MIGRATION_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs'];\n\nfunction findMigrationsFile(dir: string): string | undefined {\n for (const ext of MIGRATION_EXTENSIONS) {\n const candidate = join(dir, `migrations${ext}`);\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\nfunction loadMigrations(filePath: string, entityLabel: string): MigrationStep[] {\n try {\n const jiti = getJiti();\n const mod = jiti(filePath) as { default?: unknown } | unknown;\n const migrations =\n mod && typeof mod === 'object' && 'default' in mod\n ? (mod as { default: unknown }).default\n : mod;\n\n if (!Array.isArray(migrations)) {\n throw new DiscoveryError(\n `Migrations file ${filePath} for ${entityLabel} must default-export an array of MigrationStep.`,\n );\n }\n return migrations as MigrationStep[];\n } catch (err: unknown) {\n if (err instanceof DiscoveryError) throw err;\n throw new DiscoveryError(\n `Failed to load migrations ${filePath} for ${entityLabel}: ${(err as Error).message}`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Entity loaders\n// ---------------------------------------------------------------------------\n\nfunction loadNodeEntity(dir: string, name: string): DiscoveredEntity {\n const schema = loadSchema(dir, `node type \"${name}\"`);\n const meta = readJsonIfExists(join(dir, 'meta.json')) as\n | {\n description?: string;\n titleField?: string;\n subtitleField?: string;\n viewDefaults?: ViewResolverConfig;\n allowedIn?: string[];\n migrationWriteBack?: MigrationWriteBack;\n }\n | undefined;\n const sampleData = readJsonIfExists(join(dir, 'sample.json')) as\n | Record<string, unknown>\n | undefined;\n const viewsPath = findViewsFile(dir);\n const migrationsPath = findMigrationsFile(dir);\n const migrations = migrationsPath\n ? loadMigrations(migrationsPath, `node type \"${name}\"`)\n : undefined;\n\n return {\n kind: 'node',\n name,\n schema,\n description: meta?.description,\n titleField: meta?.titleField,\n subtitleField: meta?.subtitleField,\n viewDefaults: meta?.viewDefaults,\n viewsPath,\n sampleData,\n allowedIn: meta?.allowedIn,\n migrations,\n migrationWriteBack: meta?.migrationWriteBack,\n };\n}\n\nfunction loadEdgeEntity(dir: string, name: string): DiscoveredEntity {\n const schema = loadSchema(dir, `edge type \"${name}\"`);\n\n const edgePath = join(dir, 'edge.json');\n if (!existsSync(edgePath)) {\n throw new DiscoveryError(\n `Missing edge.json for edge type \"${name}\" in ${dir}. ` +\n 'Edge entities must declare topology (from/to node types).',\n );\n }\n const topology = readJson(edgePath) as EdgeTopology;\n\n // Validate topology shape\n if (!topology.from) {\n throw new DiscoveryError(`edge.json for \"${name}\" is missing required \"from\" field`);\n }\n if (!topology.to) {\n throw new DiscoveryError(`edge.json for \"${name}\" is missing required \"to\" field`);\n }\n\n const meta = readJsonIfExists(join(dir, 'meta.json')) as\n | {\n description?: string;\n titleField?: string;\n subtitleField?: string;\n viewDefaults?: ViewResolverConfig;\n allowedIn?: string[];\n targetGraph?: string;\n migrationWriteBack?: MigrationWriteBack;\n }\n | undefined;\n const sampleData = readJsonIfExists(join(dir, 'sample.json')) as\n | Record<string, unknown>\n | undefined;\n const viewsPath = findViewsFile(dir);\n const migrationsPath = findMigrationsFile(dir);\n const migrations = migrationsPath\n ? loadMigrations(migrationsPath, `edge type \"${name}\"`)\n : undefined;\n\n return {\n kind: 'edge',\n name,\n schema,\n topology,\n description: meta?.description,\n titleField: meta?.titleField,\n subtitleField: meta?.subtitleField,\n viewDefaults: meta?.viewDefaults,\n viewsPath,\n sampleData,\n allowedIn: meta?.allowedIn,\n targetGraph:\n topology.targetGraph ?? (meta as { targetGraph?: string } | undefined)?.targetGraph,\n migrations,\n migrationWriteBack: meta?.migrationWriteBack,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Directory scanner\n// ---------------------------------------------------------------------------\n\nfunction getSubdirectories(dir: string): string[] {\n if (!existsSync(dir)) return [];\n return readdirSync(dir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface DiscoveryWarning {\n code: 'DANGLING_TOPOLOGY_REF';\n message: string;\n}\n\nexport interface DiscoverResult {\n result: DiscoveryResult;\n warnings: DiscoveryWarning[];\n}\n\n/**\n * Scan an entities directory and return all discovered nodes and edges.\n *\n * @param entitiesDir - Path to the entities directory (absolute or relative to cwd)\n * @returns Discovery result with nodes and edges maps, plus any warnings\n */\nexport function discoverEntities(entitiesDir: string): DiscoverResult {\n const absDir = resolve(entitiesDir);\n\n if (!existsSync(absDir) || !statSync(absDir).isDirectory()) {\n throw new DiscoveryError(`Entities directory not found: ${entitiesDir}`);\n }\n\n const nodes = new Map<string, DiscoveredEntity>();\n const edges = new Map<string, DiscoveredEntity>();\n const warnings: DiscoveryWarning[] = [];\n\n // Discover nodes\n const nodesDir = join(absDir, 'nodes');\n for (const name of getSubdirectories(nodesDir)) {\n nodes.set(name, loadNodeEntity(join(nodesDir, name), name));\n }\n\n // Discover edges\n const edgesDir = join(absDir, 'edges');\n for (const name of getSubdirectories(edgesDir)) {\n edges.set(name, loadEdgeEntity(join(edgesDir, name), name));\n }\n\n // Validate topology references\n const nodeNames = new Set(nodes.keys());\n for (const [axbType, entity] of edges) {\n const topology = entity.topology!;\n const fromTypes = Array.isArray(topology.from) ? topology.from : [topology.from];\n const toTypes = Array.isArray(topology.to) ? topology.to : [topology.to];\n\n for (const ref of [...fromTypes, ...toTypes]) {\n if (!nodeNames.has(ref)) {\n warnings.push({\n code: 'DANGLING_TOPOLOGY_REF',\n message: `Edge \"${axbType}\" references node type \"${ref}\" which was not found in the nodes directory`,\n });\n }\n }\n }\n\n return {\n result: { nodes, edges },\n warnings,\n };\n}\n","/**\n * Firestore implementation of `StorageBackend`.\n *\n * Wraps the existing `FirestoreAdapter`, `TransactionAdapter`, and\n * `BatchAdapter` so the Firestore code path keeps the exact behavior it\n * had before the backend abstraction landed.\n */\n\nimport type { Firestore, Query, Transaction } from '@google-cloud/firestore';\nimport { FieldValue } from '@google-cloud/firestore';\n\nimport {\n bulkRemoveEdges as bulkRemoveEdgesImpl,\n removeNodeCascade as removeNodeCascadeImpl,\n} from '../bulk.js';\nimport { FiregraphError } from '../errors.js';\nimport { buildEdgeQueryPlan } from '../query.js';\nimport { deserializeFirestoreTypes } from '../serialization.js';\nimport type {\n BulkOptions,\n BulkResult,\n CascadeResult,\n FindEdgesParams,\n GraphReader,\n QueryFilter,\n QueryMode,\n QueryOptions,\n StoredGraphRecord,\n} from '../types.js';\nimport type {\n BatchBackend,\n StorageBackend,\n TransactionBackend,\n UpdatePayload,\n WritableRecord,\n} from './backend.js';\nimport type { BatchAdapter, FirestoreAdapter, TransactionAdapter } from './firestore-adapter.js';\nimport {\n createBatchAdapter,\n createFirestoreAdapter,\n createTransactionAdapter,\n} from './firestore-adapter.js';\nimport type { PipelineQueryAdapter } from './pipeline-adapter.js';\nimport { createPipelineQueryAdapter } from './pipeline-adapter.js';\n\nexport interface FirestoreBackendOptions {\n queryMode?: QueryMode;\n scopePath?: string;\n}\n\n/**\n * Build the patch payload Firestore expects from an `UpdatePayload`.\n *\n * - `replaceData` sets the whole `data` field at once. Tagged Firestore\n * types from the migration sandbox are reconstructed here.\n * - `dataFields` uses Firestore's `data.<key>` dotted-path syntax.\n * - `updatedAt` is always stamped with `FieldValue.serverTimestamp()`.\n * - `v` is stamped at the root when provided.\n */\nfunction buildFirestoreUpdate(update: UpdatePayload, db: Firestore): Record<string, unknown> {\n const out: Record<string, unknown> = {\n updatedAt: FieldValue.serverTimestamp(),\n };\n if (update.replaceData) {\n out.data = deserializeFirestoreTypes(update.replaceData, db);\n }\n if (update.dataFields) {\n for (const [k, v] of Object.entries(update.dataFields)) {\n out[`data.${k}`] = v;\n }\n }\n if (update.v !== undefined) {\n out.v = update.v;\n }\n return out;\n}\n\n/**\n * Stamp `createdAt`/`updatedAt` server-timestamp sentinels on a\n * timestampless record. Used for `setDoc`.\n */\nfunction stampWritableRecord(record: WritableRecord): Record<string, unknown> {\n const now = FieldValue.serverTimestamp();\n const out: Record<string, unknown> = {\n aType: record.aType,\n aUid: record.aUid,\n axbType: record.axbType,\n bType: record.bType,\n bUid: record.bUid,\n data: record.data,\n createdAt: now,\n updatedAt: now,\n };\n if (record.v !== undefined) out.v = record.v;\n return out;\n}\n\nclass FirestoreTransactionBackend implements TransactionBackend {\n constructor(\n private readonly adapter: TransactionAdapter,\n private readonly db: Firestore,\n ) {}\n\n getDoc(docId: string): Promise<StoredGraphRecord | null> {\n return this.adapter.getDoc(docId);\n }\n\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n return this.adapter.query(filters, options);\n }\n\n async setDoc(docId: string, record: WritableRecord): Promise<void> {\n this.adapter.setDoc(docId, stampWritableRecord(record));\n }\n\n async updateDoc(docId: string, update: UpdatePayload): Promise<void> {\n this.adapter.updateDoc(docId, buildFirestoreUpdate(update, this.db));\n }\n\n async deleteDoc(docId: string): Promise<void> {\n this.adapter.deleteDoc(docId);\n }\n}\n\nclass FirestoreBatchBackend implements BatchBackend {\n constructor(\n private readonly adapter: BatchAdapter,\n private readonly db: Firestore,\n ) {}\n\n setDoc(docId: string, record: WritableRecord): void {\n this.adapter.setDoc(docId, stampWritableRecord(record));\n }\n\n updateDoc(docId: string, update: UpdatePayload): void {\n this.adapter.updateDoc(docId, buildFirestoreUpdate(update, this.db));\n }\n\n deleteDoc(docId: string): void {\n this.adapter.deleteDoc(docId);\n }\n\n commit(): Promise<void> {\n return this.adapter.commit();\n }\n}\n\nclass FirestoreBackendImpl implements StorageBackend {\n readonly collectionPath: string;\n readonly scopePath: string;\n private readonly adapter: FirestoreAdapter;\n private readonly pipelineAdapter?: PipelineQueryAdapter;\n\n constructor(\n private readonly db: Firestore,\n collectionPath: string,\n private readonly queryMode: QueryMode,\n scopePath: string,\n ) {\n this.collectionPath = collectionPath;\n this.scopePath = scopePath;\n this.adapter = createFirestoreAdapter(db, collectionPath);\n if (queryMode === 'pipeline') {\n this.pipelineAdapter = createPipelineQueryAdapter(db, collectionPath);\n }\n }\n\n // --- Reads ---\n\n getDoc(docId: string): Promise<StoredGraphRecord | null> {\n return this.adapter.getDoc(docId);\n }\n\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n if (this.pipelineAdapter) {\n return this.pipelineAdapter.query(filters, options);\n }\n return this.adapter.query(filters, options);\n }\n\n // --- Writes ---\n\n setDoc(docId: string, record: WritableRecord): Promise<void> {\n return this.adapter.setDoc(docId, stampWritableRecord(record));\n }\n\n updateDoc(docId: string, update: UpdatePayload): Promise<void> {\n return this.adapter.updateDoc(docId, buildFirestoreUpdate(update, this.db));\n }\n\n deleteDoc(docId: string): Promise<void> {\n return this.adapter.deleteDoc(docId);\n }\n\n // --- Transactions / Batches ---\n\n runTransaction<T>(fn: (tx: TransactionBackend) => Promise<T>): Promise<T> {\n return this.db.runTransaction(async (firestoreTx: Transaction) => {\n const txAdapter = createTransactionAdapter(this.db, this.collectionPath, firestoreTx);\n return fn(new FirestoreTransactionBackend(txAdapter, this.db));\n });\n }\n\n createBatch(): BatchBackend {\n const batchAdapter = createBatchAdapter(this.db, this.collectionPath);\n return new FirestoreBatchBackend(batchAdapter, this.db);\n }\n\n // --- Subgraphs ---\n\n subgraph(parentNodeUid: string, name: string): StorageBackend {\n const subPath = `${this.collectionPath}/${parentNodeUid}/${name}`;\n const newScope = this.scopePath ? `${this.scopePath}/${name}` : name;\n return new FirestoreBackendImpl(this.db, subPath, this.queryMode, newScope);\n }\n\n // --- Cascade & bulk ---\n\n removeNodeCascade(\n uid: string,\n reader: GraphReader,\n options?: BulkOptions,\n ): Promise<CascadeResult> {\n return removeNodeCascadeImpl(this.db, this.collectionPath, reader, uid, options);\n }\n\n bulkRemoveEdges(\n params: FindEdgesParams,\n reader: GraphReader,\n options?: BulkOptions,\n ): Promise<BulkResult> {\n return bulkRemoveEdgesImpl(this.db, this.collectionPath, reader, params, options);\n }\n\n // --- Cross-collection ---\n\n async findEdgesGlobal(\n params: FindEdgesParams,\n collectionName?: string,\n ): Promise<StoredGraphRecord[]> {\n const name = collectionName ?? this.collectionPath.split('/').pop()!;\n const plan = buildEdgeQueryPlan(params);\n\n if (plan.strategy === 'get') {\n throw new FiregraphError(\n 'findEdgesGlobal() requires a query, not a direct document lookup. ' +\n 'Omit one of aUid/axbType/bUid to force a query strategy.',\n 'INVALID_QUERY',\n );\n }\n\n const collectionGroupRef = this.db.collectionGroup(name);\n let q: Query = collectionGroupRef;\n for (const f of plan.filters) {\n q = q.where(f.field, f.op, f.value);\n }\n if (plan.options?.orderBy) {\n q = q.orderBy(plan.options.orderBy.field, plan.options.orderBy.direction ?? 'asc');\n }\n if (plan.options?.limit !== undefined) {\n q = q.limit(plan.options.limit);\n }\n const snap = await q.get();\n return snap.docs.map((doc) => doc.data() as StoredGraphRecord);\n }\n}\n\n/**\n * Create a Firestore-backed `StorageBackend`.\n *\n * The query-mode auto-fallback for the emulator (`FIRESTORE_EMULATOR_HOST`)\n * is performed at the call site (`createGraphClient`) so that the backend\n * itself doesn't reach into `process.env`.\n */\nexport function createFirestoreBackend(\n db: Firestore,\n collectionPath: string,\n options: FirestoreBackendOptions = {},\n): StorageBackend {\n const queryMode = options.queryMode ?? 'pipeline';\n const scopePath = options.scopePath ?? '';\n return new FirestoreBackendImpl(db, collectionPath, queryMode, scopePath);\n}\n","import type { Firestore } from '@google-cloud/firestore';\n\nimport { computeEdgeDocId, computeNodeDocId } from './docid.js';\nimport { NODE_RELATION } from './internal/constants.js';\nimport type {\n BulkBatchError,\n BulkOptions,\n BulkResult,\n CascadeResult,\n FindEdgesParams,\n GraphReader,\n StoredGraphRecord,\n} from './types.js';\n\nconst MAX_BATCH_SIZE = 500;\nconst DEFAULT_MAX_RETRIES = 3;\nconst BASE_DELAY_MS = 200;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Splits an array into chunks of at most `size` elements.\n */\nfunction chunk<T>(arr: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < arr.length; i += size) {\n chunks.push(arr.slice(i, i + size));\n }\n return chunks;\n}\n\n/**\n * Deletes a list of document IDs in chunked Firestore batches with retries.\n */\nexport async function bulkDeleteDocIds(\n db: Firestore,\n collectionPath: string,\n docIds: string[],\n options?: BulkOptions,\n): Promise<BulkResult> {\n if (docIds.length === 0) {\n return { deleted: 0, batches: 0, errors: [] };\n }\n\n const batchSize = Math.min(options?.batchSize ?? MAX_BATCH_SIZE, MAX_BATCH_SIZE);\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const onProgress = options?.onProgress;\n\n const chunks = chunk(docIds, batchSize);\n const errors: BulkBatchError[] = [];\n let deleted = 0;\n let completedBatches = 0;\n\n for (let i = 0; i < chunks.length; i++) {\n const ids = chunks[i];\n let committed = false;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const batch = db.batch();\n const collectionRef = db.collection(collectionPath);\n for (const id of ids) {\n batch.delete(collectionRef.doc(id));\n }\n await batch.commit();\n committed = true;\n deleted += ids.length;\n break;\n } catch (err) {\n if (attempt < maxRetries) {\n const delay = BASE_DELAY_MS * Math.pow(2, attempt);\n await sleep(delay);\n } else {\n errors.push({\n batchIndex: i,\n error: err instanceof Error ? err : new Error(String(err)),\n operationCount: ids.length,\n });\n }\n }\n }\n\n if (committed) {\n completedBatches++;\n }\n\n if (onProgress) {\n onProgress({\n completedBatches,\n totalBatches: chunks.length,\n deletedSoFar: deleted,\n });\n }\n }\n\n return { deleted, batches: completedBatches, errors };\n}\n\n/**\n * Finds all edges matching `params`, then deletes them in chunked batches.\n */\nexport async function bulkRemoveEdges(\n db: Firestore,\n collectionPath: string,\n reader: GraphReader,\n params: FindEdgesParams,\n options?: BulkOptions,\n): Promise<BulkResult> {\n // Override default query limit for bulk deletion — we need all matching edges.\n // limit: 0 bypasses DEFAULT_QUERY_LIMIT; an explicit user limit is preserved.\n // allowCollectionScan: true — bulk deletion inherently implies scanning.\n const effectiveParams =\n params.limit !== undefined\n ? { ...params, allowCollectionScan: params.allowCollectionScan ?? true }\n : { ...params, limit: 0, allowCollectionScan: params.allowCollectionScan ?? true };\n const edges = await reader.findEdges(effectiveParams);\n const docIds = edges.map((e) => computeEdgeDocId(e.aUid, e.axbType, e.bUid));\n return bulkDeleteDocIds(db, collectionPath, docIds, options);\n}\n\n/** Result from recursive subcollection deletion. */\ninterface SubcollectionDeleteResult {\n deleted: number;\n errors: BulkBatchError[];\n}\n\n/**\n * Recursively delete all documents in all subcollections under a given document.\n * Uses `listCollections()` (Admin SDK) to discover subcollections, then for each\n * subcollection: recurse into each document's subcollections first (depth-first),\n * then bulk delete all documents in the subcollection.\n *\n * The `onProgress` callback is intentionally NOT forwarded to subcollection\n * deletes to avoid confusing callers with interleaved progress from different\n * collection depths.\n */\nasync function deleteSubcollectionsRecursive(\n db: Firestore,\n collectionPath: string,\n docId: string,\n options?: BulkOptions,\n): Promise<SubcollectionDeleteResult> {\n const docRef = db.collection(collectionPath).doc(docId);\n const subcollections = await docRef.listCollections();\n\n if (subcollections.length === 0) return { deleted: 0, errors: [] };\n\n let totalDeleted = 0;\n const allErrors: BulkBatchError[] = [];\n\n // Strip onProgress for subcollection deletes — callers should only see\n // top-level progress, not interleaved reports from nested depths.\n const subOptions: BulkOptions | undefined = options\n ? { batchSize: options.batchSize, maxRetries: options.maxRetries }\n : undefined;\n\n for (const subCollRef of subcollections) {\n const subCollPath = subCollRef.path;\n // List all documents in this subcollection\n const snapshot = await subCollRef.select().get();\n const subDocIds = snapshot.docs.map((d) => d.id);\n\n // Depth-first: recurse into each document's subcollections\n for (const subDocId of subDocIds) {\n const subResult = await deleteSubcollectionsRecursive(db, subCollPath, subDocId, subOptions);\n totalDeleted += subResult.deleted;\n allErrors.push(...subResult.errors);\n }\n\n // Now delete all documents in this subcollection\n if (subDocIds.length > 0) {\n const result = await bulkDeleteDocIds(db, subCollPath, subDocIds, subOptions);\n totalDeleted += result.deleted;\n allErrors.push(...result.errors);\n }\n }\n\n return { deleted: totalDeleted, errors: allErrors };\n}\n\n/**\n * Deletes a node and all of its outgoing and incoming edges.\n *\n * Edges are deleted first in chunked batches, then the node document\n * is deleted in the final batch. This is NOT atomic across batches —\n * if a batch fails after retries, remaining batches still execute.\n *\n * By default, subcollections (subgraphs) under the node's document are\n * recursively deleted. Set `options.deleteSubcollections` to `false` to skip.\n */\nexport async function removeNodeCascade(\n db: Firestore,\n collectionPath: string,\n reader: GraphReader,\n uid: string,\n options?: BulkOptions,\n): Promise<CascadeResult> {\n // Find all edges touching this node (outgoing + incoming).\n // Filter out the node's own self-loop record (axbType === 'is').\n // These queries intentionally scan broadly — allowCollectionScan bypasses safety checks.\n // limit: 0 bypasses the DEFAULT_QUERY_LIMIT to ensure we find all edges.\n const [outgoingRaw, incomingRaw] = await Promise.all([\n reader.findEdges({ aUid: uid, allowCollectionScan: true, limit: 0 }),\n reader.findEdges({ bUid: uid, allowCollectionScan: true, limit: 0 }),\n ]);\n const outgoing = outgoingRaw.filter((e) => e.axbType !== NODE_RELATION);\n const incoming = incomingRaw.filter((e) => e.axbType !== NODE_RELATION);\n\n // Deduplicate: a self-referencing edge could appear in both lists.\n const edgeDocIdSet = new Set<string>();\n const allEdges: StoredGraphRecord[] = [];\n for (const edge of [...outgoing, ...incoming]) {\n const docId = computeEdgeDocId(edge.aUid, edge.axbType, edge.bUid);\n if (!edgeDocIdSet.has(docId)) {\n edgeDocIdSet.add(docId);\n allEdges.push(edge);\n }\n }\n\n // Delete subcollections (subgraphs) under this node's document (depth-first).\n const shouldDeleteSubcollections = options?.deleteSubcollections !== false;\n const nodeDocId = computeNodeDocId(uid);\n let subcollectionResult: SubcollectionDeleteResult = { deleted: 0, errors: [] };\n\n if (shouldDeleteSubcollections) {\n subcollectionResult = await deleteSubcollectionsRecursive(\n db,\n collectionPath,\n nodeDocId,\n options,\n );\n }\n\n // Build doc IDs: edges first, then the node last.\n const edgeDocIds = allEdges.map((e) => computeEdgeDocId(e.aUid, e.axbType, e.bUid));\n const allDocIds = [...edgeDocIds, nodeDocId];\n\n // Wrap the progress callback to track overall progress.\n const batchSize = Math.min(options?.batchSize ?? MAX_BATCH_SIZE, MAX_BATCH_SIZE);\n const result = await bulkDeleteDocIds(db, collectionPath, allDocIds, {\n ...options,\n batchSize,\n });\n\n // Determine if the node doc was in a failed batch.\n // The node is always in the last doc ID. If the last batch errored, node wasn't deleted.\n const totalChunks = Math.ceil(allDocIds.length / batchSize);\n const nodeChunkIndex = totalChunks - 1;\n const nodeDeleted = !result.errors.some((e) => e.batchIndex === nodeChunkIndex);\n\n // edgesDeleted counts only top-level edges (not subcollection docs).\n // deleted includes everything: top-level edges + node + subcollection docs.\n const topLevelEdgesDeleted = nodeDeleted ? result.deleted - 1 : result.deleted;\n\n return {\n deleted: result.deleted + subcollectionResult.deleted,\n batches: result.batches,\n errors: [...result.errors, ...subcollectionResult.errors],\n edgesDeleted: topLevelEdgesDeleted,\n nodeDeleted,\n };\n}\n","import type { Firestore, Query, Transaction } from '@google-cloud/firestore';\n\nimport type { QueryFilter, QueryOptions, StoredGraphRecord } from '../types.js';\n\nexport interface FirestoreAdapter {\n collectionPath: string;\n getDoc(docId: string): Promise<StoredGraphRecord | null>;\n setDoc(docId: string, data: Record<string, unknown>): Promise<void>;\n updateDoc(docId: string, data: Record<string, unknown>): Promise<void>;\n deleteDoc(docId: string): Promise<void>;\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]>;\n}\n\nexport function createFirestoreAdapter(db: Firestore, collectionPath: string): FirestoreAdapter {\n const collectionRef = db.collection(collectionPath);\n\n return {\n collectionPath,\n\n async getDoc(docId: string): Promise<StoredGraphRecord | null> {\n const snap = await collectionRef.doc(docId).get();\n if (!snap.exists) return null;\n return snap.data() as StoredGraphRecord;\n },\n\n async setDoc(docId: string, data: Record<string, unknown>): Promise<void> {\n await collectionRef.doc(docId).set(data);\n },\n\n async updateDoc(docId: string, data: Record<string, unknown>): Promise<void> {\n await collectionRef.doc(docId).update(data);\n },\n\n async deleteDoc(docId: string): Promise<void> {\n await collectionRef.doc(docId).delete();\n },\n\n async query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n let q: Query = collectionRef;\n for (const f of filters) {\n q = q.where(f.field, f.op, f.value);\n }\n if (options?.orderBy) {\n q = q.orderBy(options.orderBy.field, options.orderBy.direction ?? 'asc');\n }\n if (options?.limit !== undefined) {\n q = q.limit(options.limit);\n }\n const snap = await q.get();\n return snap.docs.map((doc) => doc.data() as StoredGraphRecord);\n },\n };\n}\n\nexport interface TransactionAdapter {\n getDoc(docId: string): Promise<StoredGraphRecord | null>;\n setDoc(docId: string, data: Record<string, unknown>): void;\n updateDoc(docId: string, data: Record<string, unknown>): void;\n deleteDoc(docId: string): void;\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]>;\n}\n\nexport function createTransactionAdapter(\n db: Firestore,\n collectionPath: string,\n tx: Transaction,\n): TransactionAdapter {\n const collectionRef = db.collection(collectionPath);\n\n return {\n async getDoc(docId: string): Promise<StoredGraphRecord | null> {\n const snap = await tx.get(collectionRef.doc(docId));\n if (!snap.exists) return null;\n return snap.data() as StoredGraphRecord;\n },\n\n setDoc(docId: string, data: Record<string, unknown>): void {\n tx.set(collectionRef.doc(docId), data);\n },\n\n updateDoc(docId: string, data: Record<string, unknown>): void {\n tx.update(collectionRef.doc(docId), data);\n },\n\n deleteDoc(docId: string): void {\n tx.delete(collectionRef.doc(docId));\n },\n\n async query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n let q: Query = collectionRef;\n for (const f of filters) {\n q = q.where(f.field, f.op, f.value);\n }\n if (options?.orderBy) {\n q = q.orderBy(options.orderBy.field, options.orderBy.direction ?? 'asc');\n }\n if (options?.limit !== undefined) {\n q = q.limit(options.limit);\n }\n const snap = await tx.get(q);\n return snap.docs.map((doc) => doc.data() as StoredGraphRecord);\n },\n };\n}\n\nexport interface BatchAdapter {\n setDoc(docId: string, data: Record<string, unknown>): void;\n updateDoc(docId: string, data: Record<string, unknown>): void;\n deleteDoc(docId: string): void;\n commit(): Promise<void>;\n}\n\nexport function createBatchAdapter(db: Firestore, collectionPath: string): BatchAdapter {\n const collectionRef = db.collection(collectionPath);\n const batch = db.batch();\n\n return {\n setDoc(docId: string, data: Record<string, unknown>): void {\n batch.set(collectionRef.doc(docId), data);\n },\n\n updateDoc(docId: string, data: Record<string, unknown>): void {\n batch.update(collectionRef.doc(docId), data);\n },\n\n deleteDoc(docId: string): void {\n batch.delete(collectionRef.doc(docId));\n },\n\n async commit(): Promise<void> {\n await batch.commit();\n },\n };\n}\n","/**\n * Pipeline query adapter — translates QueryFilter[] to Firestore Pipeline\n * expressions and executes them via db.pipeline().\n *\n * Only handles query() — doc-level operations (get/set/update/delete) stay\n * on the standard FirestoreAdapter.\n */\nimport type { Firestore, Pipelines } from '@google-cloud/firestore';\n\nimport type { QueryFilter, QueryOptions, StoredGraphRecord } from '../types.js';\n\n/**\n * Minimal interface for the Pipeline query adapter.\n * Only implements the query path — doc operations are handled by FirestoreAdapter.\n */\nexport interface PipelineQueryAdapter {\n query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]>;\n}\n\n/**\n * Lazily loaded Pipelines module. We use dynamic import so that standard-mode\n * users (and the emulator) don't pull in pipeline-related code at module load.\n */\nlet _Pipelines: typeof Pipelines | null = null;\n\nasync function getPipelines(): Promise<typeof Pipelines> {\n if (!_Pipelines) {\n const mod = await import('@google-cloud/firestore');\n _Pipelines = mod.Pipelines;\n }\n return _Pipelines;\n}\n\ntype PipelinesType = typeof Pipelines;\ntype BooleanExpr = Pipelines.BooleanExpression;\n\n/**\n * Maps a QueryFilter to a Pipeline BooleanExpression.\n *\n * Uses the string-based overloads (e.g. `equal(fieldName, value)`) which\n * accept `unknown` values, avoiding type issues with `constant()` overloads.\n */\nfunction buildFilterExpression(P: PipelinesType, filter: QueryFilter): BooleanExpr {\n const { field: fieldName, op, value } = filter;\n\n switch (op) {\n case '==':\n return P.equal(fieldName, value);\n case '!=':\n return P.notEqual(fieldName, value);\n case '<':\n return P.lessThan(fieldName, value);\n case '<=':\n return P.lessThanOrEqual(fieldName, value);\n case '>':\n return P.greaterThan(fieldName, value);\n case '>=':\n return P.greaterThanOrEqual(fieldName, value);\n case 'in':\n return P.equalAny(fieldName, value as Array<unknown>);\n case 'not-in':\n return P.notEqualAny(fieldName, value as Array<unknown>);\n case 'array-contains':\n return P.arrayContains(fieldName, value);\n case 'array-contains-any':\n return P.arrayContainsAny(fieldName, value as Array<unknown>);\n default:\n throw new Error(`Unsupported filter op for pipeline mode: ${op}`);\n }\n}\n\nexport function createPipelineQueryAdapter(\n db: Firestore,\n collectionPath: string,\n): PipelineQueryAdapter {\n return {\n async query(filters: QueryFilter[], options?: QueryOptions): Promise<StoredGraphRecord[]> {\n const P = await getPipelines();\n\n // Build pipeline\n let pipeline = db.pipeline().collection(collectionPath);\n\n // Apply filters\n if (filters.length === 1) {\n pipeline = pipeline.where(buildFilterExpression(P, filters[0]));\n } else if (filters.length > 1) {\n const [first, second, ...rest] = filters.map((f) => buildFilterExpression(P, f));\n pipeline = pipeline.where(P.and(first, second, ...rest));\n }\n\n // Apply sort\n if (options?.orderBy) {\n const f = P.field(options.orderBy.field);\n const ordering = options.orderBy.direction === 'desc' ? f.descending() : f.ascending();\n pipeline = pipeline.sort(ordering);\n }\n\n // Apply limit\n if (options?.limit !== undefined) {\n pipeline = pipeline.limit(options.limit);\n }\n\n const snap = await pipeline.execute();\n return snap.results.map((r) => r.data() as StoredGraphRecord);\n },\n };\n}\n","/**\n * Firestore-specific client factory.\n *\n * Kept in its own module so that bundlers don't pull\n * `@google-cloud/firestore` into non-Firestore entry points — most\n * importantly the Cloudflare DO backend (`firegraph/cloudflare`) and the\n * routing primitive (`firegraph/backend`), both of which must load cleanly\n * in a Workers environment where the Node Firestore SDK is unavailable.\n */\n\nimport type { Firestore } from '@google-cloud/firestore';\n\nimport { GraphClientImpl } from './client.js';\nimport type { StorageBackend } from './internal/backend.js';\nimport { createFirestoreBackend } from './internal/firestore-backend.js';\nimport type {\n DynamicGraphClient,\n DynamicRegistryConfig,\n GraphClient,\n GraphClientOptions,\n QueryMode,\n} from './types.js';\n\nlet _standardModeWarned = false;\n\nexport function createGraphClient(\n db: Firestore,\n collectionPath: string,\n options: GraphClientOptions & { registryMode: DynamicRegistryConfig },\n): DynamicGraphClient;\nexport function createGraphClient(\n db: Firestore,\n collectionPath: string,\n options?: GraphClientOptions,\n): GraphClient;\nexport function createGraphClient(\n db: Firestore,\n collectionPath: string,\n options?: GraphClientOptions,\n): GraphClient | DynamicGraphClient {\n const requestedMode = options?.queryMode ?? 'pipeline';\n const isEmulator = !!process.env.FIRESTORE_EMULATOR_HOST;\n const effectiveMode: QueryMode = isEmulator ? 'standard' : requestedMode;\n\n if (\n effectiveMode === 'standard' &&\n !isEmulator &&\n requestedMode === 'standard' &&\n !_standardModeWarned\n ) {\n _standardModeWarned = true;\n console.warn(\n '[firegraph] Standard query mode enabled. This is NOT recommended for production:\\n' +\n ' - Enterprise Firestore: data.* filters cause full collection scans (high billing)\\n' +\n ' - Standard Firestore: data.* filters without composite indexes will fail\\n' +\n ' See: https://github.com/typicalday/firegraph#query-modes',\n );\n }\n\n const backend = createFirestoreBackend(db, collectionPath, { queryMode: effectiveMode });\n\n let metaBackend: StorageBackend | undefined;\n if (options?.registryMode?.collection && options.registryMode.collection !== collectionPath) {\n metaBackend = createFirestoreBackend(db, options.registryMode.collection, {\n queryMode: effectiveMode,\n });\n }\n\n return new GraphClientImpl(backend, options, metaBackend) as GraphClient | DynamicGraphClient;\n}\n","import { nanoid } from 'nanoid';\n\nexport function generateId(): string {\n return nanoid();\n}\n","import type { DiscoveryResult, RegistryEntry } from './types.js';\n\nexport interface FirestoreIndexField {\n fieldPath: string;\n order: 'ASCENDING' | 'DESCENDING';\n}\n\nexport interface FirestoreIndex {\n collectionGroup: string;\n queryScope: 'COLLECTION' | 'COLLECTION_GROUP';\n fields: FirestoreIndexField[];\n}\n\nexport interface FirestoreIndexConfig {\n indexes: FirestoreIndex[];\n fieldOverrides: unknown[];\n}\n\n/**\n * Base composite indexes required for all firegraph collections.\n * These cover the standard query patterns:\n * - Forward edge lookup: (aUid, axbType)\n * - Reverse edge lookup: (axbType, bUid)\n * - Type-scoped queries: (aType, axbType) — also covers findNodes\n * - Edge type + target: (axbType, bType)\n */\nfunction baseIndexes(collection: string): FirestoreIndex[] {\n return [\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aUid', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bUid', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aType', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bType', order: 'ASCENDING' },\n ],\n },\n ];\n}\n\n/**\n * Extracts top-level field names from a JSON Schema object.\n * Only returns fields from schemas with type: \"object\" and properties.\n */\nfunction extractSchemaFields(schema: object): string[] {\n const s = schema as Record<string, unknown>;\n if (s.type !== 'object' || !s.properties) return [];\n return Object.keys(s.properties as Record<string, unknown>);\n}\n\n/**\n * Collection group indexes for `findEdgesGlobal()` queries.\n *\n * These mirror the base collection indexes but with `COLLECTION_GROUP` scope,\n * which allows querying across all subcollections with the given name.\n * Only generated when the registry has edge types with `targetGraph` set,\n * indicating cross-graph edges exist and global queries are likely.\n */\nfunction collectionGroupIndexes(collectionName: string): FirestoreIndex[] {\n return [\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'aUid', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bUid', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'aType', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n ],\n },\n {\n collectionGroup: collectionName,\n queryScope: 'COLLECTION_GROUP',\n fields: [\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: 'bType', order: 'ASCENDING' },\n ],\n },\n ];\n}\n\n/**\n * Generates a Firestore index configuration for a firegraph collection.\n *\n * Always includes the 4 base composite indexes. If an entity discovery result\n * is provided, generates additional data-field indexes for common query\n * patterns on node data fields:\n * (aType, axbType, data.{field})\n *\n * When registry entries with `targetGraph` are provided, also generates\n * collection group indexes for `findEdgesGlobal()` queries. The collection\n * group name defaults to `'graph'` (the standard subgraph name) but can be\n * overridden per `targetGraph` value.\n *\n * @param collection - Firestore collection name (e.g. 'graph')\n * @param entities - Optional discovery result for per-entity data field indexes\n * @param registryEntries - Optional registry entries; when any have `targetGraph`,\n * collection group indexes are generated for the distinct subgraph names\n */\nexport function generateIndexConfig(\n collection: string,\n entities?: DiscoveryResult,\n registryEntries?: ReadonlyArray<RegistryEntry>,\n): FirestoreIndexConfig {\n const indexes = baseIndexes(collection);\n\n if (entities) {\n // Generate data-field indexes for node types.\n // Pattern: (aType, axbType, data.{field}) — covers findNodes with where clauses\n // and findEdges scoped by aType + axbType + data filter.\n for (const [, entity] of entities.nodes) {\n const fields = extractSchemaFields(entity.schema);\n for (const field of fields) {\n indexes.push({\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aType', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: `data.${field}`, order: 'ASCENDING' },\n ],\n });\n }\n }\n\n // Generate data-field indexes for edge types.\n // Pattern: (aUid, axbType, data.{field}) — covers forward edge lookups with data filters.\n for (const [, entity] of entities.edges) {\n const fields = extractSchemaFields(entity.schema);\n for (const field of fields) {\n indexes.push({\n collectionGroup: collection,\n queryScope: 'COLLECTION',\n fields: [\n { fieldPath: 'aUid', order: 'ASCENDING' },\n { fieldPath: 'axbType', order: 'ASCENDING' },\n { fieldPath: `data.${field}`, order: 'ASCENDING' },\n ],\n });\n }\n }\n }\n\n // Generate collection group indexes when cross-graph edges exist.\n // Each distinct targetGraph value gets its own set of collection group indexes.\n if (registryEntries) {\n const targetGraphNames = new Set<string>();\n for (const entry of registryEntries) {\n if (entry.targetGraph) {\n targetGraphNames.add(entry.targetGraph);\n }\n }\n for (const name of targetGraphNames) {\n indexes.push(...collectionGroupIndexes(name));\n }\n }\n\n return { indexes, fieldOverrides: [] };\n}\n","import { FieldValue } from '@google-cloud/firestore';\n\nimport { NODE_RELATION } from './internal/constants.js';\nimport type { GraphRecord } from './types.js';\n\nexport function buildNodeRecord(\n aType: string,\n uid: string,\n data: Record<string, unknown>,\n): GraphRecord {\n const now = FieldValue.serverTimestamp();\n return {\n aType,\n aUid: uid,\n axbType: NODE_RELATION,\n bType: aType,\n bUid: uid,\n data,\n createdAt: now,\n updatedAt: now,\n };\n}\n\nexport function buildEdgeRecord(\n aType: string,\n aUid: string,\n axbType: string,\n bType: string,\n bUid: string,\n data: Record<string, unknown>,\n): GraphRecord {\n const now = FieldValue.serverTimestamp();\n return {\n aType,\n aUid,\n axbType,\n bType,\n bUid,\n data,\n createdAt: now,\n updatedAt: now,\n };\n}\n","import { TraversalError } from './errors.js';\nimport type {\n FindEdgesParams,\n GraphClient,\n GraphReader,\n GraphRegistry,\n HopDefinition,\n HopResult,\n StoredGraphRecord,\n TraversalBuilder,\n TraversalOptions,\n TraversalResult,\n} from './types.js';\n\nconst DEFAULT_LIMIT = 10;\nconst DEFAULT_MAX_READS = 100;\nconst DEFAULT_CONCURRENCY = 5;\n\n/** One-time warning flag: emitted when cross-graph hop is silently skipped. */\nlet _crossGraphWarned = false;\n\n/** Type guard to check if a reader is a GraphClient (has subgraph method). */\nfunction isGraphClient(reader: GraphReader): reader is GraphClient {\n return 'subgraph' in reader && typeof (reader as GraphClient).subgraph === 'function';\n}\n\nclass Semaphore {\n private queue: Array<() => void> = [];\n private active = 0;\n\n constructor(private readonly slots: number) {}\n\n async acquire(): Promise<void> {\n if (this.active < this.slots) {\n this.active++;\n return;\n }\n return new Promise<void>((resolve) => {\n this.queue.push(resolve);\n });\n }\n\n release(): void {\n this.active--;\n const next = this.queue.shift();\n if (next) {\n this.active++;\n next();\n }\n }\n}\n\nclass TraversalBuilderImpl implements TraversalBuilder {\n private readonly hops: HopDefinition[] = [];\n\n constructor(\n private readonly reader: GraphReader,\n private readonly startUid: string,\n private readonly registry?: GraphRegistry,\n ) {}\n\n follow(axbType: string, options?: Omit<HopDefinition, 'axbType'>): TraversalBuilder {\n this.hops.push({ axbType, ...options });\n return this;\n }\n\n async run(options?: TraversalOptions): Promise<TraversalResult> {\n if (this.hops.length === 0) {\n throw new TraversalError('Traversal requires at least one follow() hop');\n }\n\n const maxReads = options?.maxReads ?? DEFAULT_MAX_READS;\n const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY;\n const returnIntermediates = options?.returnIntermediates ?? false;\n const semaphore = new Semaphore(concurrency);\n\n let totalReads = 0;\n let truncated = false;\n // Track (uid, reader) pairs to support context carry-forward across hops.\n // When a hop crosses into a subgraph, the resulting UIDs carry the subgraph\n // reader so subsequent hops without targetGraph stay in that subgraph.\n let sources: Array<{ uid: string; reader: GraphReader }> = [\n { uid: this.startUid, reader: this.reader },\n ];\n const hopResults: HopResult[] = [];\n\n for (let depth = 0; depth < this.hops.length; depth++) {\n const hop = this.hops[depth];\n\n if (sources.length === 0) {\n hopResults.push({\n axbType: hop.axbType,\n depth,\n edges: [],\n sourceCount: 0,\n truncated: false,\n });\n continue;\n }\n\n const hopEdges: Array<{ edge: StoredGraphRecord; reader: GraphReader }> = [];\n const sourceCount = sources.length;\n let hopTruncated = false;\n\n // Resolve targetGraph for this hop:\n // 1. Explicit on the hop definition takes precedence\n // 2. Otherwise check the registry for the axbType\n const resolvedTargetGraph = this.resolveTargetGraph(hop);\n const direction = hop.direction ?? 'forward';\n const isCrossGraph = direction === 'forward' && !!resolvedTargetGraph;\n\n const tasks = sources.map(({ uid, reader: sourceReader }) => async () => {\n if (totalReads >= maxReads) {\n hopTruncated = true;\n return;\n }\n\n await semaphore.acquire();\n try {\n if (totalReads >= maxReads) {\n hopTruncated = true;\n return;\n }\n\n totalReads++;\n\n const params: FindEdgesParams = { axbType: hop.axbType };\n\n if (direction === 'forward') {\n params.aUid = uid;\n if (hop.bType) params.bType = hop.bType;\n } else {\n params.bUid = uid;\n if (hop.aType) params.aType = hop.aType;\n }\n\n if (direction === 'forward' && hop.aType) {\n params.aType = hop.aType;\n }\n if (direction === 'reverse' && hop.bType) {\n params.bType = hop.bType;\n }\n\n if (hop.orderBy) params.orderBy = hop.orderBy;\n\n const limit = hop.limit ?? DEFAULT_LIMIT;\n if (hop.filter) {\n params.limit = 0;\n } else {\n params.limit = limit;\n }\n\n // Choose the reader for this hop:\n // - Cross-graph hop: create a subgraph reader from the ROOT client\n // (targetGraph is always relative to root)\n // - No cross-graph: use the carried-forward reader from previous hop\n // (context tracking — stay in whatever subgraph we're already in)\n let hopReader: GraphReader;\n let nextReader: GraphReader;\n if (isCrossGraph) {\n if (isGraphClient(this.reader)) {\n hopReader = this.reader.subgraph(uid, resolvedTargetGraph!);\n nextReader = hopReader;\n } else {\n hopReader = sourceReader;\n nextReader = sourceReader;\n if (!_crossGraphWarned) {\n _crossGraphWarned = true;\n console.warn(\n `[firegraph] Traversal hop \"${hop.axbType}\" has targetGraph \"${resolvedTargetGraph}\" ` +\n 'but the reader does not support subgraph(). Cross-graph hop will query the current ' +\n 'collection instead. Pass a GraphClient to createTraversal() to enable cross-graph traversal.',\n );\n }\n }\n } else {\n // No targetGraph — carry forward context from previous hop\n hopReader = sourceReader;\n nextReader = sourceReader;\n }\n\n let edges = await hopReader.findEdges(params);\n\n if (hop.filter) {\n edges = edges.filter(hop.filter);\n edges = edges.slice(0, limit);\n }\n\n for (const edge of edges) {\n hopEdges.push({ edge, reader: nextReader });\n }\n } finally {\n semaphore.release();\n }\n });\n\n await Promise.all(tasks.map((task) => task()));\n\n const edges = hopEdges.map((h) => h.edge);\n\n hopResults.push({\n axbType: hop.axbType,\n depth,\n edges: returnIntermediates ? [...edges] : edges,\n sourceCount,\n truncated: hopTruncated,\n });\n\n if (hopTruncated) {\n truncated = true;\n }\n\n // Build next sources with deduplication by UID.\n // When the same UID appears from multiple source readers, the first one wins.\n const seen = new Map<string, GraphReader>();\n for (const { edge, reader: edgeReader } of hopEdges) {\n const nextUid = direction === 'forward' ? edge.bUid : edge.aUid;\n if (!seen.has(nextUid)) {\n seen.set(nextUid, edgeReader);\n }\n }\n sources = [...seen.entries()].map(([uid, reader]) => ({ uid, reader }));\n }\n\n const lastHop = hopResults[hopResults.length - 1];\n\n return {\n nodes: lastHop.edges,\n hops: hopResults,\n totalReads,\n truncated,\n };\n }\n\n /**\n * Resolve the targetGraph for a hop. Priority:\n * 1. Explicit `hop.targetGraph` (user override)\n * 2. Registry `targetGraph` for the axbType (if registry available)\n * 3. undefined (no cross-graph)\n */\n private resolveTargetGraph(hop: HopDefinition): string | undefined {\n if (hop.targetGraph) return hop.targetGraph;\n\n if (this.registry) {\n const entries = this.registry.lookupByAxbType(hop.axbType);\n // All entries for the same axbType should share targetGraph; use the first non-undefined\n for (const entry of entries) {\n if (entry.targetGraph) return entry.targetGraph;\n }\n }\n\n return undefined;\n }\n}\n\n/** @internal Reset the one-time cross-graph warning flag (for testing). */\nexport function _resetCrossGraphWarning(): void {\n _crossGraphWarned = false;\n}\n\n/**\n * Create a traversal builder for multi-hop graph traversal.\n *\n * Accepts either a `GraphReader` (backwards compatible) or a `GraphClient`.\n * When a `GraphClient` is provided, cross-graph traversal via `targetGraph`\n * is supported — the traversal can follow edges into subgraphs.\n *\n * @param reader - A `GraphClient` or `GraphReader` to execute queries against\n * @param startUid - UID of the starting node\n * @param registry - Optional registry for automatic `targetGraph` resolution\n */\nexport function createTraversal(\n reader: GraphClient | GraphReader,\n startUid: string,\n registry?: GraphRegistry,\n): TraversalBuilder {\n return new TraversalBuilderImpl(reader, startUid, registry);\n}\n","/**\n * Model Views — framework-agnostic view definitions for graph entities.\n *\n * Projects define Web Components that render entity data in purpose-driven\n * ways. Each view class declares a static `viewName`, and receives the\n * entity's `data` payload via a `data` property setter.\n *\n * @example\n * ```ts\n * import { defineViews } from 'firegraph';\n *\n * class UserCard extends HTMLElement {\n * static viewName = 'card';\n * static description = 'Compact user card';\n * private _data: Record<string, unknown> = {};\n * set data(v: Record<string, unknown>) { this._data = v; this.render(); }\n * connectedCallback() { this.render(); }\n * private render() {\n * this.innerHTML = `<strong>${this._data.displayName ?? ''}</strong>`;\n * }\n * }\n *\n * export default defineViews({\n * nodes: { user: { views: [UserCard] } },\n * });\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A Web Component class used as a view. The class must have a static\n * `viewName` and must be constructable. It will be registered as a custom\n * element via `customElements.define()` in browser environments.\n *\n * Note: this interface avoids referencing `HTMLElement` directly so the\n * library can compile without DOM lib types. Consumer code (which has DOM)\n * will satisfy this constraint naturally.\n */\nexport interface ViewComponentClass {\n new (...args: any[]): { data: Record<string, unknown> };\n /** Short identifier for this view (e.g. 'card', 'profile'). */\n viewName: string;\n /** Optional human-readable description. */\n description?: string;\n}\n\n/** Configuration for all views of a single entity type. */\nexport interface EntityViewConfig {\n /** View component classes to register. */\n views: ViewComponentClass[];\n /**\n * Optional sample data for the gallery. A single object matching\n * the entity's JSON Schema — shared across all views.\n */\n sampleData?: Record<string, unknown>;\n}\n\n/** Input shape accepted by `defineViews()`. */\nexport interface ViewRegistryInput {\n /** Node views keyed by aType (e.g. 'user', 'tour'). */\n nodes?: Record<string, EntityViewConfig>;\n /** Edge views keyed by axbType (e.g. 'hasDeparture'). */\n edges?: Record<string, EntityViewConfig>;\n}\n\n/** Serialisable metadata for a single view. */\nexport interface ViewMeta {\n /** Custom element tag name (e.g. 'fg-user-card'). */\n tagName: string;\n /** Short identifier matching the component's static viewName. */\n viewName: string;\n /** Optional human-readable description. */\n description?: string;\n}\n\n/** Serialisable metadata for all views of a single entity type. */\nexport interface EntityViewMeta {\n views: ViewMeta[];\n sampleData?: Record<string, unknown>;\n}\n\n/** The resolved view registry returned by `defineViews()`. */\nexport interface ViewRegistry {\n nodes: Record<string, EntityViewMeta>;\n edges: Record<string, EntityViewMeta>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Sanitise a string for use as part of a custom element tag name. */\nfunction sanitizeTagPart(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n}\n\n/** Minimal interface for CustomElementRegistry (avoids depending on DOM lib). */\ninterface CustomElementRegistryLike {\n get(name: string): unknown;\n define(name: string, constructor: unknown): void;\n}\n\n/**\n * Try to access the browser's `customElements` registry.\n * Returns `null` in Node.js or environments without Web Components support.\n */\nfunction getCustomElements(): CustomElementRegistryLike | null {\n const g = globalThis as any;\n if (g.customElements && typeof g.customElements.define === 'function') {\n return g.customElements as CustomElementRegistryLike;\n }\n return null;\n}\n\n/**\n * Wrap a view class so that errors in connectedCallback, disconnectedCallback,\n * and the data setter are caught and logged rather than crashing the page.\n * Shows an inline error message when the view fails to render.\n */\nfunction resilientView(ViewClass: ViewComponentClass, tagName: string): ViewComponentClass {\n const g = globalThis as any;\n if (!g.HTMLElement) return ViewClass; // Node.js — no wrapping needed\n\n const Wrapped = class extends (ViewClass as unknown as new (...args: any[]) => any) {\n connectedCallback() {\n try {\n super.connectedCallback?.();\n } catch (err) {\n console.warn(`[firegraph] <${tagName}> connectedCallback error:`, err);\n this._showError(err);\n }\n }\n\n disconnectedCallback() {\n try {\n super.disconnectedCallback?.();\n } catch (err) {\n console.warn(`[firegraph] <${tagName}> disconnectedCallback error:`, err);\n }\n }\n\n set data(v: Record<string, unknown>) {\n try {\n super.data = v;\n } catch (err) {\n console.warn(`[firegraph] <${tagName}> data setter error:`, err);\n this._showError(err);\n }\n }\n\n get data(): Record<string, unknown> {\n try {\n return super.data;\n } catch {\n return {};\n }\n }\n\n _showError(err: unknown) {\n try {\n this.innerHTML =\n `<div style=\"padding:6px;color:#f87171;font-size:11px;font-family:monospace;\">` +\n `View error in &lt;${tagName}&gt;: ${err instanceof Error ? err.message : String(err)}</div>`;\n } catch {\n /* last resort — don't throw from error handler */\n }\n }\n };\n\n // Preserve static metadata\n (Wrapped as unknown as ViewComponentClass).viewName = ViewClass.viewName;\n (Wrapped as unknown as ViewComponentClass).description = ViewClass.description;\n\n return Wrapped as unknown as ViewComponentClass;\n}\n\n// ---------------------------------------------------------------------------\n// defineViews()\n// ---------------------------------------------------------------------------\n\n/**\n * Build a `ViewRegistry` from component classes.\n *\n * In the browser the components are registered as custom elements with\n * deterministic tag names (`fg-{entityType}-{viewName}`). On the server\n * (Node.js) only metadata is returned — no custom element registration.\n */\nexport function defineViews(input: ViewRegistryInput): ViewRegistry {\n const nodes: Record<string, EntityViewMeta> = {};\n const edges: Record<string, EntityViewMeta> = {};\n const registry = getCustomElements();\n\n // --- nodes ---\n for (const [entityType, config] of Object.entries(input.nodes ?? {})) {\n const viewMetas: ViewMeta[] = [];\n for (const ViewClass of config.views) {\n const tagName = `fg-${sanitizeTagPart(entityType)}-${sanitizeTagPart(ViewClass.viewName)}`;\n viewMetas.push({\n tagName,\n viewName: ViewClass.viewName,\n description: ViewClass.description,\n });\n if (registry && !registry.get(tagName)) {\n registry.define(tagName, resilientView(ViewClass, tagName));\n }\n }\n nodes[entityType] = {\n views: viewMetas,\n sampleData: config.sampleData,\n };\n }\n\n // --- edges ---\n for (const [axbType, config] of Object.entries(input.edges ?? {})) {\n const viewMetas: ViewMeta[] = [];\n for (const ViewClass of config.views) {\n const tagName = `fg-edge-${sanitizeTagPart(axbType)}-${sanitizeTagPart(ViewClass.viewName)}`;\n viewMetas.push({\n tagName,\n viewName: ViewClass.viewName,\n description: ViewClass.description,\n });\n if (registry && !registry.get(tagName)) {\n registry.define(tagName, resilientView(ViewClass, tagName));\n }\n }\n edges[axbType] = {\n views: viewMetas,\n sampleData: config.sampleData,\n };\n }\n\n return { nodes, edges };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqHO,SAAS,aAAa,QAA0C;AACrE,SAAO;AACT;AAeO,SAAS,YACd,gBACA,oBACA,SACQ;AACR,MAAI,CAAC,eAAgB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A,QACA,UAAU,UAAU;AAAA,QACpB,aAAa,UAAU;AAAA,MACzB,CAAC;AACD,UAAI,YAAY,CAAC,SAAS,IAAI,OAAO,GAAG;AACtC,iBAAS,OAAO,SAAS,cAAc,WAAW,OAAO,CAAC;AAAA,MAC5D;AAAA,IACF;AACA,UAAM,OAAO,IAAI;AAAA,MACf,OAAO;AAAA,MACP,YAAY,OAAO;AAAA,IACrB;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,MAAM;AACxB;","names":["resolve","FieldValue","FieldValue","resolve","edges"]}
@@ -42,6 +42,26 @@ module.exports = __toCommonJS(query_client_exports);
42
42
  // src/query-client/client.ts
43
43
  var import_node_http = __toESM(require("http"), 1);
44
44
 
45
+ // src/query-client/config.ts
46
+ var import_node_fs = require("fs");
47
+ var import_node_path = require("path");
48
+ var CONFIG_FILES = ["firegraph.config.ts", "firegraph.config.js", "firegraph.config.mjs"];
49
+ var DEFAULT_PORT = 3884;
50
+ function readEditorPort(cwd) {
51
+ const dir = cwd ?? process.cwd();
52
+ for (const name of CONFIG_FILES) {
53
+ try {
54
+ const content = (0, import_node_fs.readFileSync)((0, import_node_path.join)(dir, name), "utf8");
55
+ const editorBlock = content.match(/editor\s*:\s*\{[^}]*\}/s)?.[0] ?? "";
56
+ const portMatch = editorBlock.match(/port\s*:\s*(\d+)/);
57
+ if (portMatch) return parseInt(portMatch[1], 10);
58
+ } catch {
59
+ continue;
60
+ }
61
+ }
62
+ return DEFAULT_PORT;
63
+ }
64
+
45
65
  // src/query-client/shaping.ts
46
66
  function summarizeRecord(r) {
47
67
  if (!r) return null;
@@ -68,26 +88,6 @@ function summarizeEdge(r) {
68
88
  return out;
69
89
  }
70
90
 
71
- // src/query-client/config.ts
72
- var import_node_fs = require("fs");
73
- var import_node_path = require("path");
74
- var CONFIG_FILES = ["firegraph.config.ts", "firegraph.config.js", "firegraph.config.mjs"];
75
- var DEFAULT_PORT = 3884;
76
- function readEditorPort(cwd) {
77
- const dir = cwd ?? process.cwd();
78
- for (const name of CONFIG_FILES) {
79
- try {
80
- const content = (0, import_node_fs.readFileSync)((0, import_node_path.join)(dir, name), "utf8");
81
- const editorBlock = content.match(/editor\s*:\s*\{[^}]*\}/s)?.[0] ?? "";
82
- const portMatch = editorBlock.match(/port\s*:\s*(\d+)/);
83
- if (portMatch) return parseInt(portMatch[1], 10);
84
- } catch {
85
- continue;
86
- }
87
- }
88
- return DEFAULT_PORT;
89
- }
90
-
91
91
  // src/query-client/client.ts
92
92
  var QueryClientError = class extends Error {
93
93
  constructor(message, code) {
@@ -286,14 +286,16 @@ var QueryClient = class {
286
286
  }
287
287
  const data = await this.mutate("traverse", input);
288
288
  return {
289
- hops: (data.hops ?? []).map((h) => ({
290
- relation: h.axbType,
291
- direction: h.direction,
292
- depth: h.depth,
293
- edgeCount: (h.edges ?? []).length,
294
- edges: (h.edges ?? []).map(summarizeEdge).filter(Boolean),
295
- truncated: h.truncated ?? false
296
- })),
289
+ hops: (data.hops ?? []).map(
290
+ (h) => ({
291
+ relation: h.axbType,
292
+ direction: h.direction,
293
+ depth: h.depth,
294
+ edgeCount: (h.edges ?? []).length,
295
+ edges: (h.edges ?? []).map(summarizeEdge).filter(Boolean),
296
+ truncated: h.truncated ?? false
297
+ })
298
+ ),
297
299
  totalReads: data.totalReads ?? 0,
298
300
  truncated: data.truncated ?? false
299
301
  };