@open-mercato/core 0.8.1-develop.7239.1.d90c352076 → 0.8.1-develop.7241.1.fad7b2ce2a

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 (26) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/helpers/integration/dbFixtures.js +4 -0
  3. package/dist/helpers/integration/dbFixtures.js.map +2 -2
  4. package/dist/modules/customers/index.js +1 -0
  5. package/dist/modules/customers/index.js.map +2 -2
  6. package/dist/modules/query_index/lib/coverage.js +84 -15
  7. package/dist/modules/query_index/lib/coverage.js.map +2 -2
  8. package/dist/modules/query_index/subscribers/delete_one.js.map +2 -2
  9. package/dist/modules/query_index/subscribers/upsert_one.js.map +2 -2
  10. package/dist/modules/sales/data/entities.js.map +2 -2
  11. package/dist/modules/sales/migrations/Migration20260825120000_sales_document_sequences_backing_sequences.js +49 -0
  12. package/dist/modules/sales/migrations/Migration20260825120000_sales_document_sequences_backing_sequences.js.map +7 -0
  13. package/dist/modules/sales/services/salesDocumentNumberGenerator.js +126 -24
  14. package/dist/modules/sales/services/salesDocumentNumberGenerator.js.map +2 -2
  15. package/dist/modules/sales/setup.js +16 -12
  16. package/dist/modules/sales/setup.js.map +2 -2
  17. package/package.json +7 -7
  18. package/src/helpers/integration/dbFixtures.ts +10 -0
  19. package/src/modules/customers/index.ts +1 -0
  20. package/src/modules/query_index/lib/coverage.ts +168 -16
  21. package/src/modules/query_index/subscribers/delete_one.ts +4 -0
  22. package/src/modules/query_index/subscribers/upsert_one.ts +4 -0
  23. package/src/modules/sales/data/entities.ts +8 -0
  24. package/src/modules/sales/migrations/Migration20260825120000_sales_document_sequences_backing_sequences.ts +61 -0
  25. package/src/modules/sales/services/salesDocumentNumberGenerator.ts +161 -24
  26. package/src/modules/sales/setup.ts +16 -4
@@ -1,4 +1,4 @@
1
- [build:core] found 5048 entry points
1
+ [build:core] found 5051 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 233 entry points
4
4
  [build:core:generated] built successfully
@@ -25,6 +25,9 @@ function resolveDatabaseUrl() {
25
25
  if (!url) throw new Error("[internal] DATABASE_URL is not configured for integration DB fixtures");
26
26
  return url;
27
27
  }
28
+ function resolveIntegrationDatabaseUrl() {
29
+ return resolveDatabaseUrl();
30
+ }
28
31
  async function withClient(run) {
29
32
  const client = new Client({ connectionString: resolveDatabaseUrl() });
30
33
  await client.connect();
@@ -97,6 +100,7 @@ export {
97
100
  deleteIntegrationCredentialsInDb,
98
101
  deleteOrganizationInDb,
99
102
  deleteUserAclInDb,
103
+ resolveIntegrationDatabaseUrl,
100
104
  setUserAclInDb,
101
105
  withClient
102
106
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/helpers/integration/dbFixtures.ts"],
4
- "sourcesContent": ["import { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { Client } from 'pg';\nimport { resolveAppRoot } from './appRoot';\n\n/**\n * Database fixtures for the org-scope fail-open hardening tests.\n *\n * These helpers talk to Postgres directly via `pg` rather than bootstrapping the\n * app DI container, because:\n * - the directory create command denies non-super-admin actors (the only\n * loginable accounts here), so orgs cannot be created over the API; and\n * - granting `customers.*` through the ACL API requires a super-admin actor.\n * Raw SQL keeps the test self-contained and avoids depending on built package\n * `dist/` output for an in-process MikroORM bootstrap.\n */\n\nfunction readEnvValue(key: string): string | undefined {\n if (process.env[key]) return process.env[key];\n const candidatePaths = [\n path.resolve(resolveAppRoot(), '.env'),\n path.resolve(process.cwd(), 'apps/mercato/.env'),\n path.resolve(process.cwd(), '.env'),\n ];\n for (const envPath of candidatePaths) {\n try {\n const content = readFileSync(envPath, 'utf-8');\n const match = content.match(new RegExp(`^${key}=(.+)$`, 'm'));\n if (match?.[1]) return match[1].trim();\n } catch {\n continue;\n }\n }\n return undefined;\n}\n\nfunction resolveDatabaseUrl(): string {\n const url = readEnvValue('DATABASE_URL');\n if (!url) throw new Error('[internal] DATABASE_URL is not configured for integration DB fixtures');\n return url;\n}\n\n/**\n * The slice of `pg`'s client these fixtures use, declared structurally.\n *\n * `pg` publishes `Client` as a class merged with a namespace, and the app project's module\n * resolution picks the namespace half in type position (`TS2709`), so naming the class here made\n * every caller outside `packages/core` fail to typecheck. A structural type is resolvable from\n * every project and keeps `query<T>()` generic, which `InstanceType<typeof Client>` did not.\n */\nexport type IntegrationDbClient = {\n query<T = Record<string, unknown>>(\n text: string,\n values?: readonly unknown[],\n ): Promise<{ rows: T[]; rowCount: number | null }>;\n};\n\nexport async function withClient<T>(run: (client: IntegrationDbClient) => Promise<T>): Promise<T> {\n const client = new Client({ connectionString: resolveDatabaseUrl() }) as unknown as IntegrationDbClient & {\n connect: () => Promise<void>;\n end: () => Promise<void>;\n };\n await client.connect();\n try {\n return await run(client);\n } finally {\n await client.end();\n }\n}\n\n/**\n * Nulls a user's home organization (`organization_id`) directly in the database.\n *\n * Required to construct the \"floating restricted user\" precondition: the JWT\n * `auth.orgId` is minted from `users.organization_id` at login, so this MUST run\n * BEFORE the user logs in.\n */\nexport async function clearUserHomeOrganization(userId: string): Promise<void> {\n await withClient(async (client) => {\n await client.query('update users set organization_id = null where id = $1', [userId]);\n });\n}\n\n/**\n * Upserts a per-user ACL row, setting the effective feature list and the\n * organization-visibility list.\n *\n * `organizations` maps to `OrganizationScope.allowedIds` (write path) and\n * `filterIds` (read path):\n * - `[orgA]` => restricted to orgA (write fail-open precondition, #2239)\n * - `[]` => restricted to zero orgs (read fail-open precondition, #2245)\n * - `null` => unrestricted\n */\nexport async function setUserAclInDb(input: {\n userId: string;\n tenantId: string;\n features: string[];\n organizations: string[] | null;\n}): Promise<void> {\n await withClient(async (client) => {\n const existing = await client.query<{ id: string }>(\n 'select id from user_acls where user_id = $1 and tenant_id = $2 limit 1',\n [input.userId, input.tenantId],\n );\n const featuresJson = JSON.stringify(input.features);\n const organizationsJson = input.organizations === null ? null : JSON.stringify(input.organizations);\n if (existing.rows.length > 0) {\n await client.query(\n 'update user_acls set features_json = $2::jsonb, organizations_json = $3::jsonb, is_super_admin = false, updated_at = now() where id = $1',\n [existing.rows[0].id, featuresJson, organizationsJson],\n );\n return;\n }\n await client.query(\n `insert into user_acls (id, user_id, tenant_id, features_json, organizations_json, is_super_admin, created_at)\n values (gen_random_uuid(), $1, $2, $3::jsonb, $4::jsonb, false, now())`,\n [input.userId, input.tenantId, featuresJson, organizationsJson],\n );\n });\n}\n\n/** Removes any per-user ACL rows for the user (best-effort test cleanup). */\nexport async function deleteUserAclInDb(userId: string): Promise<void> {\n if (!userId) return;\n await withClient(async (client) => {\n await client.query('delete from user_acls where user_id = $1', [userId]);\n });\n}\n\n/**\n * Creates an organization directly in the database within the given tenant.\n *\n * The directory create command routes through `enforceTenantSelection`, which\n * denies the (non-super-admin) accounts loginable on this instance. Landing the\n * org in a known tenant lets the floating user (created under it) share the\n * tenant \u2014 required because cross-tenant access returns 404 before the\n * org-scope guard ever runs.\n */\nexport async function createOrganizationInDb(input: { name: string; tenantId: string }): Promise<string> {\n return withClient(async (client) => {\n const result = await client.query<{ id: string }>(\n `insert into organizations\n (id, tenant_id, name, is_active, ancestor_ids, child_ids, descendant_ids, depth, created_at, updated_at)\n values (gen_random_uuid(), $1, $2, true, '[]'::jsonb, '[]'::jsonb, '[]'::jsonb, 0, now(), now())\n returning id`,\n [input.tenantId, input.name],\n );\n return result.rows[0].id;\n });\n}\n\n/** Hard-deletes an organization row (best-effort test cleanup). */\nexport async function deleteOrganizationInDb(organizationId: string | null): Promise<void> {\n if (!organizationId) return;\n await withClient(async (client) => {\n await client.query('delete from organizations where id = $1', [organizationId]);\n });\n}\n\n/**\n * Hard-deletes integration credential rows for an organization (best-effort test\n * cleanup). Integration credentials are stored per (integration_id,\n * organization_id, tenant_id, user_id) with no FK to organizations, so a\n * throwaway org's credential rows must be removed explicitly when the org row is\n * torn down.\n */\nexport async function deleteIntegrationCredentialsInDb(organizationId: string | null): Promise<void> {\n if (!organizationId) return;\n await withClient(async (client) => {\n await client.query('delete from integration_credentials where organization_id = $1', [organizationId]);\n });\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AACjB,SAAS,cAAc;AACvB,SAAS,sBAAsB;AAc/B,SAAS,aAAa,KAAiC;AACrD,MAAI,QAAQ,IAAI,GAAG,EAAG,QAAO,QAAQ,IAAI,GAAG;AAC5C,QAAM,iBAAiB;AAAA,IACrB,KAAK,QAAQ,eAAe,GAAG,MAAM;AAAA,IACrC,KAAK,QAAQ,QAAQ,IAAI,GAAG,mBAAmB;AAAA,IAC/C,KAAK,QAAQ,QAAQ,IAAI,GAAG,MAAM;AAAA,EACpC;AACA,aAAW,WAAW,gBAAgB;AACpC,QAAI;AACF,YAAM,UAAU,aAAa,SAAS,OAAO;AAC7C,YAAM,QAAQ,QAAQ,MAAM,IAAI,OAAO,IAAI,GAAG,UAAU,GAAG,CAAC;AAC5D,UAAI,QAAQ,CAAC,EAAG,QAAO,MAAM,CAAC,EAAE,KAAK;AAAA,IACvC,QAAQ;AACN;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,qBAA6B;AACpC,QAAM,MAAM,aAAa,cAAc;AACvC,MAAI,CAAC,IAAK,OAAM,IAAI,MAAM,uEAAuE;AACjG,SAAO;AACT;AAiBA,eAAsB,WAAc,KAA8D;AAChG,QAAM,SAAS,IAAI,OAAO,EAAE,kBAAkB,mBAAmB,EAAE,CAAC;AAIpE,QAAM,OAAO,QAAQ;AACrB,MAAI;AACF,WAAO,MAAM,IAAI,MAAM;AAAA,EACzB,UAAE;AACA,UAAM,OAAO,IAAI;AAAA,EACnB;AACF;AASA,eAAsB,0BAA0B,QAA+B;AAC7E,QAAM,WAAW,OAAO,WAAW;AACjC,UAAM,OAAO,MAAM,yDAAyD,CAAC,MAAM,CAAC;AAAA,EACtF,CAAC;AACH;AAYA,eAAsB,eAAe,OAKnB;AAChB,QAAM,WAAW,OAAO,WAAW;AACjC,UAAM,WAAW,MAAM,O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{ Client } from 'pg';\nimport { resolveAppRoot } from './appRoot';\n\n/**\n * Database fixtures for the org-scope fail-open hardening tests.\n *\n * These helpers talk to Postgres directly via `pg` rather than bootstrapping the\n * app DI container, because:\n * - the directory create command denies non-super-admin actors (the only\n * loginable accounts here), so orgs cannot be created over the API; and\n * - granting `customers.*` through the ACL API requires a super-admin actor.\n * Raw SQL keeps the test self-contained and avoids depending on built package\n * `dist/` output for an in-process MikroORM bootstrap.\n */\n\nfunction readEnvValue(key: string): string | undefined {\n if (process.env[key]) return process.env[key];\n const candidatePaths = [\n path.resolve(resolveAppRoot(), '.env'),\n path.resolve(process.cwd(), 'apps/mercato/.env'),\n path.resolve(process.cwd(), '.env'),\n ];\n for (const envPath of candidatePaths) {\n try {\n const content = readFileSync(envPath, 'utf-8');\n const match = content.match(new RegExp(`^${key}=(.+)$`, 'm'));\n if (match?.[1]) return match[1].trim();\n } catch {\n continue;\n }\n }\n return undefined;\n}\n\nfunction resolveDatabaseUrl(): string {\n const url = readEnvValue('DATABASE_URL');\n if (!url) throw new Error('[internal] DATABASE_URL is not configured for integration DB fixtures');\n return url;\n}\n\n/**\n * The same connection string `withClient` uses, for specs that need their own pool rather\n * than a single `pg` client \u2014 a spec driving server-side library code that expects a Kysely\n * instance, for example. Reuses the `.env` fallback so those specs resolve the database the\n * same way every other fixture here does.\n */\nexport function resolveIntegrationDatabaseUrl(): string {\n return resolveDatabaseUrl();\n}\n\n/**\n * The slice of `pg`'s client these fixtures use, declared structurally.\n *\n * `pg` publishes `Client` as a class merged with a namespace, and the app project's module\n * resolution picks the namespace half in type position (`TS2709`), so naming the class here made\n * every caller outside `packages/core` fail to typecheck. A structural type is resolvable from\n * every project and keeps `query<T>()` generic, which `InstanceType<typeof Client>` did not.\n */\nexport type IntegrationDbClient = {\n query<T = Record<string, unknown>>(\n text: string,\n values?: readonly unknown[],\n ): Promise<{ rows: T[]; rowCount: number | null }>;\n};\n\nexport async function withClient<T>(run: (client: IntegrationDbClient) => Promise<T>): Promise<T> {\n const client = new Client({ connectionString: resolveDatabaseUrl() }) as unknown as IntegrationDbClient & {\n connect: () => Promise<void>;\n end: () => Promise<void>;\n };\n await client.connect();\n try {\n return await run(client);\n } finally {\n await client.end();\n }\n}\n\n/**\n * Nulls a user's home organization (`organization_id`) directly in the database.\n *\n * Required to construct the \"floating restricted user\" precondition: the JWT\n * `auth.orgId` is minted from `users.organization_id` at login, so this MUST run\n * BEFORE the user logs in.\n */\nexport async function clearUserHomeOrganization(userId: string): Promise<void> {\n await withClient(async (client) => {\n await client.query('update users set organization_id = null where id = $1', [userId]);\n });\n}\n\n/**\n * Upserts a per-user ACL row, setting the effective feature list and the\n * organization-visibility list.\n *\n * `organizations` maps to `OrganizationScope.allowedIds` (write path) and\n * `filterIds` (read path):\n * - `[orgA]` => restricted to orgA (write fail-open precondition, #2239)\n * - `[]` => restricted to zero orgs (read fail-open precondition, #2245)\n * - `null` => unrestricted\n */\nexport async function setUserAclInDb(input: {\n userId: string;\n tenantId: string;\n features: string[];\n organizations: string[] | null;\n}): Promise<void> {\n await withClient(async (client) => {\n const existing = await client.query<{ id: string }>(\n 'select id from user_acls where user_id = $1 and tenant_id = $2 limit 1',\n [input.userId, input.tenantId],\n );\n const featuresJson = JSON.stringify(input.features);\n const organizationsJson = input.organizations === null ? null : JSON.stringify(input.organizations);\n if (existing.rows.length > 0) {\n await client.query(\n 'update user_acls set features_json = $2::jsonb, organizations_json = $3::jsonb, is_super_admin = false, updated_at = now() where id = $1',\n [existing.rows[0].id, featuresJson, organizationsJson],\n );\n return;\n }\n await client.query(\n `insert into user_acls (id, user_id, tenant_id, features_json, organizations_json, is_super_admin, created_at)\n values (gen_random_uuid(), $1, $2, $3::jsonb, $4::jsonb, false, now())`,\n [input.userId, input.tenantId, featuresJson, organizationsJson],\n );\n });\n}\n\n/** Removes any per-user ACL rows for the user (best-effort test cleanup). */\nexport async function deleteUserAclInDb(userId: string): Promise<void> {\n if (!userId) return;\n await withClient(async (client) => {\n await client.query('delete from user_acls where user_id = $1', [userId]);\n });\n}\n\n/**\n * Creates an organization directly in the database within the given tenant.\n *\n * The directory create command routes through `enforceTenantSelection`, which\n * denies the (non-super-admin) accounts loginable on this instance. Landing the\n * org in a known tenant lets the floating user (created under it) share the\n * tenant \u2014 required because cross-tenant access returns 404 before the\n * org-scope guard ever runs.\n */\nexport async function createOrganizationInDb(input: { name: string; tenantId: string }): Promise<string> {\n return withClient(async (client) => {\n const result = await client.query<{ id: string }>(\n `insert into organizations\n (id, tenant_id, name, is_active, ancestor_ids, child_ids, descendant_ids, depth, created_at, updated_at)\n values (gen_random_uuid(), $1, $2, true, '[]'::jsonb, '[]'::jsonb, '[]'::jsonb, 0, now(), now())\n returning id`,\n [input.tenantId, input.name],\n );\n return result.rows[0].id;\n });\n}\n\n/** Hard-deletes an organization row (best-effort test cleanup). */\nexport async function deleteOrganizationInDb(organizationId: string | null): Promise<void> {\n if (!organizationId) return;\n await withClient(async (client) => {\n await client.query('delete from organizations where id = $1', [organizationId]);\n });\n}\n\n/**\n * Hard-deletes integration credential rows for an organization (best-effort test\n * cleanup). Integration credentials are stored per (integration_id,\n * organization_id, tenant_id, user_id) with no FK to organizations, so a\n * throwaway org's credential rows must be removed explicitly when the org row is\n * torn down.\n */\nexport async function deleteIntegrationCredentialsInDb(organizationId: string | null): Promise<void> {\n if (!organizationId) return;\n await withClient(async (client) => {\n await client.query('delete from integration_credentials where organization_id = $1', [organizationId]);\n });\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AACjB,SAAS,cAAc;AACvB,SAAS,sBAAsB;AAc/B,SAAS,aAAa,KAAiC;AACrD,MAAI,QAAQ,IAAI,GAAG,EAAG,QAAO,QAAQ,IAAI,GAAG;AAC5C,QAAM,iBAAiB;AAAA,IACrB,KAAK,QAAQ,eAAe,GAAG,MAAM;AAAA,IACrC,KAAK,QAAQ,QAAQ,IAAI,GAAG,mBAAmB;AAAA,IAC/C,KAAK,QAAQ,QAA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ACA;AAAA,IACF;AACA,UAAM,OAAO;AAAA,MACX;AAAA;AAAA,MAEA,CAAC,MAAM,QAAQ,MAAM,UAAU,cAAc,iBAAiB;AAAA,IAChE;AAAA,EACF,CAAC;AACH;AAGA,eAAsB,kBAAkB,QAA+B;AACrE,MAAI,CAAC,OAAQ;AACb,QAAM,WAAW,OAAO,WAAW;AACjC,UAAM,OAAO,MAAM,4CAA4C,CAAC,MAAM,CAAC;AAAA,EACzE,CAAC;AACH;AAWA,eAAsB,uBAAuB,OAA4D;AACvG,SAAO,WAAW,OAAO,WAAW;AAClC,UAAM,SAAS,MAAM,OAAO;AAAA,MAC1B;AAAA;AAAA;AAAA;AAAA,MAIA,CAAC,MAAM,UAAU,MAAM,IAAI;AAAA,IAC7B;AACA,WAAO,OAAO,KAAK,CAAC,EAAE;AAAA,EACxB,CAAC;AACH;AAGA,eAAsB,uBAAuB,gBAA8C;AACzF,MAAI,CAAC,eAAgB;AACrB,QAAM,WAAW,OAAO,WAAW;AACjC,UAAM,OAAO,MAAM,2CAA2C,CAAC,cAAc,CAAC;AAAA,EAChF,CAAC;AACH;AASA,eAAsB,iCAAiC,gBAA8C;AACnG,MAAI,CAAC,eAAgB;AACrB,QAAM,WAAW,OAAO,WAAW;AACjC,UAAM,OAAO,MAAM,kEAAkE,CAAC,cAAc,CAAC;AAAA,EACvG,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ const metadata = {
5
5
  description: "Core CRM capabilities for people, companies, deals, and activities.",
6
6
  author: "Open Mercato Team",
7
7
  license: "MIT",
8
+ requires: ["progress"],
8
9
  ejectable: true
9
10
  };
10
11
  import { features } from "./acl.js";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/customers/index.ts"],
4
- "sourcesContent": ["import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n\nexport const metadata: ModuleInfo = {\n name: 'customers',\n title: 'Customer Relationship Management',\n version: '0.1.0',\n description: 'Core CRM capabilities for people, companies, deals, and activities.',\n author: 'Open Mercato Team',\n license: 'MIT',\n ejectable: true,\n}\n\nexport { features } from './acl'\n"],
5
- "mappings": "AAEO,MAAM,WAAuB;AAAA,EAClC,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,WAAW;AACb;AAEA,SAAS,gBAAgB;",
4
+ "sourcesContent": ["import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n\nexport const metadata: ModuleInfo = {\n name: 'customers',\n title: 'Customer Relationship Management',\n version: '0.1.0',\n description: 'Core CRM capabilities for people, companies, deals, and activities.',\n author: 'Open Mercato Team',\n license: 'MIT',\n requires: ['progress'],\n ejectable: true,\n}\n\nexport { features } from './acl'\n"],
5
+ "mappings": "AAEO,MAAM,WAAuB;AAAA,EAClC,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU,CAAC,UAAU;AAAA,EACrB,WAAW;AACb;AAEA,SAAS,gBAAgB;",
6
6
  "names": []
7
7
  }
@@ -54,6 +54,74 @@ async function pruneDuplicateCoverageRows(db, scope, keepId) {
54
54
  }
55
55
  await query.execute();
56
56
  }
57
+ function coverageInitializationLockKey(scope) {
58
+ return [
59
+ scope.entityType,
60
+ scope.tenantId ?? "__null_tenant__",
61
+ normalizeOrganizationForStore(scope.organizationId ?? null),
62
+ scope.withDeleted === true ? "with_deleted" : "active_only"
63
+ ].join("|");
64
+ }
65
+ async function lockCoverageInitialization(db, scope) {
66
+ await sql`
67
+ select pg_advisory_xact_lock(
68
+ hashtextextended(${coverageInitializationLockKey(scope)}, 0)
69
+ )
70
+ `.execute(db);
71
+ }
72
+ async function updateCoverageRows(db, scope, deltas) {
73
+ let update = db.updateTable("entity_index_coverage").set({
74
+ base_count: sql`greatest(${sql.ref("base_count")} + ${deltas.deltaBase}, 0)`,
75
+ indexed_count: sql`greatest(${sql.ref("indexed_count")} + ${deltas.deltaIndex}, 0)`,
76
+ vector_indexed_count: sql`greatest(${sql.ref("vector_indexed_count")} + ${deltas.deltaVector}, 0)`,
77
+ refreshed_at: sql`now()`
78
+ }).where("entity_type", "=", scope.entityType).where("with_deleted", "=", scope.withDeleted === true);
79
+ update = scope.tenantId == null ? update.where("tenant_id", "is", null) : update.where("tenant_id", "=", scope.tenantId);
80
+ update = applyOrganizationCondition(update, "organization_id", scope.organizationId ?? null);
81
+ return update.returning(["id"]).execute();
82
+ }
83
+ async function incrementCoverageRow(db, scope, deltas) {
84
+ const storedOrgId = normalizeOrganizationForStore(scope.organizationId ?? null);
85
+ let deltaBase = deltas.deltaBase;
86
+ let deltaIndex = deltas.deltaIndex;
87
+ let deltaVector = deltas.deltaVector;
88
+ if (scope.organizationId == null) {
89
+ let purge = db.deleteFrom("entity_index_coverage").where("entity_type", "=", scope.entityType).where("with_deleted", "=", scope.withDeleted === true).where("organization_id", "is", null);
90
+ purge = scope.tenantId == null ? purge.where("tenant_id", "is", null) : purge.where("tenant_id", "=", scope.tenantId);
91
+ const purged = await purge.returning(["base_count", "indexed_count", "vector_indexed_count"]).execute();
92
+ for (const row of purged ?? []) {
93
+ deltaBase += toCount(row.base_count);
94
+ deltaIndex += toCount(row.indexed_count);
95
+ deltaVector += toCount(row.vector_indexed_count);
96
+ }
97
+ }
98
+ let updated = await updateCoverageRows(db, scope, { deltaBase, deltaIndex, deltaVector });
99
+ if (updated.length === 0 && scope.tenantId == null) {
100
+ await lockCoverageInitialization(db, scope);
101
+ updated = await updateCoverageRows(db, scope, { deltaBase, deltaIndex, deltaVector });
102
+ }
103
+ if (updated.length > 0) {
104
+ if (updated.length > 1) await pruneDuplicateCoverageRows(db, scope, updated[0].id);
105
+ return;
106
+ }
107
+ const rows = await db.insertInto("entity_index_coverage").values({
108
+ entity_type: scope.entityType,
109
+ tenant_id: scope.tenantId ?? null,
110
+ organization_id: storedOrgId,
111
+ with_deleted: scope.withDeleted === true,
112
+ base_count: Math.max(deltaBase, 0),
113
+ indexed_count: Math.max(deltaIndex, 0),
114
+ vector_indexed_count: Math.max(deltaVector, 0),
115
+ refreshed_at: sql`now()`
116
+ }).onConflict((oc) => oc.columns(["entity_type", "tenant_id", "organization_id", "with_deleted"]).doUpdateSet({
117
+ base_count: sql`greatest(${sql.ref("entity_index_coverage.base_count")} + ${deltaBase}, 0)`,
118
+ indexed_count: sql`greatest(${sql.ref("entity_index_coverage.indexed_count")} + ${deltaIndex}, 0)`,
119
+ vector_indexed_count: sql`greatest(${sql.ref("entity_index_coverage.vector_indexed_count")} + ${deltaVector}, 0)`,
120
+ refreshed_at: sql`now()`
121
+ })).returning(["id"]).execute();
122
+ const keepId = rows?.[0]?.id ?? null;
123
+ await pruneDuplicateCoverageRows(db, scope, keepId);
124
+ }
57
125
  async function upsertCoverageRow(db, scope, counts) {
58
126
  const storedOrgId = normalizeOrganizationForStore(scope.organizationId ?? null);
59
127
  if (scope.organizationId == null) {
@@ -136,22 +204,23 @@ async function readCoverageSnapshots(db, batch) {
136
204
  }
137
205
  async function applyCoverageAdjustments(em, adjustments, options) {
138
206
  if (!adjustments.length) return;
139
- const db = options?.trx ?? em.getKysely();
140
- const aggregated = aggregateAdjustments(adjustments);
207
+ const db = em.getKysely();
208
+ const ambientTrx = db.isTransaction === true ? db : null;
209
+ const aggregated = aggregateAdjustments(adjustments).sort((left, right) => scopeKey(left.scope).localeCompare(scopeKey(right.scope)));
210
+ const executor = options?.trx ?? ambientTrx;
141
211
  for (const entry of aggregated) {
142
- const scope = entry.scope;
143
- const existing = await fetchCoverageRow(db, scope);
144
- const currentBase = existing ? toCount(existing.base_count) : 0;
145
- const currentIndex = existing ? toCount(existing.indexed_count) : 0;
146
- const currentVector = existing ? toCount(existing.vector_indexed_count) : 0;
147
- const nextBase = Math.max(currentBase + entry.deltaBase, 0);
148
- const nextIndex = Math.max(currentIndex + entry.deltaIndex, 0);
149
- const nextVector = Math.max(currentVector + entry.deltaVector, 0);
150
- await upsertCoverageRow(db, scope, {
151
- baseCount: nextBase,
152
- indexedCount: nextIndex,
153
- vectorIndexedCount: nextVector
154
- });
212
+ const deltas = {
213
+ deltaBase: entry.deltaBase,
214
+ deltaIndex: entry.deltaIndex,
215
+ deltaVector: entry.deltaVector
216
+ };
217
+ if (executor) {
218
+ await incrementCoverageRow(executor, entry.scope, deltas);
219
+ } else if (entry.scope.tenantId == null) {
220
+ await db.transaction().execute((trx) => incrementCoverageRow(trx, entry.scope, deltas));
221
+ } else {
222
+ await incrementCoverageRow(db, entry.scope, deltas);
223
+ }
155
224
  }
156
225
  }
157
226
  async function deleteCoverageForEntity(db, entityType) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/query_index/lib/coverage.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, type Transaction, sql } from 'kysely'\nimport { resolveEntityTableName } from '@open-mercato/shared/lib/query/engine'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('query_index').child({ component: 'coverage' })\n\ntype CoverageExecutor = Kysely<any> | Transaction<any>\n\nexport type CoverageScope = {\n entityType: string\n tenantId?: string | null\n organizationId?: string | null\n withDeleted?: boolean\n}\n\ntype CoverageRow = {\n base_count: unknown\n indexed_count: unknown\n vector_indexed_count: unknown\n refreshed_at: Date | string | null\n}\n\nexport type CoverageSnapshot = CoverageRow & {\n baseCount: number\n indexedCount: number\n vectorIndexedCount: number\n}\n\nexport type CoverageBatchScope = {\n entityTypes: readonly string[]\n tenantId?: string | null\n organizationId?: string | null\n withDeleted?: boolean\n}\n\nexport type CoverageAdjustment = {\n entityType: string\n tenantId: string | null\n organizationId: string | null\n withDeleted?: boolean\n deltaBase: number\n deltaIndex: number\n deltaVector?: number\n}\n\nexport type CoverageDeltaInput = {\n entityType: string\n tenantId: string | null\n organizationId: string | null\n withDeleted?: boolean\n baseDelta: number\n indexDelta: number\n vectorDelta?: number\n}\n\nconst COLUMN_CACHE = new Map<string, boolean>()\n// In-flight de-dup: without this, N concurrent `tableHasColumn` callers for the same\n// (table, column) \u2014 e.g. every entity type's `refreshCoverageSnapshot` asking about\n// `vector_search.entity_id` \u2014 would each see a cold cache and fire their own identical\n// `information_schema.columns` query, since the cache is only populated after a query\n// resolves. Tracking the in-flight promise lets late arrivals await the first one instead.\nconst COLUMN_CACHE_PENDING = new Map<string, Promise<boolean>>()\nconst GLOBAL_ORGANIZATION_PLACEHOLDER = '00000000-0000-0000-0000-000000000000'\nexport const COVERAGE_ORG_PLACEHOLDER = GLOBAL_ORGANIZATION_PLACEHOLDER\n\nfunction toCount(value: unknown): number {\n if (typeof value === 'number') return Number.isFinite(value) ? value : 0\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n }\n if (value != null && typeof (value as { valueOf: () => number }).valueOf === 'function') {\n const parsed = Number((value as { valueOf: () => number }).valueOf())\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n}\n\nfunction normalizeOrganizationForStore(orgId: string | null | undefined): string {\n return orgId ?? GLOBAL_ORGANIZATION_PLACEHOLDER\n}\n\nfunction applyOrganizationCondition<QB extends { where: (...args: any[]) => QB }>(\n qb: QB,\n column: string,\n organizationId: string | null | undefined,\n): QB {\n const stored = normalizeOrganizationForStore(organizationId ?? null)\n if (stored === GLOBAL_ORGANIZATION_PLACEHOLDER) {\n return qb.where((eb: any) => eb.or([\n eb(column as any, 'is', null),\n eb(column as any, '=', GLOBAL_ORGANIZATION_PLACEHOLDER),\n ]))\n }\n return qb.where(column as any, '=', stored)\n}\n\nasync function fetchCoverageRow(\n db: CoverageExecutor,\n scope: CoverageScope\n): Promise<(CoverageRow & { organization_id: string | null }) | null> {\n const { entityType, tenantId, organizationId, withDeleted } = scope\n let query = db\n .selectFrom('entity_index_coverage' as any)\n .select([\n 'base_count' as any,\n 'indexed_count' as any,\n 'vector_indexed_count' as any,\n 'refreshed_at' as any,\n 'organization_id' as any,\n ])\n .where('entity_type' as any, '=', entityType)\n .where('with_deleted' as any, '=', withDeleted === true)\n .orderBy('refreshed_at' as any, 'desc')\n query = tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', tenantId)\n query = applyOrganizationCondition(query as any, 'organization_id', organizationId ?? null)\n const row = await query.executeTakeFirst() as (CoverageRow & { organization_id: string | null }) | undefined\n return row ?? null\n}\n\nasync function pruneDuplicateCoverageRows(\n db: CoverageExecutor,\n scope: CoverageScope,\n keepId: string | null\n): Promise<void> {\n let query = db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', scope.entityType)\n .where('with_deleted' as any, '=', scope.withDeleted === true)\n query = scope.tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', scope.tenantId)\n query = applyOrganizationCondition(query as any, 'organization_id', scope.organizationId ?? null)\n if (keepId) {\n query = query.where('id' as any, '!=', keepId)\n }\n await query.execute()\n}\n\nasync function upsertCoverageRow(\n db: CoverageExecutor,\n scope: CoverageScope,\n counts: { baseCount: number; indexedCount: number; vectorIndexedCount: number }\n): Promise<void> {\n const storedOrgId = normalizeOrganizationForStore(scope.organizationId ?? null)\n if (scope.organizationId == null) {\n let purge = db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', scope.entityType)\n .where('with_deleted' as any, '=', scope.withDeleted === true)\n .where('organization_id' as any, 'is', null as any)\n purge = scope.tenantId == null\n ? purge.where('tenant_id' as any, 'is', null as any)\n : purge.where('tenant_id' as any, '=', scope.tenantId)\n await purge.execute()\n }\n\n const rows = await db\n .insertInto('entity_index_coverage' as any)\n .values({\n entity_type: scope.entityType,\n tenant_id: scope.tenantId ?? null,\n organization_id: storedOrgId,\n with_deleted: scope.withDeleted === true,\n base_count: counts.baseCount,\n indexed_count: counts.indexedCount,\n vector_indexed_count: counts.vectorIndexedCount,\n refreshed_at: sql`now()`,\n } as any)\n .onConflict((oc: any) => oc\n .columns(['entity_type', 'tenant_id', 'organization_id', 'with_deleted'])\n .doUpdateSet({\n base_count: counts.baseCount,\n indexed_count: counts.indexedCount,\n vector_indexed_count: counts.vectorIndexedCount,\n refreshed_at: sql`now()`,\n } as any))\n .returning(['id' as any])\n .execute() as Array<{ id: string }>\n\n const keepId = rows?.[0]?.id ?? null\n await pruneDuplicateCoverageRows(db, scope, keepId)\n}\n\nexport async function readCoverageSnapshot(\n db: Kysely<any>,\n scope: CoverageScope\n): Promise<(CoverageRow & { baseCount: number; indexedCount: number; vectorIndexedCount: number }) | null> {\n const entityType = String(scope.entityType || '')\n if (!entityType) return null\n const row = await fetchCoverageRow(db, {\n entityType,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId ?? null,\n withDeleted: scope.withDeleted === true,\n })\n if (!row) return null\n const refreshedAt = row.refreshed_at instanceof Date ? row.refreshed_at : (row.refreshed_at ? new Date(row.refreshed_at) : null)\n return {\n base_count: row.base_count,\n indexed_count: row.indexed_count,\n vector_indexed_count: row.vector_indexed_count,\n refreshed_at: refreshedAt ?? null,\n baseCount: toCount(row.base_count),\n indexedCount: toCount(row.indexed_count),\n vectorIndexedCount: toCount(row.vector_indexed_count),\n }\n}\n\nexport async function readCoverageSnapshots(\n db: Kysely<any>,\n batch: CoverageBatchScope\n): Promise<Map<string, CoverageSnapshot>> {\n const entityTypes = Array.from(\n new Set((batch.entityTypes ?? []).map((id) => String(id || '')).filter((id) => id.length > 0))\n )\n const result = new Map<string, CoverageSnapshot>()\n if (entityTypes.length === 0) return result\n\n const withDeleted = batch.withDeleted === true\n let query = db\n .selectFrom('entity_index_coverage' as any)\n .select([\n 'entity_type' as any,\n 'base_count' as any,\n 'indexed_count' as any,\n 'vector_indexed_count' as any,\n 'refreshed_at' as any,\n 'organization_id' as any,\n ])\n .where('entity_type' as any, 'in', entityTypes)\n .where('with_deleted' as any, '=', withDeleted)\n .orderBy('refreshed_at' as any, 'desc')\n query = batch.tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', batch.tenantId)\n query = applyOrganizationCondition(query as any, 'organization_id', batch.organizationId ?? null)\n\n const rows = await query.execute() as Array<CoverageRow & { entity_type: string }>\n for (const row of rows ?? []) {\n const entityType = String(row.entity_type || '')\n // Rows are ordered by refreshed_at desc, so the first row seen per entity is the latest.\n if (!entityType || result.has(entityType)) continue\n const refreshedAt = row.refreshed_at instanceof Date\n ? row.refreshed_at\n : (row.refreshed_at ? new Date(row.refreshed_at) : null)\n result.set(entityType, {\n base_count: row.base_count,\n indexed_count: row.indexed_count,\n vector_indexed_count: row.vector_indexed_count,\n refreshed_at: refreshedAt ?? null,\n baseCount: toCount(row.base_count),\n indexedCount: toCount(row.indexed_count),\n vectorIndexedCount: toCount(row.vector_indexed_count),\n })\n }\n return result\n}\n\nexport async function applyCoverageAdjustments(\n em: EntityManager,\n adjustments: CoverageAdjustment[],\n options?: { trx?: CoverageExecutor },\n): Promise<void> {\n if (!adjustments.length) return\n const db = options?.trx ?? ((em as any).getKysely() as Kysely<any>)\n const aggregated = aggregateAdjustments(adjustments)\n for (const entry of aggregated) {\n const scope = entry.scope\n const existing = await fetchCoverageRow(db, scope)\n const currentBase = existing ? toCount(existing.base_count) : 0\n const currentIndex = existing ? toCount(existing.indexed_count) : 0\n const currentVector = existing ? toCount(existing.vector_indexed_count) : 0\n const nextBase = Math.max(currentBase + entry.deltaBase, 0)\n const nextIndex = Math.max(currentIndex + entry.deltaIndex, 0)\n const nextVector = Math.max(currentVector + entry.deltaVector, 0)\n\n await upsertCoverageRow(db, scope, {\n baseCount: nextBase,\n indexedCount: nextIndex,\n vectorIndexedCount: nextVector,\n })\n }\n}\n\nexport async function deleteCoverageForEntity(db: Kysely<any>, entityType: string): Promise<void> {\n if (!entityType) return\n await db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', entityType)\n .execute()\n}\n\nasync function deleteCoverageScope(db: Kysely<any>, scope: CoverageScope): Promise<void> {\n const { entityType, tenantId, organizationId, withDeleted } = scope\n if (!entityType) return\n let query = db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', entityType)\n .where('with_deleted' as any, '=', withDeleted === true)\n query = tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', tenantId)\n await applyOrganizationCondition(query as any, 'organization_id', organizationId ?? null).execute()\n}\n\nasync function tableHasColumn(db: Kysely<any>, table: string, column: string): Promise<boolean> {\n const key = `${table}.${column}`\n if (COLUMN_CACHE.has(key)) return COLUMN_CACHE.get(key)!\n const pending = COLUMN_CACHE_PENDING.get(key)\n if (pending) return pending\n const promise = (async () => {\n const exists = await db\n .selectFrom('information_schema.columns' as any)\n .select(sql<number>`1`.as('present'))\n .where(sql<boolean>`table_schema = current_schema()`)\n .where('table_name' as any, '=', table)\n .where('column_name' as any, '=', column)\n .executeTakeFirst()\n const present = !!exists\n COLUMN_CACHE.set(key, present)\n return present\n })()\n COLUMN_CACHE_PENDING.set(key, promise)\n try {\n return await promise\n } finally {\n COLUMN_CACHE_PENDING.delete(key)\n }\n}\n\nexport type ColumnCheck = { table: string; column: string }\n\n// Batches the `information_schema.columns` introspection used by `refreshCoverageSnapshot`\n// into a single query for a whole set of (table, column) pairs, and pre-populates\n// `COLUMN_CACHE_PENDING` for every pair before that query even runs. Callers of\n// `coverage_warmup.ts` use this so its many concurrently-dispatched `coverage.refresh`\n// subscribers hit an already-primed (or in-flight) cache instead of each doing their own\n// per-table introspection round trip.\nexport async function primeColumnCache(db: Kysely<any>, checks: ColumnCheck[]): Promise<void> {\n const missing: Array<{ table: string; column: string; key: string }> = []\n const seen = new Set<string>()\n for (const check of checks) {\n const table = String(check?.table || '')\n const column = String(check?.column || '')\n if (!table || !column) continue\n const key = `${table}.${column}`\n if (seen.has(key)) continue\n seen.add(key)\n if (COLUMN_CACHE.has(key) || COLUMN_CACHE_PENDING.has(key)) continue\n missing.push({ table, column, key })\n }\n if (!missing.length) return\n\n const tables = Array.from(new Set(missing.map((entry) => entry.table)))\n const columns = Array.from(new Set(missing.map((entry) => entry.column)))\n\n const batchPromise = (async (): Promise<Set<string>> => {\n const rows = await db\n .selectFrom('information_schema.columns' as any)\n .select(['table_name' as any, 'column_name' as any])\n .where(sql<boolean>`table_schema = current_schema()`)\n .where('table_name' as any, 'in', tables)\n .where('column_name' as any, 'in', columns)\n .execute() as Array<{ table_name: string; column_name: string }>\n return new Set(rows.map((row) => `${row.table_name}.${row.column_name}`))\n })()\n\n for (const entry of missing) {\n const entryPromise = batchPromise.then((present) => {\n const value = present.has(entry.key)\n COLUMN_CACHE.set(entry.key, value)\n return value\n })\n // Mark the stored promise as handled: when the batch query fails and no\n // `tableHasColumn` caller has adopted this entry yet (the common case \u2014 the warmup\n // awaits priming before dispatching any refresh), an orphaned rejection would\n // otherwise crash a plain-Node event worker via unhandledRejection. Awaiting\n // callers still observe the rejection through the stored reference.\n entryPromise.catch(() => undefined)\n COLUMN_CACHE_PENDING.set(entry.key, entryPromise)\n }\n\n try {\n await batchPromise\n } finally {\n for (const entry of missing) COLUMN_CACHE_PENDING.delete(entry.key)\n }\n}\n\nexport async function refreshCoverageSnapshot(\n em: EntityManager,\n scope: CoverageScope,\n): Promise<{ baseCount: number; indexedCount: number } | null> {\n const entityType = String(scope.entityType || '')\n if (!entityType) return null\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n const withDeleted = scope.withDeleted === true\n\n const db = (em as any).getKysely() as Kysely<any>\n const baseTable = resolveEntityTableName(em, entityType)\n\n const hasOrg = await tableHasColumn(db, baseTable, 'organization_id')\n const hasTenant = await tableHasColumn(db, baseTable, 'tenant_id')\n const hasDeleted = await tableHasColumn(db, baseTable, 'deleted_at')\n\n // A scope the base table cannot express must not narrow the index side either. Index rows\n // can carry an organization the base table has no column for \u2014 `organizations` has no\n // `organization_id` yet its index rows derive one from the record id. Filtering only the\n // index side compares two different populations and reports a gap no reindex can close;\n // returning early instead of recounting left the previous snapshot frozen, which is what\n // surfaced as a permanent \"out of sync\" row for `directory:organization`.\n //\n // Tenant is different: a base table without `tenant_id` (`user_roles`) cannot be counted\n // per tenant at all, and writing the cross-tenant total into one tenant's row would leak\n // another tenant's volume into it. Drop the unusable scoped row instead, leaving only the\n // global row \u2014 which is the one that can be true \u2014 rather than freezing a stale count.\n const scopeOrg = organizationId !== null && hasOrg\n if (tenantId !== null && !hasTenant) {\n await deleteCoverageScope(db, { entityType, tenantId, organizationId, withDeleted })\n return null\n }\n const scopeTenant = tenantId !== null && hasTenant\n\n let baseQuery = db\n .selectFrom(`${baseTable} as b` as any)\n .select(sql`count(*)`.as('count'))\n if (scopeOrg) baseQuery = baseQuery.where('b.organization_id' as any, '=', organizationId)\n if (scopeTenant) baseQuery = baseQuery.where('b.tenant_id' as any, '=', tenantId)\n if (!withDeleted && hasDeleted) baseQuery = baseQuery.where('b.deleted_at' as any, 'is', null as any)\n\n let indexQuery = db\n .selectFrom('entity_indexes as ei' as any)\n .select(sql`count(*)`.as('count'))\n .where('ei.entity_type' as any, '=', entityType)\n if (scopeOrg) indexQuery = indexQuery.where('ei.organization_id' as any, '=', organizationId)\n if (scopeTenant) indexQuery = indexQuery.where('ei.tenant_id' as any, '=', tenantId)\n if (!withDeleted) indexQuery = indexQuery.where('ei.deleted_at' as any, 'is', null as any)\n\n const vectorCountPromise = (async (): Promise<number | undefined> => {\n const hasVectorTable = await tableHasColumn(db, 'vector_search', 'entity_id')\n if (!hasVectorTable || typeof tenantId !== 'string' || tenantId.length === 0) return undefined\n\n try {\n let vectorQuery = db\n .selectFrom('vector_search' as any)\n .select(sql`count(*)`.as('count'))\n .where('entity_id' as any, '=', entityType)\n .where('tenant_id' as any, '=', tenantId)\n if (organizationId !== null) {\n vectorQuery = vectorQuery.where('organization_id' as any, '=', organizationId)\n }\n const vectorRow = await vectorQuery.executeTakeFirst() as { count: unknown } | undefined\n return toCount(vectorRow?.count)\n } catch (err) {\n logger.warn('Failed to resolve vector count for coverage snapshot', {\n entityType,\n tenantId,\n organizationId,\n error: err instanceof Error ? err.message : err,\n })\n return undefined\n }\n })()\n\n const [baseRow, indexRow, vectorCount] = await Promise.all([\n baseQuery.executeTakeFirst() as Promise<{ count: unknown } | undefined>,\n indexQuery.executeTakeFirst() as Promise<{ count: unknown } | undefined>,\n vectorCountPromise,\n ])\n\n const baseCount = toCount(baseRow?.count)\n const indexCount = toCount(indexRow?.count)\n\n await writeCoverageCounts(em, { entityType, tenantId, organizationId, withDeleted }, {\n baseCount,\n indexedCount: indexCount,\n vectorCount,\n })\n\n return { baseCount, indexedCount: indexCount }\n}\n\nexport async function writeCoverageCounts(\n em: EntityManager,\n scope: CoverageScope,\n counts: { baseCount?: number; indexedCount?: number; vectorCount?: number }\n): Promise<void> {\n const entityType = String(scope.entityType || '')\n if (!entityType) return\n const db = (em as any).getKysely() as Kysely<any>\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n const withDeleted = scope.withDeleted === true\n const existing = await fetchCoverageRow(db, {\n entityType,\n tenantId,\n organizationId,\n withDeleted,\n })\n const baseCount = counts.baseCount !== undefined\n ? Math.max(0, Math.trunc(toCount(counts.baseCount)))\n : Math.max(0, Math.trunc(toCount(existing?.base_count)))\n const indexCount = counts.indexedCount !== undefined\n ? Math.max(0, Math.trunc(toCount(counts.indexedCount)))\n : Math.max(0, Math.trunc(toCount(existing?.indexed_count)))\n const vectorCount = counts.vectorCount !== undefined\n ? Math.max(0, Math.trunc(toCount(counts.vectorCount)))\n : Math.max(0, Math.trunc(toCount(existing?.vector_indexed_count)))\n await upsertCoverageRow(db, { entityType, tenantId, organizationId, withDeleted }, {\n baseCount,\n indexedCount: indexCount,\n vectorIndexedCount: vectorCount,\n })\n}\n\ntype AggregatedAdjustment = {\n scope: CoverageScope\n deltaBase: number\n deltaIndex: number\n deltaVector: number\n}\n\nfunction aggregateAdjustments(adjustments: CoverageAdjustment[]): AggregatedAdjustment[] {\n const map = new Map<string, AggregatedAdjustment>()\n for (const adj of adjustments) {\n if (!adj?.entityType) continue\n const deltaBase = Number.isFinite(adj.deltaBase) ? adj.deltaBase : 0\n const deltaIndex = Number.isFinite(adj.deltaIndex) ? adj.deltaIndex : 0\n const deltaVector = Number.isFinite(adj.deltaVector) ? adj.deltaVector! : 0\n if (deltaBase === 0 && deltaIndex === 0 && deltaVector === 0) continue\n const scope: CoverageScope = {\n entityType: adj.entityType,\n tenantId: adj.tenantId ?? null,\n organizationId: adj.organizationId ?? null,\n withDeleted: adj.withDeleted === true,\n }\n const key = scopeKey(scope)\n const existing = map.get(key)\n if (existing) {\n existing.deltaBase += deltaBase\n existing.deltaIndex += deltaIndex\n existing.deltaVector += deltaVector\n } else {\n map.set(key, { scope, deltaBase, deltaIndex, deltaVector })\n }\n }\n return Array.from(map.values())\n}\n\nfunction scopeKey(scope: CoverageScope): string {\n const tenant = scope.tenantId ?? '__tenant_null__'\n const org = normalizeOrganizationForStore(scope.organizationId ?? null)\n const deleted = scope.withDeleted === true ? '1' : '0'\n return `${scope.entityType}|${tenant}|${org}|${deleted}`\n}\n\nexport function createCoverageAdjustments(input: CoverageDeltaInput): CoverageAdjustment[] {\n const entityType = String(input.entityType || '')\n if (!entityType) return []\n const baseDelta = Number.isFinite(input.baseDelta) ? input.baseDelta : 0\n const indexDelta = Number.isFinite(input.indexDelta) ? input.indexDelta : 0\n const vectorDelta = Number.isFinite(input.vectorDelta) ? input.vectorDelta! : 0\n if (baseDelta === 0 && indexDelta === 0 && vectorDelta === 0) return []\n const withDeleted = input.withDeleted === true\n const tenantId = input.tenantId ?? null\n const organizationId = input.organizationId ?? null\n return [\n {\n entityType,\n tenantId,\n organizationId,\n withDeleted,\n deltaBase: baseDelta,\n deltaIndex: indexDelta,\n deltaVector: vectorDelta,\n },\n ]\n}\n"],
5
- "mappings": "AACA,SAAwC,WAAW;AACnD,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAE7B,MAAM,S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AAM,UAAU,IAAI,MAAM,aAAa;AAC1E,QAAM,cAAc,OAAO,SAAS,MAAM,WAAW,IAAI,MAAM,cAAe;AAC9E,MAAI,cAAc,KAAK,eAAe,KAAK,gBAAgB,EAAG,QAAO,CAAC;AACtE,QAAM,cAAc,MAAM,gBAAgB;AAC1C,QAAM,WAAW,MAAM,YAAY;AACnC,QAAM,iBAAiB,MAAM,kBAAkB;AAC/C,SAAO;AAAA,IACL;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,aAAa;AAAA,IACf;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, type Transaction, sql } from 'kysely'\nimport { resolveEntityTableName } from '@open-mercato/shared/lib/query/engine'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('query_index').child({ component: 'coverage' })\n\ntype CoverageExecutor = Kysely<any> | Transaction<any>\n\nexport type CoverageScope = {\n entityType: string\n tenantId?: string | null\n organizationId?: string | null\n withDeleted?: boolean\n}\n\ntype CoverageRow = {\n base_count: unknown\n indexed_count: unknown\n vector_indexed_count: unknown\n refreshed_at: Date | string | null\n}\n\nexport type CoverageSnapshot = CoverageRow & {\n baseCount: number\n indexedCount: number\n vectorIndexedCount: number\n}\n\nexport type CoverageBatchScope = {\n entityTypes: readonly string[]\n tenantId?: string | null\n organizationId?: string | null\n withDeleted?: boolean\n}\n\nexport type CoverageAdjustment = {\n entityType: string\n tenantId: string | null\n organizationId: string | null\n withDeleted?: boolean\n deltaBase: number\n deltaIndex: number\n deltaVector?: number\n}\n\nexport type CoverageDeltaInput = {\n entityType: string\n tenantId: string | null\n organizationId: string | null\n withDeleted?: boolean\n baseDelta: number\n indexDelta: number\n vectorDelta?: number\n}\n\nconst COLUMN_CACHE = new Map<string, boolean>()\n// In-flight de-dup: without this, N concurrent `tableHasColumn` callers for the same\n// (table, column) \u2014 e.g. every entity type's `refreshCoverageSnapshot` asking about\n// `vector_search.entity_id` \u2014 would each see a cold cache and fire their own identical\n// `information_schema.columns` query, since the cache is only populated after a query\n// resolves. Tracking the in-flight promise lets late arrivals await the first one instead.\nconst COLUMN_CACHE_PENDING = new Map<string, Promise<boolean>>()\nconst GLOBAL_ORGANIZATION_PLACEHOLDER = '00000000-0000-0000-0000-000000000000'\nexport const COVERAGE_ORG_PLACEHOLDER = GLOBAL_ORGANIZATION_PLACEHOLDER\n\nfunction toCount(value: unknown): number {\n if (typeof value === 'number') return Number.isFinite(value) ? value : 0\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n }\n if (value != null && typeof (value as { valueOf: () => number }).valueOf === 'function') {\n const parsed = Number((value as { valueOf: () => number }).valueOf())\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n}\n\nfunction normalizeOrganizationForStore(orgId: string | null | undefined): string {\n return orgId ?? GLOBAL_ORGANIZATION_PLACEHOLDER\n}\n\nfunction applyOrganizationCondition<QB extends { where: (...args: any[]) => QB }>(\n qb: QB,\n column: string,\n organizationId: string | null | undefined,\n): QB {\n const stored = normalizeOrganizationForStore(organizationId ?? null)\n if (stored === GLOBAL_ORGANIZATION_PLACEHOLDER) {\n return qb.where((eb: any) => eb.or([\n eb(column as any, 'is', null),\n eb(column as any, '=', GLOBAL_ORGANIZATION_PLACEHOLDER),\n ]))\n }\n return qb.where(column as any, '=', stored)\n}\n\nasync function fetchCoverageRow(\n db: CoverageExecutor,\n scope: CoverageScope\n): Promise<(CoverageRow & { organization_id: string | null }) | null> {\n const { entityType, tenantId, organizationId, withDeleted } = scope\n let query = db\n .selectFrom('entity_index_coverage' as any)\n .select([\n 'base_count' as any,\n 'indexed_count' as any,\n 'vector_indexed_count' as any,\n 'refreshed_at' as any,\n 'organization_id' as any,\n ])\n .where('entity_type' as any, '=', entityType)\n .where('with_deleted' as any, '=', withDeleted === true)\n .orderBy('refreshed_at' as any, 'desc')\n query = tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', tenantId)\n query = applyOrganizationCondition(query as any, 'organization_id', organizationId ?? null)\n const row = await query.executeTakeFirst() as (CoverageRow & { organization_id: string | null }) | undefined\n return row ?? null\n}\n\nasync function pruneDuplicateCoverageRows(\n db: CoverageExecutor,\n scope: CoverageScope,\n keepId: string | null\n): Promise<void> {\n let query = db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', scope.entityType)\n .where('with_deleted' as any, '=', scope.withDeleted === true)\n query = scope.tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', scope.tenantId)\n query = applyOrganizationCondition(query as any, 'organization_id', scope.organizationId ?? null)\n if (keepId) {\n query = query.where('id' as any, '!=', keepId)\n }\n await query.execute()\n}\n\nfunction coverageInitializationLockKey(scope: CoverageScope): string {\n return [\n scope.entityType,\n scope.tenantId ?? '__null_tenant__',\n normalizeOrganizationForStore(scope.organizationId ?? null),\n scope.withDeleted === true ? 'with_deleted' : 'active_only',\n ].join('|')\n}\n\nasync function lockCoverageInitialization(db: CoverageExecutor, scope: CoverageScope): Promise<void> {\n await sql`\n select pg_advisory_xact_lock(\n hashtextextended(${coverageInitializationLockKey(scope)}, 0)\n )\n `.execute(db)\n}\n\nasync function updateCoverageRows(\n db: CoverageExecutor,\n scope: CoverageScope,\n deltas: { deltaBase: number; deltaIndex: number; deltaVector: number },\n): Promise<Array<{ id: string }>> {\n let update = db\n .updateTable('entity_index_coverage' as any)\n .set({\n base_count: sql`greatest(${sql.ref('base_count')} + ${deltas.deltaBase}, 0)`,\n indexed_count: sql`greatest(${sql.ref('indexed_count')} + ${deltas.deltaIndex}, 0)`,\n vector_indexed_count: sql`greatest(${sql.ref('vector_indexed_count')} + ${deltas.deltaVector}, 0)`,\n refreshed_at: sql`now()`,\n } as any)\n .where('entity_type' as any, '=', scope.entityType)\n .where('with_deleted' as any, '=', scope.withDeleted === true)\n update = scope.tenantId == null\n ? update.where('tenant_id' as any, 'is', null as any)\n : update.where('tenant_id' as any, '=', scope.tenantId)\n update = applyOrganizationCondition(update as any, 'organization_id', scope.organizationId ?? null)\n return update.returning(['id' as any]).execute() as Promise<Array<{ id: string }>>\n}\n\n// Applies a coverage delta by incrementing the stored columns in SQL (#5604). The obvious\n// alternative \u2014 read the row, add the delta in JavaScript, write the total back \u2014 is a\n// read-modify-write: two adjustments for the same scope that overlap both read the same row\n// and both write the same total, so one of them is silently lost. Incrementing in SQL makes\n// overlapping adjustments compose, and drops the `SELECT` (and the window between it and the\n// write) that made the coverage row a contention point in the first place.\n//\n// In steady state that is one statement. The extra statements are recovery paths that do not\n// fire once a scope has settled: the legacy NULL-organization fold below runs only for\n// global-organization scopes, the insert only until the scope's row exists, and the duplicate\n// prune only when the scope somehow holds more than one row.\n//\n// The statement is an `UPDATE` rather than an `INSERT \u2026 ON CONFLICT DO UPDATE`, because the\n// conflict target cannot see every scope this table stores: `entity_index_coverage_scope_idx`\n// is a plain `UNIQUE` constraint, and Postgres treats NULLs in one as distinct. For a scope\n// whose tenant is NULL \u2014 `resolveQueryIndexRecordScope`'s `global` branch, or any source row\n// with a NULL tenant column \u2014 the conflict branch would never fire, so every adjustment would\n// insert a fresh row carrying only its own delta and `pruneDuplicateCoverageRows` would then\n// delete the accumulated one. A NULL-aware `UPDATE` matches those rows, and it still adds the\n// delta to the column's own value, so it composes exactly the way the conflict branch does.\nasync function incrementCoverageRow(\n db: CoverageExecutor,\n scope: CoverageScope,\n deltas: { deltaBase: number; deltaIndex: number; deltaVector: number }\n): Promise<void> {\n const storedOrgId = normalizeOrganizationForStore(scope.organizationId ?? null)\n let deltaBase = deltas.deltaBase\n let deltaIndex = deltas.deltaIndex\n let deltaVector = deltas.deltaVector\n\n if (scope.organizationId == null) {\n // Legacy rows stored the global scope as a NULL organization; they are replaced by the\n // placeholder-organization row. `RETURNING` carries their counts into this delta so the\n // migration does not reset the counters (the read-modify-write this replaced folded them\n // in via its `SELECT`, which matched NULL and placeholder alike).\n let purge = db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', scope.entityType)\n .where('with_deleted' as any, '=', scope.withDeleted === true)\n .where('organization_id' as any, 'is', null as any)\n purge = scope.tenantId == null\n ? purge.where('tenant_id' as any, 'is', null as any)\n : purge.where('tenant_id' as any, '=', scope.tenantId)\n const purged = await purge\n .returning(['base_count' as any, 'indexed_count' as any, 'vector_indexed_count' as any])\n .execute() as Array<CoverageRow>\n for (const row of purged ?? []) {\n deltaBase += toCount(row.base_count)\n deltaIndex += toCount(row.indexed_count)\n deltaVector += toCount(row.vector_indexed_count)\n }\n }\n\n let updated = await updateCoverageRows(db, scope, { deltaBase, deltaIndex, deltaVector })\n\n if (updated.length === 0 && scope.tenantId == null) {\n // The unique constraint cannot serialize a first insert whose tenant is NULL. Take a\n // transaction-scoped lock only on this rowless branch, then repeat the UPDATE: a creator\n // that won while we waited has committed its row, so this adjustment composes into it.\n await lockCoverageInitialization(db, scope)\n updated = await updateCoverageRows(db, scope, { deltaBase, deltaIndex, deltaVector })\n }\n\n if (updated.length > 0) {\n // In steady state the scope holds exactly the row just incremented, so the adjustment is\n // the single statement it is described as. Only a scope that somehow accumulated more than\n // one row \u2014 a legacy import, or a concurrent first insert on a NULL-tenant scope, which the\n // unique constraint cannot prevent \u2014 pays for the collapse, and only until it is collapsed.\n if (updated.length > 1) await pruneDuplicateCoverageRows(db, scope, updated[0]!.id)\n return\n }\n\n // No row for this scope yet. `ON CONFLICT` closes the insert race for scopes the unique\n // constraint can see. NULL-tenant initialization reaches here only while holding the scoped\n // transaction advisory lock above, so it has the same single-creator guarantee.\n const rows = await db\n .insertInto('entity_index_coverage' as any)\n .values({\n entity_type: scope.entityType,\n tenant_id: scope.tenantId ?? null,\n organization_id: storedOrgId,\n with_deleted: scope.withDeleted === true,\n base_count: Math.max(deltaBase, 0),\n indexed_count: Math.max(deltaIndex, 0),\n vector_indexed_count: Math.max(deltaVector, 0),\n refreshed_at: sql`now()`,\n } as any)\n .onConflict((oc: any) => oc\n .columns(['entity_type', 'tenant_id', 'organization_id', 'with_deleted'])\n .doUpdateSet({\n base_count: sql`greatest(${sql.ref('entity_index_coverage.base_count')} + ${deltaBase}, 0)`,\n indexed_count: sql`greatest(${sql.ref('entity_index_coverage.indexed_count')} + ${deltaIndex}, 0)`,\n vector_indexed_count: sql`greatest(${sql.ref('entity_index_coverage.vector_indexed_count')} + ${deltaVector}, 0)`,\n refreshed_at: sql`now()`,\n } as any))\n .returning(['id' as any])\n .execute() as Array<{ id: string }>\n\n const keepId = rows?.[0]?.id ?? null\n await pruneDuplicateCoverageRows(db, scope, keepId)\n}\n\nasync function upsertCoverageRow(\n db: CoverageExecutor,\n scope: CoverageScope,\n counts: { baseCount: number; indexedCount: number; vectorIndexedCount: number }\n): Promise<void> {\n const storedOrgId = normalizeOrganizationForStore(scope.organizationId ?? null)\n if (scope.organizationId == null) {\n let purge = db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', scope.entityType)\n .where('with_deleted' as any, '=', scope.withDeleted === true)\n .where('organization_id' as any, 'is', null as any)\n purge = scope.tenantId == null\n ? purge.where('tenant_id' as any, 'is', null as any)\n : purge.where('tenant_id' as any, '=', scope.tenantId)\n await purge.execute()\n }\n\n const rows = await db\n .insertInto('entity_index_coverage' as any)\n .values({\n entity_type: scope.entityType,\n tenant_id: scope.tenantId ?? null,\n organization_id: storedOrgId,\n with_deleted: scope.withDeleted === true,\n base_count: counts.baseCount,\n indexed_count: counts.indexedCount,\n vector_indexed_count: counts.vectorIndexedCount,\n refreshed_at: sql`now()`,\n } as any)\n .onConflict((oc: any) => oc\n .columns(['entity_type', 'tenant_id', 'organization_id', 'with_deleted'])\n .doUpdateSet({\n base_count: counts.baseCount,\n indexed_count: counts.indexedCount,\n vector_indexed_count: counts.vectorIndexedCount,\n refreshed_at: sql`now()`,\n } as any))\n .returning(['id' as any])\n .execute() as Array<{ id: string }>\n\n const keepId = rows?.[0]?.id ?? null\n await pruneDuplicateCoverageRows(db, scope, keepId)\n}\n\nexport async function readCoverageSnapshot(\n db: Kysely<any>,\n scope: CoverageScope\n): Promise<(CoverageRow & { baseCount: number; indexedCount: number; vectorIndexedCount: number }) | null> {\n const entityType = String(scope.entityType || '')\n if (!entityType) return null\n const row = await fetchCoverageRow(db, {\n entityType,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId ?? null,\n withDeleted: scope.withDeleted === true,\n })\n if (!row) return null\n const refreshedAt = row.refreshed_at instanceof Date ? row.refreshed_at : (row.refreshed_at ? new Date(row.refreshed_at) : null)\n return {\n base_count: row.base_count,\n indexed_count: row.indexed_count,\n vector_indexed_count: row.vector_indexed_count,\n refreshed_at: refreshedAt ?? null,\n baseCount: toCount(row.base_count),\n indexedCount: toCount(row.indexed_count),\n vectorIndexedCount: toCount(row.vector_indexed_count),\n }\n}\n\nexport async function readCoverageSnapshots(\n db: Kysely<any>,\n batch: CoverageBatchScope\n): Promise<Map<string, CoverageSnapshot>> {\n const entityTypes = Array.from(\n new Set((batch.entityTypes ?? []).map((id) => String(id || '')).filter((id) => id.length > 0))\n )\n const result = new Map<string, CoverageSnapshot>()\n if (entityTypes.length === 0) return result\n\n const withDeleted = batch.withDeleted === true\n let query = db\n .selectFrom('entity_index_coverage' as any)\n .select([\n 'entity_type' as any,\n 'base_count' as any,\n 'indexed_count' as any,\n 'vector_indexed_count' as any,\n 'refreshed_at' as any,\n 'organization_id' as any,\n ])\n .where('entity_type' as any, 'in', entityTypes)\n .where('with_deleted' as any, '=', withDeleted)\n .orderBy('refreshed_at' as any, 'desc')\n query = batch.tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', batch.tenantId)\n query = applyOrganizationCondition(query as any, 'organization_id', batch.organizationId ?? null)\n\n const rows = await query.execute() as Array<CoverageRow & { entity_type: string }>\n for (const row of rows ?? []) {\n const entityType = String(row.entity_type || '')\n // Rows are ordered by refreshed_at desc, so the first row seen per entity is the latest.\n if (!entityType || result.has(entityType)) continue\n const refreshedAt = row.refreshed_at instanceof Date\n ? row.refreshed_at\n : (row.refreshed_at ? new Date(row.refreshed_at) : null)\n result.set(entityType, {\n base_count: row.base_count,\n indexed_count: row.indexed_count,\n vector_indexed_count: row.vector_indexed_count,\n refreshed_at: refreshedAt ?? null,\n baseCount: toCount(row.base_count),\n indexedCount: toCount(row.indexed_count),\n vectorIndexedCount: toCount(row.vector_indexed_count),\n })\n }\n return result\n}\n\nexport async function applyCoverageAdjustments(\n em: EntityManager,\n adjustments: CoverageAdjustment[],\n options?: { trx?: CoverageExecutor },\n): Promise<void> {\n if (!adjustments.length) return\n const db = (em as any).getKysely() as Kysely<any>\n // `em.getKysely()` hands back the EntityManager's transaction context whenever one is open,\n // and Kysely's `Transaction` throws rather than nesting a second one. A caller already inside\n // `em.transactional(...)` therefore gets the same guarantee the rowless nullable-tenant branch\n // opens a transaction for, so use the ambient one instead of asking for another.\n const ambientTrx = (db as { isTransaction?: boolean }).isTransaction === true\n ? (db as CoverageExecutor)\n : null\n // Keep scope initialization in a stable order. A caller-supplied transaction retains\n // advisory and unique-index locks until commit, so two batches that initialize the same\n // scopes in opposite orders could otherwise deadlock.\n const aggregated = aggregateAdjustments(adjustments).sort((left, right) => (\n scopeKey(left.scope).localeCompare(scopeKey(right.scope))\n ))\n const executor = options?.trx ?? ambientTrx\n for (const entry of aggregated) {\n const deltas = {\n deltaBase: entry.deltaBase,\n deltaIndex: entry.deltaIndex,\n deltaVector: entry.deltaVector,\n }\n if (executor) {\n await incrementCoverageRow(executor, entry.scope, deltas)\n } else if (entry.scope.tenantId == null) {\n await db.transaction().execute((trx) => incrementCoverageRow(trx, entry.scope, deltas))\n } else {\n await incrementCoverageRow(db, entry.scope, deltas)\n }\n }\n}\n\nexport async function deleteCoverageForEntity(db: Kysely<any>, entityType: string): Promise<void> {\n if (!entityType) return\n await db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', entityType)\n .execute()\n}\n\nasync function deleteCoverageScope(db: Kysely<any>, scope: CoverageScope): Promise<void> {\n const { entityType, tenantId, organizationId, withDeleted } = scope\n if (!entityType) return\n let query = db\n .deleteFrom('entity_index_coverage' as any)\n .where('entity_type' as any, '=', entityType)\n .where('with_deleted' as any, '=', withDeleted === true)\n query = tenantId == null\n ? query.where('tenant_id' as any, 'is', null as any)\n : query.where('tenant_id' as any, '=', tenantId)\n await applyOrganizationCondition(query as any, 'organization_id', organizationId ?? null).execute()\n}\n\nasync function tableHasColumn(db: Kysely<any>, table: string, column: string): Promise<boolean> {\n const key = `${table}.${column}`\n if (COLUMN_CACHE.has(key)) return COLUMN_CACHE.get(key)!\n const pending = COLUMN_CACHE_PENDING.get(key)\n if (pending) return pending\n const promise = (async () => {\n const exists = await db\n .selectFrom('information_schema.columns' as any)\n .select(sql<number>`1`.as('present'))\n .where(sql<boolean>`table_schema = current_schema()`)\n .where('table_name' as any, '=', table)\n .where('column_name' as any, '=', column)\n .executeTakeFirst()\n const present = !!exists\n COLUMN_CACHE.set(key, present)\n return present\n })()\n COLUMN_CACHE_PENDING.set(key, promise)\n try {\n return await promise\n } finally {\n COLUMN_CACHE_PENDING.delete(key)\n }\n}\n\nexport type ColumnCheck = { table: string; column: string }\n\n// Batches the `information_schema.columns` introspection used by `refreshCoverageSnapshot`\n// into a single query for a whole set of (table, column) pairs, and pre-populates\n// `COLUMN_CACHE_PENDING` for every pair before that query even runs. Callers of\n// `coverage_warmup.ts` use this so its many concurrently-dispatched `coverage.refresh`\n// subscribers hit an already-primed (or in-flight) cache instead of each doing their own\n// per-table introspection round trip.\nexport async function primeColumnCache(db: Kysely<any>, checks: ColumnCheck[]): Promise<void> {\n const missing: Array<{ table: string; column: string; key: string }> = []\n const seen = new Set<string>()\n for (const check of checks) {\n const table = String(check?.table || '')\n const column = String(check?.column || '')\n if (!table || !column) continue\n const key = `${table}.${column}`\n if (seen.has(key)) continue\n seen.add(key)\n if (COLUMN_CACHE.has(key) || COLUMN_CACHE_PENDING.has(key)) continue\n missing.push({ table, column, key })\n }\n if (!missing.length) return\n\n const tables = Array.from(new Set(missing.map((entry) => entry.table)))\n const columns = Array.from(new Set(missing.map((entry) => entry.column)))\n\n const batchPromise = (async (): Promise<Set<string>> => {\n const rows = await db\n .selectFrom('information_schema.columns' as any)\n .select(['table_name' as any, 'column_name' as any])\n .where(sql<boolean>`table_schema = current_schema()`)\n .where('table_name' as any, 'in', tables)\n .where('column_name' as any, 'in', columns)\n .execute() as Array<{ table_name: string; column_name: string }>\n return new Set(rows.map((row) => `${row.table_name}.${row.column_name}`))\n })()\n\n for (const entry of missing) {\n const entryPromise = batchPromise.then((present) => {\n const value = present.has(entry.key)\n COLUMN_CACHE.set(entry.key, value)\n return value\n })\n // Mark the stored promise as handled: when the batch query fails and no\n // `tableHasColumn` caller has adopted this entry yet (the common case \u2014 the warmup\n // awaits priming before dispatching any refresh), an orphaned rejection would\n // otherwise crash a plain-Node event worker via unhandledRejection. Awaiting\n // callers still observe the rejection through the stored reference.\n entryPromise.catch(() => undefined)\n COLUMN_CACHE_PENDING.set(entry.key, entryPromise)\n }\n\n try {\n await batchPromise\n } finally {\n for (const entry of missing) COLUMN_CACHE_PENDING.delete(entry.key)\n }\n}\n\nexport async function refreshCoverageSnapshot(\n em: EntityManager,\n scope: CoverageScope,\n): Promise<{ baseCount: number; indexedCount: number } | null> {\n const entityType = String(scope.entityType || '')\n if (!entityType) return null\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n const withDeleted = scope.withDeleted === true\n\n const db = (em as any).getKysely() as Kysely<any>\n const baseTable = resolveEntityTableName(em, entityType)\n\n const hasOrg = await tableHasColumn(db, baseTable, 'organization_id')\n const hasTenant = await tableHasColumn(db, baseTable, 'tenant_id')\n const hasDeleted = await tableHasColumn(db, baseTable, 'deleted_at')\n\n // A scope the base table cannot express must not narrow the index side either. Index rows\n // can carry an organization the base table has no column for \u2014 `organizations` has no\n // `organization_id` yet its index rows derive one from the record id. Filtering only the\n // index side compares two different populations and reports a gap no reindex can close;\n // returning early instead of recounting left the previous snapshot frozen, which is what\n // surfaced as a permanent \"out of sync\" row for `directory:organization`.\n //\n // Tenant is different: a base table without `tenant_id` (`user_roles`) cannot be counted\n // per tenant at all, and writing the cross-tenant total into one tenant's row would leak\n // another tenant's volume into it. Drop the unusable scoped row instead, leaving only the\n // global row \u2014 which is the one that can be true \u2014 rather than freezing a stale count.\n const scopeOrg = organizationId !== null && hasOrg\n if (tenantId !== null && !hasTenant) {\n await deleteCoverageScope(db, { entityType, tenantId, organizationId, withDeleted })\n return null\n }\n const scopeTenant = tenantId !== null && hasTenant\n\n let baseQuery = db\n .selectFrom(`${baseTable} as b` as any)\n .select(sql`count(*)`.as('count'))\n if (scopeOrg) baseQuery = baseQuery.where('b.organization_id' as any, '=', organizationId)\n if (scopeTenant) baseQuery = baseQuery.where('b.tenant_id' as any, '=', tenantId)\n if (!withDeleted && hasDeleted) baseQuery = baseQuery.where('b.deleted_at' as any, 'is', null as any)\n\n let indexQuery = db\n .selectFrom('entity_indexes as ei' as any)\n .select(sql`count(*)`.as('count'))\n .where('ei.entity_type' as any, '=', entityType)\n if (scopeOrg) indexQuery = indexQuery.where('ei.organization_id' as any, '=', organizationId)\n if (scopeTenant) indexQuery = indexQuery.where('ei.tenant_id' as any, '=', tenantId)\n if (!withDeleted) indexQuery = indexQuery.where('ei.deleted_at' as any, 'is', null as any)\n\n const vectorCountPromise = (async (): Promise<number | undefined> => {\n const hasVectorTable = await tableHasColumn(db, 'vector_search', 'entity_id')\n if (!hasVectorTable || typeof tenantId !== 'string' || tenantId.length === 0) return undefined\n\n try {\n let vectorQuery = db\n .selectFrom('vector_search' as any)\n .select(sql`count(*)`.as('count'))\n .where('entity_id' as any, '=', entityType)\n .where('tenant_id' as any, '=', tenantId)\n if (organizationId !== null) {\n vectorQuery = vectorQuery.where('organization_id' as any, '=', organizationId)\n }\n const vectorRow = await vectorQuery.executeTakeFirst() as { count: unknown } | undefined\n return toCount(vectorRow?.count)\n } catch (err) {\n logger.warn('Failed to resolve vector count for coverage snapshot', {\n entityType,\n tenantId,\n organizationId,\n error: err instanceof Error ? err.message : err,\n })\n return undefined\n }\n })()\n\n const [baseRow, indexRow, vectorCount] = await Promise.all([\n baseQuery.executeTakeFirst() as Promise<{ count: unknown } | undefined>,\n indexQuery.executeTakeFirst() as Promise<{ count: unknown } | undefined>,\n vectorCountPromise,\n ])\n\n const baseCount = toCount(baseRow?.count)\n const indexCount = toCount(indexRow?.count)\n\n await writeCoverageCounts(em, { entityType, tenantId, organizationId, withDeleted }, {\n baseCount,\n indexedCount: indexCount,\n vectorCount,\n })\n\n return { baseCount, indexedCount: indexCount }\n}\n\nexport async function writeCoverageCounts(\n em: EntityManager,\n scope: CoverageScope,\n counts: { baseCount?: number; indexedCount?: number; vectorCount?: number }\n): Promise<void> {\n const entityType = String(scope.entityType || '')\n if (!entityType) return\n const db = (em as any).getKysely() as Kysely<any>\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n const withDeleted = scope.withDeleted === true\n const existing = await fetchCoverageRow(db, {\n entityType,\n tenantId,\n organizationId,\n withDeleted,\n })\n const baseCount = counts.baseCount !== undefined\n ? Math.max(0, Math.trunc(toCount(counts.baseCount)))\n : Math.max(0, Math.trunc(toCount(existing?.base_count)))\n const indexCount = counts.indexedCount !== undefined\n ? Math.max(0, Math.trunc(toCount(counts.indexedCount)))\n : Math.max(0, Math.trunc(toCount(existing?.indexed_count)))\n const vectorCount = counts.vectorCount !== undefined\n ? Math.max(0, Math.trunc(toCount(counts.vectorCount)))\n : Math.max(0, Math.trunc(toCount(existing?.vector_indexed_count)))\n await upsertCoverageRow(db, { entityType, tenantId, organizationId, withDeleted }, {\n baseCount,\n indexedCount: indexCount,\n vectorIndexedCount: vectorCount,\n })\n}\n\ntype AggregatedAdjustment = {\n scope: CoverageScope\n deltaBase: number\n deltaIndex: number\n deltaVector: number\n}\n\nfunction aggregateAdjustments(adjustments: CoverageAdjustment[]): AggregatedAdjustment[] {\n const map = new Map<string, AggregatedAdjustment>()\n for (const adj of adjustments) {\n if (!adj?.entityType) continue\n const deltaBase = Number.isFinite(adj.deltaBase) ? adj.deltaBase : 0\n const deltaIndex = Number.isFinite(adj.deltaIndex) ? adj.deltaIndex : 0\n const deltaVector = Number.isFinite(adj.deltaVector) ? adj.deltaVector! : 0\n if (deltaBase === 0 && deltaIndex === 0 && deltaVector === 0) continue\n const scope: CoverageScope = {\n entityType: adj.entityType,\n tenantId: adj.tenantId ?? null,\n organizationId: adj.organizationId ?? null,\n withDeleted: adj.withDeleted === true,\n }\n const key = scopeKey(scope)\n const existing = map.get(key)\n if (existing) {\n existing.deltaBase += deltaBase\n existing.deltaIndex += deltaIndex\n existing.deltaVector += deltaVector\n } else {\n map.set(key, { scope, deltaBase, deltaIndex, deltaVector })\n }\n }\n return Array.from(map.values())\n}\n\nfunction scopeKey(scope: CoverageScope): string {\n const tenant = scope.tenantId ?? '__tenant_null__'\n const org = normalizeOrganizationForStore(scope.organizationId ?? null)\n const deleted = scope.withDeleted === true ? '1' : '0'\n return `${scope.entityType}|${tenant}|${org}|${deleted}`\n}\n\nexport function createCoverageAdjustments(input: CoverageDeltaInput): CoverageAdjustment[] {\n const entityType = String(input.entityType || '')\n if (!entityType) return []\n const baseDelta = Number.isFinite(input.baseDelta) ? input.baseDelta : 0\n const indexDelta = Number.isFinite(input.indexDelta) ? input.indexDelta : 0\n const vectorDelta = Number.isFinite(input.vectorDelta) ? input.vectorDelta! : 0\n if (baseDelta === 0 && indexDelta === 0 && vectorDelta === 0) return []\n const withDeleted = input.withDeleted === true\n const tenantId = input.tenantId ?? null\n const organizationId = input.organizationId ?? null\n return [\n {\n entityType,\n tenantId,\n organizationId,\n withDeleted,\n deltaBase: baseDelta,\n deltaIndex: indexDelta,\n deltaVector: vectorDelta,\n },\n ]\n}\n"],
5
+ "mappings": "AACA,SAAwC,WAAW;AACnD,SAAS,8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S,SAAS,OAA8B;AAC9C,QAAM,SAAS,MAAM,YAAY;AACjC,QAAM,MAAM,8BAA8B,MAAM,kBAAkB,IAAI;AACtE,QAAM,UAAU,MAAM,gBAAgB,OAAO,MAAM;AACnD,SAAO,GAAG,MAAM,UAAU,IAAI,MAAM,IAAI,GAAG,IAAI,OAAO;AACxD;AAEO,SAAS,0BAA0B,OAAiD;AACzF,QAAM,aAAa,OAAO,MAAM,cAAc,EAAE;AAChD,MAAI,CAAC,WAAY,QAAO,CAAC;AACzB,QAAM,YAAY,OAAO,SAAS,MAAM,SAAS,IAAI,MAAM,YAAY;AACvE,QAAM,aAAa,OAAO,SAAS,MAAM,UAAU,IAAI,MAAM,aAAa;AAC1E,QAAM,cAAc,OAAO,SAAS,MAAM,WAAW,IAAI,MAAM,cAAe;AAC9E,MAAI,cAAc,KAAK,eAAe,KAAK,gBAAgB,EAAG,QAAO,CAAC;AACtE,QAAM,cAAc,MAAM,gBAAgB;AAC1C,QAAM,WAAW,MAAM,YAAY;AACnC,QAAM,iBAAiB,MAAM,kBAAkB;AAC/C,SAAO;AAAA,IACL;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,aAAa;AAAA,IACf;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/query_index/subscribers/delete_one.ts"],
4
- "sourcesContent": ["import { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { sql } from 'kysely'\nimport { markDeleted } from '../lib/indexer'\nimport { applyCoverageAdjustments, createCoverageAdjustments } from '../lib/coverage'\nimport {\n loadQueryIndexRowScope,\n resolveQueryIndexRecordScope,\n resolveQueryIndexSourceMetadata,\n} from '../lib/subscriber-scope'\n\nexport const metadata = { event: 'query_index.delete_one', persistent: false }\n\n// Mirrors `shouldTriggerCoverageRefresh()` in `@open-mercato/shared/lib/data/engine.ts`\n// as a small local throttle so per-record deletes stop firing an unconditional, immediate\n// full recount. Note: this Map and the shared engine's own throttle Map are independent,\n// so a rare race right after a 5-minute window resets on both could double-fire once \u2014\n// harmless (the recompute is idempotent) and far cheaper than today's per-delete cost.\nconst DELETE_COVERAGE_THROTTLE_MS = 5 * 60 * 1000\nconst lastDeleteCoverageRefreshAt = new Map<string, number>()\n\nfunction shouldAllowDeleteCoverageRefresh(entityType: string, tenantId: string | null): boolean {\n if (!entityType) return false\n const key = `${entityType}|${tenantId ?? '__null__'}`\n const now = Date.now()\n const last = lastDeleteCoverageRefreshAt.get(key) ?? 0\n if (now - last < DELETE_COVERAGE_THROTTLE_MS) return false\n lastDeleteCoverageRefreshAt.set(key, now)\n return true\n}\n\nexport default async function handle(payload: any, ctx: { resolve: <T=any>(name: string) => T }) {\n // Forked EntityManager \u2014 this awaited subscriber runs synchronously on the request\n // `em`; isolating it prevents our queries/writes from resetting the originating CRUD\n // write's UnitOfWork and dropping its pending changes. See upsert_one.ts for detail.\n const baseEm = ctx.resolve<any>('em')\n const em = typeof baseEm?.fork === 'function' ? baseEm.fork() : baseEm\n const entityType = String(payload?.entityType || '')\n const recordId = String(payload?.recordId || '')\n if (!entityType || !recordId) return\n let organizationId: string | null = payload?.organizationId ?? null\n let tenantId: string | null = payload?.tenantId ?? null\n const suppressCoverage = payload?.suppressCoverage === true\n const coverageDelayMs = typeof payload?.coverageDelayMs === 'number' ? payload.coverageDelayMs : undefined\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n try {\n const hasPayloadOrganizationId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'organizationId')\n const hasPayloadTenantId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'tenantId')\n const source = resolveQueryIndexSourceMetadata(em, entityType)\n const sourceScope = await loadQueryIndexRowScope(em, source, recordId)\n const resolvedScope = resolveQueryIndexRecordScope({\n payloadOrganizationId: payload?.organizationId,\n payloadTenantId: payload?.tenantId,\n hasPayloadOrganizationId,\n hasPayloadTenantId,\n sourceScope,\n })\n organizationId = resolvedScope.organizationId\n tenantId = resolvedScope.tenantId\n\n if (alwaysConsistent) {\n const db = (em as any).getKysely()\n await db.transaction().execute(async (trx: any) => {\n const { wasActive } = await markDeleted(em, { entityType, recordId, organizationId, tenantId, trx })\n\n let baseQuery = trx\n .selectFrom(source.table as any)\n .select(['deleted_at' as any])\n .where('id' as any, '=', recordId)\n if (source.organizationColumn) {\n baseQuery = baseQuery.where(\n source.organizationColumn as any,\n organizationId === null ? 'is' : '=',\n organizationId as any,\n )\n }\n if (source.tenantColumn) {\n baseQuery = baseQuery.where(sql`${sql.ref(source.tenantColumn)} is not distinct from ${tenantId}`)\n }\n const row = await baseQuery.executeTakeFirst() as { deleted_at: Date | null } | undefined\n const baseDelta = !row || row.deleted_at != null ? -1 : 0\n\n const baseDeltaOverride =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n const indexDeltaOverride =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n let effectiveBaseDelta = baseDeltaOverride ?? baseDelta\n let effectiveIndexDelta = indexDeltaOverride ?? (wasActive ? -1 : 0)\n\n if (!Number.isFinite(effectiveBaseDelta)) effectiveBaseDelta = 0\n if (!Number.isFinite(effectiveIndexDelta)) effectiveIndexDelta = 0\n\n if (effectiveBaseDelta !== 0 || effectiveIndexDelta !== 0) {\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta: effectiveBaseDelta,\n indexDelta: effectiveIndexDelta,\n })\n if (adjustments.length) {\n await applyCoverageAdjustments(em, adjustments, { trx })\n }\n }\n })\n\n const bus = ctx.resolve<any>('eventBus')\n const shouldRefreshCoverage =\n !suppressCoverage && (coverageDelayMs === undefined || coverageDelayMs >= 0)\n const coverageRefreshDelay = coverageDelayMs ?? 0\n if (shouldRefreshCoverage) {\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageRefreshDelay,\n }, { rethrowHandlerErrors: true })\n }\n await bus.emitEvent('search.delete_record', { entityId: entityType, recordId, organizationId, tenantId }, { rethrowHandlerErrors: true })\n return\n }\n\n const { wasActive } = await markDeleted(em, { entityType, recordId, organizationId, tenantId })\n\n let baseDelta = 0\n let baseCheckSucceeded = false\n try {\n const db = (em as any).getKysely()\n let baseQuery = db\n .selectFrom(source.table as any)\n .select(['deleted_at' as any])\n .where('id' as any, '=', recordId)\n if (source.organizationColumn) {\n baseQuery = baseQuery.where(\n source.organizationColumn as any,\n organizationId === null ? 'is' : '=',\n organizationId as any,\n )\n }\n if (source.tenantColumn) {\n baseQuery = baseQuery.where(sql`${sql.ref(source.tenantColumn)} is not distinct from ${tenantId}`)\n }\n const row = await baseQuery.executeTakeFirst() as { deleted_at: Date | null } | undefined\n const baseMissing = !row\n const baseDeleted = baseMissing || (row && row.deleted_at != null)\n baseCheckSucceeded = true\n if (baseDeleted) baseDelta = -1\n } catch {}\n if (!baseCheckSucceeded) baseDelta = -1\n\n const baseDeltaOverride =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n const indexDeltaOverride =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n let effectiveBaseDelta = baseDeltaOverride ?? baseDelta\n let effectiveIndexDelta = indexDeltaOverride ?? (wasActive ? -1 : 0)\n\n if (!Number.isFinite(effectiveBaseDelta)) effectiveBaseDelta = 0\n if (!Number.isFinite(effectiveIndexDelta)) effectiveIndexDelta = 0\n\n if (effectiveBaseDelta !== 0 || effectiveIndexDelta !== 0) {\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta: effectiveBaseDelta,\n indexDelta: effectiveIndexDelta,\n })\n if (adjustments.length) {\n await applyCoverageAdjustments(em, adjustments)\n }\n }\n\n // The projection row + token removal above are synchronous (the data engine\n // awaits this subscriber) so list reads are consistent immediately. The coverage\n // recompute (a COUNT, run inline when delayMs is 0) and the fulltext delete are\n // secondary, so defer them fire-and-forget to keep write/bulk-delete latency bounded.\n const explicitDelayRequested = typeof payload?.coverageDelayMs === 'number'\n const shouldRefreshCoverage =\n !suppressCoverage &&\n (coverageDelayMs === undefined || coverageDelayMs >= 0) &&\n (explicitDelayRequested || shouldAllowDeleteCoverageRefresh(entityType, tenantId))\n const coverageRefreshDelay = coverageDelayMs ?? 0\n void (async () => {\n try {\n const bus = ctx.resolve<any>('eventBus')\n if (shouldRefreshCoverage) {\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageRefreshDelay,\n })\n }\n await bus.emitEvent('search.delete_record', { entityId: entityType, recordId, organizationId, tenantId })\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.delete_one:coverage_search',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n ).catch(() => {})\n }\n })()\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.delete_one',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n )\n throw error\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,0BAA0B;AACnC,SAAS,wCAAwC;AACjD,SAAS,WAAW;AACpB,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B,iCAAiC;AACpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW,EAAE,OAAO,0BAA0B,YAAY,MAAM;AAO7E,MAAM,8BAA8B,IAAI,KAAK;AAC7C,MAAM,8BAA8B,oBAAI,IAAoB;AAE5D,SAAS,iCAAiC,YAAoB,UAAkC;AAC9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MACL;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA,UAAU,YAAY;AAAA,QACtB,gBAAgB,kBAAkB;AAAA,QAClC;AAAA,MACF;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["import { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { sql } from 'kysely'\nimport { markDeleted } from '../lib/indexer'\nimport { applyCoverageAdjustments, createCoverageAdjustments } from '../lib/coverage'\nimport {\n loadQueryIndexRowScope,\n resolveQueryIndexRecordScope,\n resolveQueryIndexSourceMetadata,\n} from '../lib/subscriber-scope'\n\nexport const metadata = { event: 'query_index.delete_one', persistent: false }\n\n// Mirrors `shouldTriggerCoverageRefresh()` in `@open-mercato/shared/lib/data/engine.ts`\n// as a small local throttle so per-record deletes stop firing an unconditional, immediate\n// full recount. Note: this Map and the shared engine's own throttle Map are independent,\n// so a rare race right after a 5-minute window resets on both could double-fire once \u2014\n// harmless (the recompute is idempotent) and far cheaper than today's per-delete cost.\nconst DELETE_COVERAGE_THROTTLE_MS = 5 * 60 * 1000\nconst lastDeleteCoverageRefreshAt = new Map<string, number>()\n\nfunction shouldAllowDeleteCoverageRefresh(entityType: string, tenantId: string | null): boolean {\n if (!entityType) return false\n const key = `${entityType}|${tenantId ?? '__null__'}`\n const now = Date.now()\n const last = lastDeleteCoverageRefreshAt.get(key) ?? 0\n if (now - last < DELETE_COVERAGE_THROTTLE_MS) return false\n lastDeleteCoverageRefreshAt.set(key, now)\n return true\n}\n\nexport default async function handle(payload: any, ctx: { resolve: <T=any>(name: string) => T }) {\n // Forked EntityManager \u2014 this awaited subscriber runs synchronously on the request\n // `em`; isolating it prevents our queries/writes from resetting the originating CRUD\n // write's UnitOfWork and dropping its pending changes. See upsert_one.ts for detail.\n const baseEm = ctx.resolve<any>('em')\n const em = typeof baseEm?.fork === 'function' ? baseEm.fork() : baseEm\n const entityType = String(payload?.entityType || '')\n const recordId = String(payload?.recordId || '')\n if (!entityType || !recordId) return\n let organizationId: string | null = payload?.organizationId ?? null\n let tenantId: string | null = payload?.tenantId ?? null\n const suppressCoverage = payload?.suppressCoverage === true\n const coverageDelayMs = typeof payload?.coverageDelayMs === 'number' ? payload.coverageDelayMs : undefined\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n try {\n const hasPayloadOrganizationId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'organizationId')\n const hasPayloadTenantId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'tenantId')\n const source = resolveQueryIndexSourceMetadata(em, entityType)\n const sourceScope = await loadQueryIndexRowScope(em, source, recordId)\n const resolvedScope = resolveQueryIndexRecordScope({\n payloadOrganizationId: payload?.organizationId,\n payloadTenantId: payload?.tenantId,\n hasPayloadOrganizationId,\n hasPayloadTenantId,\n sourceScope,\n })\n organizationId = resolvedScope.organizationId\n tenantId = resolvedScope.tenantId\n\n if (alwaysConsistent) {\n const db = (em as any).getKysely()\n await db.transaction().execute(async (trx: any) => {\n const { wasActive } = await markDeleted(em, { entityType, recordId, organizationId, tenantId, trx })\n\n let baseQuery = trx\n .selectFrom(source.table as any)\n .select(['deleted_at' as any])\n .where('id' as any, '=', recordId)\n if (source.organizationColumn) {\n baseQuery = baseQuery.where(\n source.organizationColumn as any,\n organizationId === null ? 'is' : '=',\n organizationId as any,\n )\n }\n if (source.tenantColumn) {\n baseQuery = baseQuery.where(sql`${sql.ref(source.tenantColumn)} is not distinct from ${tenantId}`)\n }\n const row = await baseQuery.executeTakeFirst() as { deleted_at: Date | null } | undefined\n const baseDelta = !row || row.deleted_at != null ? -1 : 0\n\n const baseDeltaOverride =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n const indexDeltaOverride =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n let effectiveBaseDelta = baseDeltaOverride ?? baseDelta\n let effectiveIndexDelta = indexDeltaOverride ?? (wasActive ? -1 : 0)\n\n if (!Number.isFinite(effectiveBaseDelta)) effectiveBaseDelta = 0\n if (!Number.isFinite(effectiveIndexDelta)) effectiveIndexDelta = 0\n\n if (effectiveBaseDelta !== 0 || effectiveIndexDelta !== 0) {\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta: effectiveBaseDelta,\n indexDelta: effectiveIndexDelta,\n })\n if (adjustments.length) {\n // Stays inside the transaction: `alwaysConsistent` exists to make the read\n // projection and its coverage counters commit together, and the adjustment is a\n // one incrementing statement in steady state (see `applyCoverageAdjustments`), so\n // it holds the coverage row's lock only for that statement.\n await applyCoverageAdjustments(em, adjustments, { trx })\n }\n }\n })\n\n const bus = ctx.resolve<any>('eventBus')\n const shouldRefreshCoverage =\n !suppressCoverage && (coverageDelayMs === undefined || coverageDelayMs >= 0)\n const coverageRefreshDelay = coverageDelayMs ?? 0\n if (shouldRefreshCoverage) {\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageRefreshDelay,\n }, { rethrowHandlerErrors: true })\n }\n await bus.emitEvent('search.delete_record', { entityId: entityType, recordId, organizationId, tenantId }, { rethrowHandlerErrors: true })\n return\n }\n\n const { wasActive } = await markDeleted(em, { entityType, recordId, organizationId, tenantId })\n\n let baseDelta = 0\n let baseCheckSucceeded = false\n try {\n const db = (em as any).getKysely()\n let baseQuery = db\n .selectFrom(source.table as any)\n .select(['deleted_at' as any])\n .where('id' as any, '=', recordId)\n if (source.organizationColumn) {\n baseQuery = baseQuery.where(\n source.organizationColumn as any,\n organizationId === null ? 'is' : '=',\n organizationId as any,\n )\n }\n if (source.tenantColumn) {\n baseQuery = baseQuery.where(sql`${sql.ref(source.tenantColumn)} is not distinct from ${tenantId}`)\n }\n const row = await baseQuery.executeTakeFirst() as { deleted_at: Date | null } | undefined\n const baseMissing = !row\n const baseDeleted = baseMissing || (row && row.deleted_at != null)\n baseCheckSucceeded = true\n if (baseDeleted) baseDelta = -1\n } catch {}\n if (!baseCheckSucceeded) baseDelta = -1\n\n const baseDeltaOverride =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n const indexDeltaOverride =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n let effectiveBaseDelta = baseDeltaOverride ?? baseDelta\n let effectiveIndexDelta = indexDeltaOverride ?? (wasActive ? -1 : 0)\n\n if (!Number.isFinite(effectiveBaseDelta)) effectiveBaseDelta = 0\n if (!Number.isFinite(effectiveIndexDelta)) effectiveIndexDelta = 0\n\n if (effectiveBaseDelta !== 0 || effectiveIndexDelta !== 0) {\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta: effectiveBaseDelta,\n indexDelta: effectiveIndexDelta,\n })\n if (adjustments.length) {\n await applyCoverageAdjustments(em, adjustments)\n }\n }\n\n // The projection row + token removal above are synchronous (the data engine\n // awaits this subscriber) so list reads are consistent immediately. The coverage\n // recompute (a COUNT, run inline when delayMs is 0) and the fulltext delete are\n // secondary, so defer them fire-and-forget to keep write/bulk-delete latency bounded.\n const explicitDelayRequested = typeof payload?.coverageDelayMs === 'number'\n const shouldRefreshCoverage =\n !suppressCoverage &&\n (coverageDelayMs === undefined || coverageDelayMs >= 0) &&\n (explicitDelayRequested || shouldAllowDeleteCoverageRefresh(entityType, tenantId))\n const coverageRefreshDelay = coverageDelayMs ?? 0\n void (async () => {\n try {\n const bus = ctx.resolve<any>('eventBus')\n if (shouldRefreshCoverage) {\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageRefreshDelay,\n })\n }\n await bus.emitEvent('search.delete_record', { entityId: entityType, recordId, organizationId, tenantId })\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.delete_one:coverage_search',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n ).catch(() => {})\n }\n })()\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.delete_one',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n )\n throw error\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,0BAA0B;AACnC,SAAS,wCAAwC;AACjD,SAAS,WAAW;AACpB,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B,iCAAiC;AACpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW,EAAE,OAAO,0BAA0B,YAAY,MAAM;AAO7E,MAAM,8BAA8B,IAAI,KAAK;AAC7C,MAAM,8BAA8B,oBAAI,IAAoB;AAE5D,SAAS,iCAAiC,YAAoB,UAAkC;AAC9F,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,MAAM,GAAG,UAAU,IAAI,YAAY,UAAU;AACnD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,OAAO,4BAA4B,IAAI,GAAG,KAAK;AACrD,MAAI,MAAM,OAAO,4BAA6B,QAAO;AACrD,8BAA4B,IAAI,KAAK,GAAG;AACxC,SAAO;AACT;AAEA,eAAO,OAA8B,SAAc,KAA8C;AAI/F,QAAM,SAAS,IAAI,QAAa,IAAI;AACpC,QAAM,KAAK,OAAO,QAAQ,SAAS,aAAa,OAAO,KAAK,IAAI;AAChE,QAAM,aAAa,OAAO,SAAS,cAAc,EAAE;AACnD,QAAM,WAAW,OAAO,SAAS,YAAY,EAAE;AAC/C,MAAI,CAAC,cAAc,CAAC,SAAU;AAC9B,MAAI,iBAAgC,SAAS,kBAAkB;AAC/D,MAAI,WAA0B,SAAS,YAAY;AACnD,QAAM,mBAAmB,SAAS,qBAAqB;AACvD,QAAM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I;AACF,cAAM,MAAM,IAAI,QAAa,UAAU;AACvC,YAAI,uBAAuB;AACzB,gBAAM,IAAI,UAAU,gCAAgC;AAAA,YAClD;AAAA,YACA,UAAU,YAAY;AAAA,YACtB,gBAAgB,kBAAkB;AAAA,YAClC,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AACA,cAAM,IAAI,UAAU,wBAAwB,EAAE,UAAU,YAAY,UAAU,gBAAgB,SAAS,CAAC;AAAA,MAC1G,SAAS,OAAO;AACd,cAAM;AAAA,UACJ,EAAE,GAAG;AAAA,UACL;AAAA,YACE,QAAQ;AAAA,YACR,SAAS;AAAA,YACT;AAAA,YACA;AAAA,YACA;AAAA,YACA,UAAU,YAAY;AAAA,YACtB,gBAAgB,kBAAkB;AAAA,YAClC;AAAA,UACF;AAAA,QACF,EAAE,MAAM,MAAM;AAAA,QAAC,CAAC;AAAA,MAClB;AAAA,IACF,GAAG;AAAA,EACL,SAAS,OAAO;AACd,UAAM;AAAA,MACJ,EAAE,GAAG;AAAA,MACL;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA,UAAU,YAAY;AAAA,QACtB,gBAAgB,kBAAkB;AAAA,QAClC;AAAA,MACF;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACF;",
6
6
  "names": ["wasActive", "baseDelta", "baseDeltaOverride", "indexDeltaOverride", "effectiveBaseDelta", "effectiveIndexDelta", "shouldRefreshCoverage", "coverageRefreshDelay"]
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/query_index/subscribers/upsert_one.ts"],
4
- "sourcesContent": ["import { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { upsertIndexRow, reindexSearchTokensForRecord, type UpsertIndexResult } from '../lib/indexer'\nimport { applyCoverageAdjustments, createCoverageAdjustments } from '../lib/coverage'\nimport {\n loadQueryIndexRowScope,\n resolveQueryIndexRecordScope,\n resolveQueryIndexSourceMetadata,\n} from '../lib/subscriber-scope'\n\nexport const metadata = { event: 'query_index.upsert_one', persistent: false }\n\nexport default async function handle(payload: any, ctx: { resolve: <T=any>(name: string) => T }) {\n // Run index maintenance on a FORKED EntityManager (fresh identity map + UnitOfWork)\n // so it can never disturb the originating CRUD write's `em`. The data engine awaits\n // this emit for read-your-writes consistency, which means the subscriber runs\n // synchronously on the request `em`; sharing it would let our `em.find` / raw\n // `getKysely()` queries reset the caller's UoW change-tracking and silently drop the\n // caller's pending write (e.g. the deal's `setCustomFields` insert). The fork reads\n // the same committed DB rows via the shared connection but keeps its own UoW.\n const baseEm = ctx.resolve<any>('em')\n const em = typeof baseEm?.fork === 'function' ? baseEm.fork() : baseEm\n const entityType = String(payload?.entityType || '')\n const recordId = String(payload?.recordId || '')\n if (!entityType || !recordId) return\n let organizationId: string | null = payload?.organizationId ?? null\n let tenantId: string | null = payload?.tenantId ?? null\n const suppressCoverage = payload?.suppressCoverage === true\n const coverageDelayMs = typeof payload?.coverageDelayMs === 'number' ? payload.coverageDelayMs : undefined\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n try {\n const hasPayloadOrganizationId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'organizationId')\n const hasPayloadTenantId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'tenantId')\n const source = resolveQueryIndexSourceMetadata(em, entityType)\n const sourceScope = await loadQueryIndexRowScope(em, source, recordId)\n const resolvedScope = resolveQueryIndexRecordScope({\n payloadOrganizationId: payload?.organizationId,\n payloadTenantId: payload?.tenantId,\n hasPayloadOrganizationId,\n hasPayloadTenantId,\n sourceScope,\n })\n organizationId = resolvedScope.organizationId\n tenantId = resolvedScope.tenantId\n\n const searchTokenDoc = typeof payload?.searchTokenDoc === 'object' && payload.searchTokenDoc && !Array.isArray(payload.searchTokenDoc)\n ? (payload.searchTokenDoc as Record<string, unknown>)\n : null\n if (alwaysConsistent) {\n const db = (em as any).getKysely()\n let result: UpsertIndexResult | null = null\n await db.transaction().execute(async (trx: any) => {\n result = await upsertIndexRow(em, {\n entityType,\n recordId,\n organizationId,\n tenantId,\n searchTokenDoc,\n deferSearchTokens: false,\n trx,\n })\n if (!suppressCoverage) {\n const doc = result.doc\n const isActive = !!doc && (doc.deleted_at == null || doc.deleted_at === null)\n let baseDelta: number | undefined =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n let indexDelta: number | undefined =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n const crudAction = typeof payload?.crudAction === 'string' ? payload.crudAction : undefined\n\n if (baseDelta === undefined) {\n if (result.revived) baseDelta = 1\n else if (crudAction === 'created') baseDelta = 1\n else baseDelta = 0\n }\n\n if (indexDelta === undefined) {\n if (isActive && (result.created || result.revived)) indexDelta = 1\n else indexDelta = 0\n }\n\n if (!isActive && baseDelta > 0) baseDelta = 0\n if (!isActive && indexDelta > 0) indexDelta = 0\n if (!Number.isFinite(baseDelta)) baseDelta = 0\n if (!Number.isFinite(indexDelta)) indexDelta = 0\n\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta,\n indexDelta,\n })\n if (adjustments.length) {\n await applyCoverageAdjustments(em, adjustments, { trx })\n }\n }\n })\n\n const bus = ctx.resolve<any>('eventBus')\n const eventScope = { entityType, recordId, organizationId, tenantId }\n await bus.emitEvent('query_index.vectorize_one', eventScope, { rethrowHandlerErrors: true })\n await bus.emitEvent('search.index_record', { entityId: entityType, recordId, organizationId, tenantId }, { rethrowHandlerErrors: true })\n if (!suppressCoverage && coverageDelayMs !== undefined && coverageDelayMs >= 0) {\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageDelayMs,\n }, { rethrowHandlerErrors: true })\n }\n return\n }\n // Update the projection row synchronously so list reads (`customValues`) are\n // consistent the moment the write returns; defer the heavy search-token rebuild.\n const result = await upsertIndexRow(em, {\n entityType,\n recordId,\n organizationId,\n tenantId,\n searchTokenDoc,\n deferSearchTokens: true,\n })\n if (!suppressCoverage) {\n const doc = result.doc\n const isActive = !!doc && (doc.deleted_at == null || doc.deleted_at === null)\n let baseDelta: number | undefined =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n let indexDelta: number | undefined =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n const crudAction = typeof payload?.crudAction === 'string' ? payload.crudAction : undefined\n\n if (baseDelta === undefined) {\n if (result.revived) baseDelta = 1\n else if (crudAction === 'created') baseDelta = 1\n else baseDelta = 0\n }\n\n if (indexDelta === undefined) {\n if (isActive && (result.created || result.revived)) indexDelta = 1\n else indexDelta = 0\n }\n\n if (!isActive && baseDelta > 0) baseDelta = 0\n if (!isActive && indexDelta > 0) indexDelta = 0\n if (!Number.isFinite(baseDelta)) baseDelta = 0\n if (!Number.isFinite(indexDelta)) indexDelta = 0\n\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta,\n indexDelta,\n })\n if (adjustments.length) {\n await applyCoverageAdjustments(em, adjustments)\n }\n if (coverageDelayMs !== undefined && coverageDelayMs >= 0) {\n try {\n const bus = ctx.resolve<any>('eventBus')\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageDelayMs,\n })\n } catch {}\n }\n }\n // Defer the heavy, eventually-consistent tail: search-token rebuild + vectorize +\n // fulltext indexing. The data engine awaits this subscriber for projection\n // consistency, so this work runs fire-and-forget to keep write latency bounded.\n const deferredScope = { entityType, recordId, organizationId, tenantId }\n const resolvedDoc = result.doc\n void (async () => {\n try {\n await reindexSearchTokensForRecord(em, { ...deferredScope, doc: resolvedDoc, searchTokenDoc })\n const bus = ctx.resolve<any>('eventBus')\n await bus.emitEvent('query_index.vectorize_one', deferredScope)\n await bus.emitEvent('search.index_record', { entityId: entityType, recordId, organizationId, tenantId })\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.upsert_one:search_tokens',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n ).catch(() => {})\n }\n })()\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.upsert_one',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n )\n throw error\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,0BAA0B;AACnC,SAAS,wCAAwC;AACjD,SAAS,gBAAgB,oCAA4D;AACrF,SAAS,0BAA0B,iCAAiC;AACpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW,EAAE,OAAO,0BAA0B,YAAY,MAAM;AAE7E,eAAO,OAA8B,SAAc,KAA8C;AAQ/F,QAAM,SAAS,IAAI,QAAa,IAAI;AACpC,QAAM,KAAK,OAAO,QAAQ,SAAS,aAAa,OAAO,KAAK,IAAI;AAChE,QAAM,aAAa,OAAO,SAAS,cAAc,EAAE;AACnD,QAAM,WAAW,OAAO,SAAS,YAAY,EAAE;AAC/C,MAAI,CAAC,cAAc,CAAC,SAAU;AAC9B,MAAI,iBAAgC,SAAS,kBAAkB;AAC/D,MAAI,WAA0B,SAAS,YAAY;AACnD,QAAM,mBAAmB,SAAS,qBAAqB;AACvD,QAAM,kBAAkB,OAAO,SAAS,oBAAoB,WAAW,QAAQ,kBAAkB;AACjG,QAAM,mBAAmB,iCAAiC;AAC1D,MAAI;AACF,UAAM,2BAA2B,OAAO,UAAU,eAAe,KAAK,WAAW,CAAC,GAAG,gBAAgB;AACrG,UAAM,qBAAqB,OAAO,UAAU,eAAe,KAAK,WAAW,CAAC,GAA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AE,UAAU,YAAY,UAAU,gBAAgB,SAAS,CAAC;AAAA,MACzG,SAAS,OAAO;AACd,cAAM;AAAA,UACJ,EAAE,GAAG;AAAA,UACL;AAAA,YACE,QAAQ;AAAA,YACR,SAAS;AAAA,YACT;AAAA,YACA;AAAA,YACA;AAAA,YACA,UAAU,YAAY;AAAA,YACtB,gBAAgB,kBAAkB;AAAA,YAClC;AAAA,UACF;AAAA,QACF,EAAE,MAAM,MAAM;AAAA,QAAC,CAAC;AAAA,MAClB;AAAA,IACF,GAAG;AAAA,EACL,SAAS,OAAO;AACd,UAAM;AAAA,MACJ,EAAE,GAAG;AAAA,MACL;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA,UAAU,YAAY;AAAA,QACtB,gBAAgB,kBAAkB;AAAA,QAClC;AAAA,MACF;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["import { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'\nimport { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'\nimport { upsertIndexRow, reindexSearchTokensForRecord, type UpsertIndexResult } from '../lib/indexer'\nimport { applyCoverageAdjustments, createCoverageAdjustments } from '../lib/coverage'\nimport {\n loadQueryIndexRowScope,\n resolveQueryIndexRecordScope,\n resolveQueryIndexSourceMetadata,\n} from '../lib/subscriber-scope'\n\nexport const metadata = { event: 'query_index.upsert_one', persistent: false }\n\nexport default async function handle(payload: any, ctx: { resolve: <T=any>(name: string) => T }) {\n // Run index maintenance on a FORKED EntityManager (fresh identity map + UnitOfWork)\n // so it can never disturb the originating CRUD write's `em`. The data engine awaits\n // this emit for read-your-writes consistency, which means the subscriber runs\n // synchronously on the request `em`; sharing it would let our `em.find` / raw\n // `getKysely()` queries reset the caller's UoW change-tracking and silently drop the\n // caller's pending write (e.g. the deal's `setCustomFields` insert). The fork reads\n // the same committed DB rows via the shared connection but keeps its own UoW.\n const baseEm = ctx.resolve<any>('em')\n const em = typeof baseEm?.fork === 'function' ? baseEm.fork() : baseEm\n const entityType = String(payload?.entityType || '')\n const recordId = String(payload?.recordId || '')\n if (!entityType || !recordId) return\n let organizationId: string | null = payload?.organizationId ?? null\n let tenantId: string | null = payload?.tenantId ?? null\n const suppressCoverage = payload?.suppressCoverage === true\n const coverageDelayMs = typeof payload?.coverageDelayMs === 'number' ? payload.coverageDelayMs : undefined\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n try {\n const hasPayloadOrganizationId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'organizationId')\n const hasPayloadTenantId = Object.prototype.hasOwnProperty.call(payload ?? {}, 'tenantId')\n const source = resolveQueryIndexSourceMetadata(em, entityType)\n const sourceScope = await loadQueryIndexRowScope(em, source, recordId)\n const resolvedScope = resolveQueryIndexRecordScope({\n payloadOrganizationId: payload?.organizationId,\n payloadTenantId: payload?.tenantId,\n hasPayloadOrganizationId,\n hasPayloadTenantId,\n sourceScope,\n })\n organizationId = resolvedScope.organizationId\n tenantId = resolvedScope.tenantId\n\n const searchTokenDoc = typeof payload?.searchTokenDoc === 'object' && payload.searchTokenDoc && !Array.isArray(payload.searchTokenDoc)\n ? (payload.searchTokenDoc as Record<string, unknown>)\n : null\n if (alwaysConsistent) {\n const db = (em as any).getKysely()\n let result: UpsertIndexResult | null = null\n await db.transaction().execute(async (trx: any) => {\n result = await upsertIndexRow(em, {\n entityType,\n recordId,\n organizationId,\n tenantId,\n searchTokenDoc,\n deferSearchTokens: false,\n trx,\n })\n if (!suppressCoverage) {\n const doc = result.doc\n const isActive = !!doc && (doc.deleted_at == null || doc.deleted_at === null)\n let baseDelta: number | undefined =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n let indexDelta: number | undefined =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n const crudAction = typeof payload?.crudAction === 'string' ? payload.crudAction : undefined\n\n if (baseDelta === undefined) {\n if (result.revived) baseDelta = 1\n else if (crudAction === 'created') baseDelta = 1\n else baseDelta = 0\n }\n\n if (indexDelta === undefined) {\n if (isActive && (result.created || result.revived)) indexDelta = 1\n else indexDelta = 0\n }\n\n if (!isActive && baseDelta > 0) baseDelta = 0\n if (!isActive && indexDelta > 0) indexDelta = 0\n if (!Number.isFinite(baseDelta)) baseDelta = 0\n if (!Number.isFinite(indexDelta)) indexDelta = 0\n\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta,\n indexDelta,\n })\n if (adjustments.length) {\n // Stays inside the transaction: `alwaysConsistent` exists to make the read\n // projection and its coverage counters commit together, and the adjustment is a\n // one incrementing statement in steady state (see `applyCoverageAdjustments`), so\n // it holds the coverage row's lock only for that statement.\n await applyCoverageAdjustments(em, adjustments, { trx })\n }\n }\n })\n\n const bus = ctx.resolve<any>('eventBus')\n const eventScope = { entityType, recordId, organizationId, tenantId }\n await bus.emitEvent('query_index.vectorize_one', eventScope, { rethrowHandlerErrors: true })\n await bus.emitEvent('search.index_record', { entityId: entityType, recordId, organizationId, tenantId }, { rethrowHandlerErrors: true })\n if (!suppressCoverage && coverageDelayMs !== undefined && coverageDelayMs >= 0) {\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageDelayMs,\n }, { rethrowHandlerErrors: true })\n }\n return\n }\n // Update the projection row synchronously so list reads (`customValues`) are\n // consistent the moment the write returns; defer the heavy search-token rebuild.\n const result = await upsertIndexRow(em, {\n entityType,\n recordId,\n organizationId,\n tenantId,\n searchTokenDoc,\n deferSearchTokens: true,\n })\n if (!suppressCoverage) {\n const doc = result.doc\n const isActive = !!doc && (doc.deleted_at == null || doc.deleted_at === null)\n let baseDelta: number | undefined =\n typeof payload?.coverageBaseDelta === 'number' ? payload.coverageBaseDelta : undefined\n let indexDelta: number | undefined =\n typeof payload?.coverageIndexDelta === 'number' ? payload.coverageIndexDelta : undefined\n const crudAction = typeof payload?.crudAction === 'string' ? payload.crudAction : undefined\n\n if (baseDelta === undefined) {\n if (result.revived) baseDelta = 1\n else if (crudAction === 'created') baseDelta = 1\n else baseDelta = 0\n }\n\n if (indexDelta === undefined) {\n if (isActive && (result.created || result.revived)) indexDelta = 1\n else indexDelta = 0\n }\n\n if (!isActive && baseDelta > 0) baseDelta = 0\n if (!isActive && indexDelta > 0) indexDelta = 0\n if (!Number.isFinite(baseDelta)) baseDelta = 0\n if (!Number.isFinite(indexDelta)) indexDelta = 0\n\n const adjustments = createCoverageAdjustments({\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n baseDelta,\n indexDelta,\n })\n if (adjustments.length) {\n await applyCoverageAdjustments(em, adjustments)\n }\n if (coverageDelayMs !== undefined && coverageDelayMs >= 0) {\n try {\n const bus = ctx.resolve<any>('eventBus')\n await bus.emitEvent('query_index.coverage.refresh', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n delayMs: coverageDelayMs,\n })\n } catch {}\n }\n }\n // Defer the heavy, eventually-consistent tail: search-token rebuild + vectorize +\n // fulltext indexing. The data engine awaits this subscriber for projection\n // consistency, so this work runs fire-and-forget to keep write latency bounded.\n const deferredScope = { entityType, recordId, organizationId, tenantId }\n const resolvedDoc = result.doc\n void (async () => {\n try {\n await reindexSearchTokensForRecord(em, { ...deferredScope, doc: resolvedDoc, searchTokenDoc })\n const bus = ctx.resolve<any>('eventBus')\n await bus.emitEvent('query_index.vectorize_one', deferredScope)\n await bus.emitEvent('search.index_record', { entityId: entityType, recordId, organizationId, tenantId })\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.upsert_one:search_tokens',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n ).catch(() => {})\n }\n })()\n } catch (error) {\n await recordIndexerError(\n { em },\n {\n source: 'query_index',\n handler: 'event:query_index.upsert_one',\n error,\n entityType,\n recordId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n payload,\n },\n )\n throw error\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,0BAA0B;AACnC,SAAS,wCAAwC;AACjD,SAAS,gBAAgB,oCAA4D;AACrF,SAAS,0BAA0B,iCAAiC;AACpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW,EAAE,OAAO,0BAA0B,YAAY,MAAM;AAE7E,eAAO,OAA8B,SAAc,KAA8C;AAQ/F,QAAM,SAAS,IAAI,QAAa,IAAI;AACpC,QAAM,KAAK,OAAO,QAAQ,SAAS,aAAa,OAAO,KAAK,IAAI;AAChE,QAAM,aAAa,OAAO,SAAS,cAAc,EAAE;AACnD,QAAM,WAAW,OAAO,SAAS,YAAY,EAAE;AAC/C,MAAI,CAAC,cAAc,CAAC,SAAU;AAC9B,MAAI,iBAAgC,SAAS,kBAAkB;AAC/D,MAAI,WAA0B,SAAS,YAAY;AACnD,QAAM,mBAAmB,SAAS,qBAAqB;AACvD,QAAM,kBAAkB,OAAO,SAAS,oBAAoB,WAAW,QAAQ,kBAAkB;AACjG,QAAM,mBAAmB,iCAAiC;AAC1D,MAAI;AACF,UAAM,2BAA2B,OAAO,UAAU,eAAe,KAAK,WAAW,CAAC,GAAG,gBAAgB;AACrG,UAAM,qBAAqB,OAAO,UAAU,eAAe,KAAK,WAAW,CAAC,GAAG,UAAU;AACzF,UAAM,SAAS,gCAAgC,IAAI,UAAU;AAC7D,UAAM,cAAc,MAAM,uBAAuB,IAAI,QAAQ,QAAQ;AACrE,UAAM,gBAAgB,6BAA6B;AAAA,MACjD,uBAAuB,SAAS;AAAA,MAChC,iBAAiB,SAAS;AAAA,MAC1B;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,qBAAiB,cAAc;AAC/B,eAAW,cAAc;AAEzB,UAAM,iBAAiB,OAAO,SAAS,mBAAmB,YAAY,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