@open-mercato/cli 0.11.1-develop.8920.1.d3c2cc4681 → 0.11.1-develop.8942.1.68c12f7f28

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 (186) hide show
  1. package/.turbo/turbo-build.log +6 -2
  2. package/dist/agentic/guides/module-facts.json +356 -385
  3. package/dist/agentic/guides/module-facts.v2.json +356 -385
  4. package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
  5. package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
  6. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  7. package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
  8. package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
  9. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  10. package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
  11. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  13. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  14. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  15. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  16. package/dist/agentic/guides/modules/auth/entities.md +1 -0
  17. package/dist/agentic/guides/modules/auth/index.md +2 -2
  18. package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
  19. package/dist/agentic/guides/modules/availability/index.md +1 -1
  20. package/dist/agentic/guides/modules/backups/index.md +1 -1
  21. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  22. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  23. package/dist/agentic/guides/modules/cart/index.md +1 -1
  24. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  25. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  26. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  27. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  28. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  29. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  30. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  31. package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
  32. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  33. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  34. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  35. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  36. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  37. package/dist/agentic/guides/modules/configs/index.md +1 -1
  38. package/dist/agentic/guides/modules/content/index.md +1 -1
  39. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  40. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
  41. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  42. package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
  43. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  44. package/dist/agentic/guides/modules/customers/index.md +1 -1
  45. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  46. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  47. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  48. package/dist/agentic/guides/modules/devices/index.md +1 -1
  49. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  50. package/dist/agentic/guides/modules/directory/index.md +1 -1
  51. package/dist/agentic/guides/modules/documents/index.md +1 -1
  52. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  53. package/dist/agentic/guides/modules/entities/index.md +1 -1
  54. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  55. package/dist/agentic/guides/modules/events/index.md +1 -1
  56. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  57. package/dist/agentic/guides/modules/forms/index.md +1 -1
  58. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  59. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  60. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  61. package/dist/agentic/guides/modules/generators/index.md +1 -1
  62. package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
  63. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  64. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  65. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  66. package/dist/agentic/guides/modules/maintenance/index.md +1 -1
  67. package/dist/agentic/guides/modules/messages/index.md +1 -1
  68. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  69. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  70. package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
  71. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  72. package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
  73. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  74. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  75. package/dist/agentic/guides/modules/planner/index.md +1 -1
  76. package/dist/agentic/guides/modules/portal/index.md +1 -1
  77. package/dist/agentic/guides/modules/progress/index.md +1 -1
  78. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  79. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  80. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  81. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  82. package/dist/agentic/guides/modules/resources/index.md +1 -1
  83. package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
  84. package/dist/agentic/guides/modules/sales/index.md +1 -1
  85. package/dist/agentic/guides/modules/sales/setup.md +1 -1
  86. package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
  87. package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
  88. package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
  89. package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
  90. package/dist/agentic/guides/modules/scheduler/index.md +3 -4
  91. package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
  92. package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
  93. package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
  94. package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
  95. package/dist/agentic/guides/modules/search/index.md +3 -2
  96. package/dist/agentic/guides/modules/security/index.md +1 -1
  97. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  98. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  99. package/dist/agentic/guides/modules/sso/index.md +1 -1
  100. package/dist/agentic/guides/modules/staff/index.md +1 -1
  101. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  102. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  103. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  104. package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
  105. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  106. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  107. package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
  108. package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
  109. package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
  110. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  111. package/dist/agentic/guides/modules/translations/index.md +1 -1
  112. package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
  113. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  114. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  115. package/dist/agentic/guides/modules/wms/index.md +1 -1
  116. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  117. package/dist/agentic/guides/reference-module-facts.json +2 -2
  118. package/dist/agentic/guides/reference-modules/example/index.md +1 -1
  119. package/dist/agentic/guides/upstream/manifest.json +1 -1
  120. package/dist/agentic/shared/AGENTS.md.template +3 -3
  121. package/dist/agentic/shared/ai/harness/cases.json +4 -4
  122. package/dist/bin.js +6 -3
  123. package/dist/bin.js.map +2 -2
  124. package/dist/i18n/de.json +5 -1
  125. package/dist/i18n/en.json +5 -1
  126. package/dist/i18n/es.json +5 -1
  127. package/dist/i18n/ko.json +5 -1
  128. package/dist/i18n/pl.json +5 -1
  129. package/dist/lib/cli-bootstrap-mode.js +10 -1
  130. package/dist/lib/cli-bootstrap-mode.js.map +2 -2
  131. package/dist/lib/db/commands.js +18 -3
  132. package/dist/lib/db/commands.js.map +2 -2
  133. package/dist/lib/db/maintenance-client.js +72 -0
  134. package/dist/lib/db/maintenance-client.js.map +7 -0
  135. package/dist/lib/generate-watch-structure.js +2 -1
  136. package/dist/lib/generate-watch-structure.js.map +2 -2
  137. package/dist/lib/generators/database-declarations.js +21 -0
  138. package/dist/lib/generators/database-declarations.js.map +7 -0
  139. package/dist/lib/generators/module-registry.js +19 -3
  140. package/dist/lib/generators/module-registry.js.map +2 -2
  141. package/dist/lib/init-existing-database.js +91 -1
  142. package/dist/lib/init-existing-database.js.map +2 -2
  143. package/dist/lib/init-i18n.js +13 -0
  144. package/dist/lib/init-i18n.js.map +7 -0
  145. package/dist/lib/init-secrets.js +2 -10
  146. package/dist/lib/init-secrets.js.map +2 -2
  147. package/dist/lib/scheduler-supervisor.js +47 -7
  148. package/dist/lib/scheduler-supervisor.js.map +2 -2
  149. package/dist/lib/testing/integration-discovery.js +14 -0
  150. package/dist/lib/testing/integration-discovery.js.map +2 -2
  151. package/dist/lib/worker-job-handler.js +36 -26
  152. package/dist/lib/worker-job-handler.js.map +2 -2
  153. package/dist/mercato.js +93 -54
  154. package/dist/mercato.js.map +3 -3
  155. package/package.json +7 -7
  156. package/src/__tests__/mercato.test.ts +166 -9
  157. package/src/bin.ts +10 -4
  158. package/src/i18n/de.json +5 -1
  159. package/src/i18n/en.json +5 -1
  160. package/src/i18n/es.json +5 -1
  161. package/src/i18n/ko.json +5 -1
  162. package/src/i18n/pl.json +5 -1
  163. package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
  164. package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
  165. package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
  166. package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
  167. package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
  168. package/src/lib/cli-bootstrap-mode.ts +12 -2
  169. package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
  170. package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
  171. package/src/lib/db/commands.ts +20 -6
  172. package/src/lib/db/maintenance-client.ts +54 -0
  173. package/src/lib/generate-watch-structure.ts +2 -1
  174. package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
  175. package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
  176. package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
  177. package/src/lib/generators/database-declarations.ts +19 -0
  178. package/src/lib/generators/module-registry.ts +23 -4
  179. package/src/lib/init-existing-database.ts +107 -0
  180. package/src/lib/init-i18n.ts +11 -0
  181. package/src/lib/init-secrets.ts +2 -12
  182. package/src/lib/scheduler-supervisor.ts +40 -7
  183. package/src/lib/testing/integration-discovery.ts +18 -0
  184. package/src/lib/worker-job-handler.ts +39 -28
  185. package/src/mercato.ts +92 -53
  186. package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
@@ -1,7 +1,85 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createCliMaintenanceClient } from "./db/maintenance-client.js";
3
+ import { createInitTranslator } from "./init-i18n.js";
4
+ const INITIALIZATION_NAME = "mercato-init";
1
5
  function decideExistingDatabase(existingUsersCount, skipIfInitialized) {
2
6
  if (!Number.isFinite(existingUsersCount) || existingUsersCount <= 0) return "proceed";
3
7
  return skipIfInitialized ? "skip" : "abort";
4
8
  }
9
+ async function withInitializationClient(databaseUrl, action) {
10
+ const client = await createCliMaintenanceClient(databaseUrl);
11
+ try {
12
+ await client.connect();
13
+ return await action(client);
14
+ } finally {
15
+ await client.end();
16
+ }
17
+ }
18
+ async function hasIncompleteInitialization(client) {
19
+ const table = await client.query(
20
+ "SELECT to_regclass('app_initializations') AS regclass"
21
+ );
22
+ if (!table.rows[0]?.regclass) return false;
23
+ const result = await client.query(
24
+ "SELECT completed_at IS NULL AS pending FROM app_initializations WHERE name = $1",
25
+ [INITIALIZATION_NAME]
26
+ );
27
+ return result.rows[0]?.pending === true;
28
+ }
29
+ async function startInitialization(client) {
30
+ const translate = createInitTranslator(process.env);
31
+ const lock = await client.query(
32
+ "SELECT pg_try_advisory_lock(hashtext($1)) AS locked",
33
+ [INITIALIZATION_NAME]
34
+ );
35
+ if (lock.rows[0]?.locked !== true) {
36
+ throw new Error(translate("cli.init.errors.concurrentInitialization"));
37
+ }
38
+ const cleared = await client.query(
39
+ "DELETE FROM app_initializations WHERE name = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)",
40
+ [INITIALIZATION_NAME]
41
+ );
42
+ const initializationId = randomUUID();
43
+ const result = await client.query(
44
+ "INSERT INTO app_initializations (id, name) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING",
45
+ [initializationId, INITIALIZATION_NAME]
46
+ );
47
+ if (result.rowCount !== 1) {
48
+ throw new Error(translate("cli.init.errors.concurrentInitialization"));
49
+ }
50
+ return { initializationId, clearedInterruptedAttempt: cleared.rowCount === 1 };
51
+ }
52
+ async function openInitializationSession(databaseUrl) {
53
+ const client = await createCliMaintenanceClient(databaseUrl, { pinned: true });
54
+ try {
55
+ await client.connect();
56
+ const { initializationId, clearedInterruptedAttempt } = await startInitialization(client);
57
+ return {
58
+ clearedInterruptedAttempt,
59
+ cancelWithoutUsers: () => cancelInitializationWithoutUsers(client, initializationId),
60
+ complete: () => completeInitialization(client, initializationId),
61
+ close: () => client.end()
62
+ };
63
+ } catch (error) {
64
+ await client.end();
65
+ throw error;
66
+ }
67
+ }
68
+ async function cancelInitializationWithoutUsers(client, initializationId) {
69
+ await client.query(
70
+ "DELETE FROM app_initializations WHERE id = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)",
71
+ [initializationId]
72
+ );
73
+ }
74
+ async function completeInitialization(client, initializationId) {
75
+ const result = await client.query(
76
+ "UPDATE app_initializations SET completed_at = now() WHERE id = $1 AND completed_at IS NULL",
77
+ [initializationId]
78
+ );
79
+ if (result.rowCount !== 1) {
80
+ throw new Error(createInitTranslator(process.env)("cli.init.errors.initializationStateMissing"));
81
+ }
82
+ }
5
83
  function describeDatabaseTarget(databaseUrl) {
6
84
  try {
7
85
  const url = new URL(databaseUrl);
@@ -18,9 +96,21 @@ function formatSkipIfInitializedMessage(existingUsersCount, databaseUrl) {
18
96
  " Not the database you expected? Check DATABASE_URL in .env. To wipe it and seed from scratch: yarn mercato init --reinstall"
19
97
  ];
20
98
  }
99
+ function formatIncompleteInitializationMessage(databaseUrl) {
100
+ return createInitTranslator(process.env)("cli.init.errors.incompleteInitialization", {
101
+ database: describeDatabaseTarget(databaseUrl)
102
+ });
103
+ }
21
104
  export {
105
+ cancelInitializationWithoutUsers,
106
+ completeInitialization,
22
107
  decideExistingDatabase,
23
108
  describeDatabaseTarget,
24
- formatSkipIfInitializedMessage
109
+ formatIncompleteInitializationMessage,
110
+ formatSkipIfInitializedMessage,
111
+ hasIncompleteInitialization,
112
+ openInitializationSession,
113
+ startInitialization,
114
+ withInitializationClient
25
115
  };
26
116
  //# sourceMappingURL=init-existing-database.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/init-existing-database.ts"],
4
- "sourcesContent": ["export type ExistingDatabaseDecision = 'proceed' | 'skip' | 'abort'\n\nexport function decideExistingDatabase(existingUsersCount: number, skipIfInitialized: boolean): ExistingDatabaseDecision {\n if (!Number.isFinite(existingUsersCount) || existingUsersCount <= 0) return 'proceed'\n return skipIfInitialized ? 'skip' : 'abort'\n}\n\nexport function describeDatabaseTarget(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl)\n const database = decodeURIComponent(url.pathname.replace(/^\\/+/, '')) || '(default database)'\n const host = url.hostname || 'localhost'\n return `${host}${url.port ? `:${url.port}` : ''}/${database}`\n } catch {\n return 'the database from DATABASE_URL'\n }\n}\n\nexport function formatSkipIfInitializedMessage(existingUsersCount: number, databaseUrl: string): string[] {\n return [\n `\u2705 Database already initialized (${existingUsersCount} user(s) in ${describeDatabaseTarget(databaseUrl)}) \u2014 keeping the existing data and skipping the first-run seed.`,\n ' Not the database you expected? Check DATABASE_URL in .env. To wipe it and seed from scratch: yarn mercato init --reinstall',\n ]\n}\n"],
5
- "mappings": "AAEO,SAAS,uBAAuB,oBAA4B,mBAAsD;AACvH,MAAI,CAAC,OAAO,SAAS,kBAAkB,KAAK,sBAAsB,EAAG,QAAO;AAC5E,SAAO,oBAAoB,SAAS;AACtC;AAEO,SAAS,uBAAuB,aAA6B;AAClE,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,WAAW;AAC/B,UAAM,WAAW,mBAAmB,IAAI,SAAS,QAAQ,QAAQ,EAAE,CAAC,KAAK;AACzE,UAAM,OAAO,IAAI,YAAY;AAC7B,WAAO,GAAG,IAAI,GAAG,IAAI,OAAO,IAAI,IAAI,IAAI,KAAK,EAAE,IAAI,QAAQ;AAAA,EAC7D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,+BAA+B,oBAA4B,aAA+B;AACxG,SAAO;AAAA,IACL,wCAAmC,kBAAkB,eAAe,uBAAuB,WAAW,CAAC;AAAA,IACvG;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { Client } from 'pg'\nimport { randomUUID } from 'node:crypto'\nimport { createCliMaintenanceClient } from './db/maintenance-client'\nimport { createInitTranslator } from './init-i18n'\n\nconst INITIALIZATION_NAME = 'mercato-init'\n\nexport type ExistingDatabaseDecision = 'proceed' | 'skip' | 'abort'\ntype InitializationClient = Pick<Client, 'query'>\n\nexport function decideExistingDatabase(existingUsersCount: number, skipIfInitialized: boolean): ExistingDatabaseDecision {\n if (!Number.isFinite(existingUsersCount) || existingUsersCount <= 0) return 'proceed'\n return skipIfInitialized ? 'skip' : 'abort'\n}\n\nexport async function withInitializationClient<T>(\n databaseUrl: string,\n action: (client: InitializationClient) => Promise<T>,\n): Promise<T> {\n const client = await createCliMaintenanceClient(databaseUrl)\n try {\n await client.connect()\n return await action(client)\n } finally {\n await client.end()\n }\n}\n\nexport async function hasIncompleteInitialization(client: InitializationClient): Promise<boolean> {\n const table = await client.query<{ regclass: string | null }>(\n \"SELECT to_regclass('app_initializations') AS regclass\",\n )\n if (!table.rows[0]?.regclass) return false\n\n const result = await client.query<{ pending: boolean }>(\n 'SELECT completed_at IS NULL AS pending FROM app_initializations WHERE name = $1',\n [INITIALIZATION_NAME],\n )\n return result.rows[0]?.pending === true\n}\n\nexport type InitializationStart = { initializationId: string; clearedInterruptedAttempt: boolean }\n\nexport async function startInitialization(client: InitializationClient): Promise<InitializationStart> {\n const translate = createInitTranslator(process.env)\n const lock = await client.query<{ locked: boolean }>(\n 'SELECT pg_try_advisory_lock(hashtext($1)) AS locked',\n [INITIALIZATION_NAME],\n )\n if (lock.rows[0]?.locked !== true) {\n throw new Error(translate('cli.init.errors.concurrentInitialization'))\n }\n const cleared = await client.query(\n 'DELETE FROM app_initializations WHERE name = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',\n [INITIALIZATION_NAME],\n )\n const initializationId = randomUUID()\n const result = await client.query(\n 'INSERT INTO app_initializations (id, name) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING',\n [initializationId, INITIALIZATION_NAME],\n )\n if (result.rowCount !== 1) {\n throw new Error(translate('cli.init.errors.concurrentInitialization'))\n }\n return { initializationId, clearedInterruptedAttempt: cleared.rowCount === 1 }\n}\n\nexport type InitializationSession = {\n clearedInterruptedAttempt: boolean\n cancelWithoutUsers: () => Promise<void>\n complete: () => Promise<void>\n close: () => Promise<void>\n}\n\nexport async function openInitializationSession(databaseUrl: string): Promise<InitializationSession> {\n const client = await createCliMaintenanceClient(databaseUrl, { pinned: true })\n try {\n await client.connect()\n const { initializationId, clearedInterruptedAttempt } = await startInitialization(client)\n return {\n clearedInterruptedAttempt,\n cancelWithoutUsers: () => cancelInitializationWithoutUsers(client, initializationId),\n complete: () => completeInitialization(client, initializationId),\n close: () => client.end(),\n }\n } catch (error) {\n await client.end()\n throw error\n }\n}\n\nexport async function cancelInitializationWithoutUsers(client: InitializationClient, initializationId: string): Promise<void> {\n await client.query(\n 'DELETE FROM app_initializations WHERE id = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',\n [initializationId],\n )\n}\n\nexport async function completeInitialization(client: InitializationClient, initializationId: string): Promise<void> {\n const result = await client.query(\n 'UPDATE app_initializations SET completed_at = now() WHERE id = $1 AND completed_at IS NULL',\n [initializationId],\n )\n if (result.rowCount !== 1) {\n throw new Error(createInitTranslator(process.env)('cli.init.errors.initializationStateMissing'))\n }\n}\n\nexport function describeDatabaseTarget(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl)\n const database = decodeURIComponent(url.pathname.replace(/^\\/+/, '')) || '(default database)'\n const host = url.hostname || 'localhost'\n return `${host}${url.port ? `:${url.port}` : ''}/${database}`\n } catch {\n return 'the database from DATABASE_URL'\n }\n}\n\nexport function formatSkipIfInitializedMessage(existingUsersCount: number, databaseUrl: string): string[] {\n return [\n `\u2705 Database already initialized (${existingUsersCount} user(s) in ${describeDatabaseTarget(databaseUrl)}) \u2014 keeping the existing data and skipping the first-run seed.`,\n ' Not the database you expected? Check DATABASE_URL in .env. To wipe it and seed from scratch: yarn mercato init --reinstall',\n ]\n}\n\nexport function formatIncompleteInitializationMessage(databaseUrl: string): string {\n return createInitTranslator(process.env)('cli.init.errors.incompleteInitialization', {\n database: describeDatabaseTarget(databaseUrl),\n })\n}\n"],
5
+ "mappings": "AACA,SAAS,kBAAkB;AAC3B,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AAErC,MAAM,sBAAsB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AAE,4CAA4C;AAAA,IACnF,UAAU,uBAAuB,WAAW;AAAA,EAC9C,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,13 @@
1
+ import { createTranslator } from "@open-mercato/shared/lib/i18n/translate";
2
+ import { createRequire } from "node:module";
3
+ const requireLocale = createRequire(import.meta.url);
4
+ function createInitTranslator(env) {
5
+ const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || "en").split(/[_.-]/)[0].toLowerCase();
6
+ const supportedLocale = ["en", "pl", "es", "de", "ko"].includes(locale) ? locale : "en";
7
+ const dictionary = requireLocale(`../i18n/${supportedLocale}.json`);
8
+ return createTranslator(dictionary);
9
+ }
10
+ export {
11
+ createInitTranslator
12
+ };
13
+ //# sourceMappingURL=init-i18n.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/init-i18n.ts"],
4
+ "sourcesContent": ["import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'\nimport { createRequire } from 'node:module'\n\nconst requireLocale = createRequire(import.meta.url)\n\nexport function createInitTranslator(env: NodeJS.ProcessEnv) {\n const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en').split(/[_.-]/)[0].toLowerCase()\n const supportedLocale = ['en', 'pl', 'es', 'de', 'ko'].includes(locale) ? locale : 'en'\n const dictionary: Record<string, string> = requireLocale(`../i18n/${supportedLocale}.json`)\n return createTranslator(dictionary)\n}\n"],
5
+ "mappings": "AAAA,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAE9B,MAAM,gBAAgB,cAAc,YAAY,GAAG;AAE5C,SAAS,qBAAqB,KAAwB;AAC3D,QAAM,UAAU,IAAI,UAAU,IAAI,eAAe,IAAI,QAAQ,MAAM,MAAM,OAAO,EAAE,CAAC,EAAE,YAAY;AACjG,QAAM,kBAAkB,CAAC,MAAM,MAAM,MAAM,MAAM,IAAI,EAAE,SAAS,MAAM,IAAI,SAAS;AACnF,QAAM,aAAqC,cAAc,WAAW,eAAe,OAAO;AAC1F,SAAO,iBAAiB,UAAU;AACpC;",
6
+ "names": []
7
+ }
@@ -1,15 +1,7 @@
1
1
  import { parseBooleanToken } from "@open-mercato/shared/lib/boolean";
2
2
  import { getPasswordPolicy, validatePassword } from "@open-mercato/shared/lib/auth/passwordPolicy";
3
3
  import { randomBytes } from "node:crypto";
4
- import { createTranslator } from "@open-mercato/shared/lib/i18n/translate";
5
- import { createRequire } from "node:module";
6
- const requireLocale = createRequire(import.meta.url);
7
- function initTranslator(env) {
8
- const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || "en").split(/[_.-]/)[0].toLowerCase();
9
- const supportedLocale = ["en", "pl", "es", "de", "ko"].includes(locale) ? locale : "en";
10
- const dictionary = requireLocale(`../i18n/${supportedLocale}.json`);
11
- return createTranslator(dictionary);
12
- }
4
+ import { createInitTranslator } from "./init-i18n.js";
13
5
  function readEnvValue(env, key) {
14
6
  const value = env[key];
15
7
  if (typeof value !== "string") return void 0;
@@ -60,7 +52,7 @@ function resolveInitSuperadminCredentials(args, env = process.env) {
60
52
  );
61
53
  const skipPasswordPolicy = !isProduction && (skipPolicyArg ? parseBooleanToken(skipPolicyArg.split("=")[1] ?? "true") ?? true : true);
62
54
  if (isProduction) {
63
- const t = initTranslator(env);
55
+ const t = createInitTranslator(env);
64
56
  const placeholder = suppliedPassword?.trim().toLowerCase();
65
57
  if (!suppliedPassword || !placeholder || ["secret", "password", "changeme", "change-me", "change_me", "replace-me", "replace_me"].includes(placeholder)) {
66
58
  throw new Error(t("cli.init.errors.superadminPasswordRequired"));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/init-secrets.ts"],
4
- "sourcesContent": ["import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { getPasswordPolicy, validatePassword } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { randomBytes } from 'node:crypto'\nimport { createTranslator } from '@open-mercato/shared/lib/i18n/translate'\nimport { createRequire } from 'node:module'\n\nconst requireLocale = createRequire(import.meta.url)\n\nfunction initTranslator(env: NodeJS.ProcessEnv) {\n const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en').split(/[_.-]/)[0].toLowerCase()\n const supportedLocale = ['en', 'pl', 'es', 'de', 'ko'].includes(locale) ? locale : 'en'\n const dictionary: Record<string, string> = requireLocale(`../i18n/${supportedLocale}.json`)\n return createTranslator(dictionary)\n}\n\ntype EnvReader = (key: string) => string | undefined\n\nfunction readEnvValue(env: NodeJS.ProcessEnv, key: string): string | undefined {\n const value = env[key]\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction resolveEmailFromDomain(domain: string | undefined, prefix: string): string | null {\n if (!domain) return null\n return `${prefix}@${domain}`\n}\n\nexport type InitDerivedSecrets = {\n adminEmail: string | null\n employeeEmail: string | null\n adminPassword: string | null\n employeePassword: string | null\n}\n\n// Well-known dev/demo password baked into local bootstrap flows so developers\n// keep the documented \"log in as admin@<domain> with password 'secret'\" UX.\n// Only used when NODE_ENV !== 'production' and the OM_INIT_*_PASSWORD env vars\n// are unset \u2014 production paths always use a random 96-bit secret.\nconst DEMO_DERIVED_PASSWORD = 'secret'\n\nlet warnedAboutDeprecatedRandomToggle = false\n\nexport function resolveInitDerivedSecrets(options: {\n email: string\n env?: NodeJS.ProcessEnv\n randomSource?: (size: number) => Buffer\n}): InitDerivedSecrets {\n const env = options.env ?? process.env\n const envRead: EnvReader = (key) => readEnvValue(env, key)\n const [, domain] = String(options.email ?? '').split('@')\n const adminEmail = envRead('OM_INIT_ADMIN_EMAIL') ?? resolveEmailFromDomain(domain, 'admin')\n const employeeEmail = envRead('OM_INIT_EMPLOYEE_EMAIL') ?? resolveEmailFromDomain(domain, 'employee')\n // OM_INIT_GENERATE_RANDOM_PASSWORD used to be an opt-in toggle for random\n // derived secrets; in production it is now the unconditional behaviour when\n // no override is set. Surface a one-time deprecation warning so existing\n // operators notice their config is no longer required.\n if (parseBooleanToken(envRead('OM_INIT_GENERATE_RANDOM_PASSWORD') ?? '') === true && !warnedAboutDeprecatedRandomToggle) {\n warnedAboutDeprecatedRandomToggle = true\n console.warn(\n '\u26A0\uFE0F OM_INIT_GENERATE_RANDOM_PASSWORD is deprecated and no longer required: derived admin/employee passwords are always randomized in production when overrides are unset.',\n )\n }\n const isProduction = (env.NODE_ENV ?? '').trim().toLowerCase() === 'production'\n const randomize = options.randomSource ?? randomBytes\n const randomSecret = () => `Aa1!${randomize(Math.max(12, getPasswordPolicy(env).minLength)).toString('base64url')}`\n const resolvePassword = (key: string, emailValue: string | null) => {\n if (!emailValue) return null\n const envValue = envRead(key)\n if (envValue) return envValue\n // Non-production (dev/test/staging defaults): seed the documented demo\n // password so `yarn dev` / `mercato init` workflows stay predictable.\n // Production: generate a fresh random secret so credentials are never\n // hardcoded and the operator-facing CLI prints the value once.\n return isProduction ? randomSecret() : DEMO_DERIVED_PASSWORD\n }\n\n return {\n adminEmail,\n employeeEmail,\n adminPassword: resolvePassword('OM_INIT_ADMIN_PASSWORD', adminEmail),\n employeePassword: resolvePassword('OM_INIT_EMPLOYEE_PASSWORD', employeeEmail),\n }\n}\n\nexport function resolveInitSuperadminCredentials(args: string[], env: NodeJS.ProcessEnv = process.env) {\n const argValue = (name: string) => args.find((arg) => arg.startsWith(`${name}=`))?.slice(name.length + 1) || undefined\n const email = argValue('--email') ?? readEnvValue(env, 'OM_INIT_SUPERADMIN_EMAIL') ?? 'superadmin@acme.com'\n const suppliedPassword = argValue('--password') ?? readEnvValue(env, 'OM_INIT_SUPERADMIN_PASSWORD')\n const isProduction = (env.NODE_ENV ?? '').trim().toLowerCase() === 'production'\n const skipPolicyArg = args.find((arg) =>\n arg === '--skip-password-policy' || arg.startsWith('--skip-password-policy=') ||\n arg === '--allow-weak-password' || arg.startsWith('--allow-weak-password='),\n )\n const skipPasswordPolicy = !isProduction && (skipPolicyArg\n ? parseBooleanToken(skipPolicyArg.split('=')[1] ?? 'true') ?? true\n : true)\n if (isProduction) {\n const t = initTranslator(env)\n const placeholder = suppliedPassword?.trim().toLowerCase()\n if (!suppliedPassword || !placeholder || ['secret', 'password', 'changeme', 'change-me', 'change_me', 'replace-me', 'replace_me'].includes(placeholder)) {\n throw new Error(t('cli.init.errors.superadminPasswordRequired'))\n }\n if (!validatePassword(suppliedPassword, getPasswordPolicy(env)).ok) {\n throw new Error(t('cli.init.errors.superadminPasswordPolicy'))\n }\n }\n return { email, password: suppliedPassword ?? 'secret', skipPasswordPolicy }\n}\n"],
5
- "mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAE9B,MAAM,gBAAgB,cAAc,YAAY,GAAG;AAEnD,SAAS,eAAe,KAAwB;AAC9C,QAAM,UAAU,IAAI,UAAU,IAAI,eAAe,IAAI,QAAQ,MAAM,MAAM,OAAO,EAAE,CAAC,EAAE,YAAY;AACjG,QAAM,kBAAkB,CAAC,MAAM,MAAM,MAAM,MAAM,IAAI,EAAE,SAAS,MAAM,IAAI,SAAS;AACnF,QAAM,aAAqC,cAAc,WAAW,eAAe,OAAO;AAC1F,SAAO,iBAAiB,UAAU;AACpC;AAIA,SAAS,aAAa,KAAwB,KAAiC;AAC7E,QAAM,QAAQ,IAAI,GAAG;AACrB,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,uBAAuB,QAA4B,QAA+B;AACzF,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,GAAG,MAAM,IAAI,MAAM;AAC5B;AAaA,MAAM,wBAAwB;AAE9B,IAAI,oCAAoC;AAEjC,SAAS,0BAA0B,SAInB;AACrB,QAAM,MAAM,QAAQ,OAAO,QAAQ;AACnC,QAAM,UAAqB,CAAC,QAAQ,aAAa,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nE,QAAM,gBAAgB,KAAK;AAAA,IAAK,CAAC,QAC/B,QAAQ,4BAA4B,IAAI,WAAW,yBAAyB,KAC5E,QAAQ,2BAA2B,IAAI,WAAW,wBAAwB;AAAA,EAC5E;AACA,QAAM,qBAAqB,CAAC,iBAAiB,gBACzC,kBAAkB,cAAc,MAAM,GAAG,EAAE,CAAC,KAAK,MAAM,KAAK,OAC5D;AACJ,MAAI,cAAc;AAChB,UAAM,IAAI,eAAe,GAAG;AAC5B,UAAM,cAAc,kBAAkB,KAAK,EAAE,YAAY;AACzD,QAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,UAAU,YAAY,YAAY,aAAa,aAAa,cAAc,YAAY,EAAE,SAAS,WAAW,GAAG;AACvJ,YAAM,IAAI,MAAM,EAAE,4CAA4C,CAAC;AAAA,IACjE;AACA,QAAI,CAAC,iBAAiB,kBAAkB,kBAAkB,GAAG,CAAC,EAAE,IAAI;AAClE,YAAM,IAAI,MAAM,EAAE,0CAA0C,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO,EAAE,OAAO,UAAU,oBAAoB,UAAU,mBAAmB;AAC7E;",
4
+ "sourcesContent": ["import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { getPasswordPolicy, validatePassword } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { randomBytes } from 'node:crypto'\nimport { createInitTranslator } from './init-i18n'\n\ntype EnvReader = (key: string) => string | undefined\n\nfunction readEnvValue(env: NodeJS.ProcessEnv, key: string): string | undefined {\n const value = env[key]\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction resolveEmailFromDomain(domain: string | undefined, prefix: string): string | null {\n if (!domain) return null\n return `${prefix}@${domain}`\n}\n\nexport type InitDerivedSecrets = {\n adminEmail: string | null\n employeeEmail: string | null\n adminPassword: string | null\n employeePassword: string | null\n}\n\n// Well-known dev/demo password baked into local bootstrap flows so developers\n// keep the documented \"log in as admin@<domain> with password 'secret'\" UX.\n// Only used when NODE_ENV !== 'production' and the OM_INIT_*_PASSWORD env vars\n// are unset \u2014 production paths always use a random 96-bit secret.\nconst DEMO_DERIVED_PASSWORD = 'secret'\n\nlet warnedAboutDeprecatedRandomToggle = false\n\nexport function resolveInitDerivedSecrets(options: {\n email: string\n env?: NodeJS.ProcessEnv\n randomSource?: (size: number) => Buffer\n}): InitDerivedSecrets {\n const env = options.env ?? process.env\n const envRead: EnvReader = (key) => readEnvValue(env, key)\n const [, domain] = String(options.email ?? '').split('@')\n const adminEmail = envRead('OM_INIT_ADMIN_EMAIL') ?? resolveEmailFromDomain(domain, 'admin')\n const employeeEmail = envRead('OM_INIT_EMPLOYEE_EMAIL') ?? resolveEmailFromDomain(domain, 'employee')\n // OM_INIT_GENERATE_RANDOM_PASSWORD used to be an opt-in toggle for random\n // derived secrets; in production it is now the unconditional behaviour when\n // no override is set. Surface a one-time deprecation warning so existing\n // operators notice their config is no longer required.\n if (parseBooleanToken(envRead('OM_INIT_GENERATE_RANDOM_PASSWORD') ?? '') === true && !warnedAboutDeprecatedRandomToggle) {\n warnedAboutDeprecatedRandomToggle = true\n console.warn(\n '\u26A0\uFE0F OM_INIT_GENERATE_RANDOM_PASSWORD is deprecated and no longer required: derived admin/employee passwords are always randomized in production when overrides are unset.',\n )\n }\n const isProduction = (env.NODE_ENV ?? '').trim().toLowerCase() === 'production'\n const randomize = options.randomSource ?? randomBytes\n const randomSecret = () => `Aa1!${randomize(Math.max(12, getPasswordPolicy(env).minLength)).toString('base64url')}`\n const resolvePassword = (key: string, emailValue: string | null) => {\n if (!emailValue) return null\n const envValue = envRead(key)\n if (envValue) return envValue\n // Non-production (dev/test/staging defaults): seed the documented demo\n // password so `yarn dev` / `mercato init` workflows stay predictable.\n // Production: generate a fresh random secret so credentials are never\n // hardcoded and the operator-facing CLI prints the value once.\n return isProduction ? randomSecret() : DEMO_DERIVED_PASSWORD\n }\n\n return {\n adminEmail,\n employeeEmail,\n adminPassword: resolvePassword('OM_INIT_ADMIN_PASSWORD', adminEmail),\n employeePassword: resolvePassword('OM_INIT_EMPLOYEE_PASSWORD', employeeEmail),\n }\n}\n\nexport function resolveInitSuperadminCredentials(args: string[], env: NodeJS.ProcessEnv = process.env) {\n const argValue = (name: string) => args.find((arg) => arg.startsWith(`${name}=`))?.slice(name.length + 1) || undefined\n const email = argValue('--email') ?? readEnvValue(env, 'OM_INIT_SUPERADMIN_EMAIL') ?? 'superadmin@acme.com'\n const suppliedPassword = argValue('--password') ?? readEnvValue(env, 'OM_INIT_SUPERADMIN_PASSWORD')\n const isProduction = (env.NODE_ENV ?? '').trim().toLowerCase() === 'production'\n const skipPolicyArg = args.find((arg) =>\n arg === '--skip-password-policy' || arg.startsWith('--skip-password-policy=') ||\n arg === '--allow-weak-password' || arg.startsWith('--allow-weak-password='),\n )\n const skipPasswordPolicy = !isProduction && (skipPolicyArg\n ? parseBooleanToken(skipPolicyArg.split('=')[1] ?? 'true') ?? true\n : true)\n if (isProduction) {\n const t = createInitTranslator(env)\n const placeholder = suppliedPassword?.trim().toLowerCase()\n if (!suppliedPassword || !placeholder || ['secret', 'password', 'changeme', 'change-me', 'change_me', 'replace-me', 'replace_me'].includes(placeholder)) {\n throw new Error(t('cli.init.errors.superadminPasswordRequired'))\n }\n if (!validatePassword(suppliedPassword, getPasswordPolicy(env)).ok) {\n throw new Error(t('cli.init.errors.superadminPasswordPolicy'))\n }\n }\n return { email, password: suppliedPassword ?? 'secret', skipPasswordPolicy }\n}\n"],
5
+ "mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AAIrC,SAAS,aAAa,KAAwB,KAAiC;AAC7E,QAAM,QAAQ,IAAI,GAAG;AACrB,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,u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IAAI,GAAG,CAAC,GAAG,MAAM,KAAK,SAAS,CAAC,KAAK;AAC7G,QAAM,QAAQ,SAAS,SAAS,KAAK,aAAa,KAAK,0BAA0B,KAAK;AACtF,QAAM,mBAAmB,SAAS,YAAY,KAAK,aAAa,KAAK,6BAA6B;AAClG,QAAM,gBAAgB,IAAI,YAAY,IAAI,KAAK,EAAE,YAAY,MAAM;AACnE,QAAM,gBAAgB,KAAK;AAAA,IAAK,CAAC,QAC/B,QAAQ,4BAA4B,IAAI,WAAW,yBAAyB,KAC5E,QAAQ,2BAA2B,IAAI,WAAW,wBAAwB;AAAA,EAC5E;AACA,QAAM,qBAAqB,CAAC,iBAAiB,gBACzC,kBAAkB,cAAc,MAAM,GAAG,EAAE,CAAC,KAAK,MAAM,KAAK,OAC5D;AACJ,MAAI,cAAc;AAChB,UAAM,IAAI,qBAAqB,GAAG;AAClC,UAAM,cAAc,kBAAkB,KAAK,EAAE,YAAY;AACzD,QAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,UAAU,YAAY,YAAY,aAAa,aAAa,cAAc,YAAY,EAAE,SAAS,WAAW,GAAG;AACvJ,YAAM,IAAI,MAAM,EAAE,4CAA4C,CAAC;AAAA,IACjE;AACA,QAAI,CAAC,iBAAiB,kBAAkB,kBAAkB,GAAG,CAAC,EAAE,IAAI;AAClE,YAAM,IAAI,MAAM,EAAE,0CAA0C,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO,EAAE,OAAO,UAAU,oBAAoB,UAAU,mBAAmB;AAC7E;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,6 @@
1
1
  import { spawn as nodeSpawn } from "node:child_process";
2
2
  import { getSslConfig } from "@open-mercato/shared/lib/db/ssl";
3
+ import { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from "@open-mercato/shared/lib/db/runtime";
3
4
  const PROBE_ERROR_LOG_THROTTLE_MS = 6e4;
4
5
  function coerceCount(value) {
5
6
  if (typeof value === "number" && Number.isFinite(value)) return Math.max(0, Math.floor(value));
@@ -25,14 +26,42 @@ async function probeEnabledSchedules(env = process.env) {
25
26
  errorMessage: "DATABASE_URL is not set"
26
27
  };
27
28
  }
28
- const { Client } = await import("pg");
29
- const client = new Client({
30
- connectionString: databaseUrl,
31
- ssl: getSslConfig()
32
- });
29
+ if (isDatabaseRuntimeEnabled()) {
30
+ return runWithFreshDatabaseExecutionContext({
31
+ kind: "maintenance",
32
+ tenantId: null,
33
+ source: "scheduler",
34
+ operation: "scheduler.lazy-probe"
35
+ }, () => probeScheduleConnection(databaseUrl, true));
36
+ }
37
+ return probeScheduleConnection(databaseUrl, false);
38
+ }
39
+ async function probeScheduleConnection(databaseUrl, maintenance) {
40
+ let clientEnded = false;
41
+ let lifecycle;
42
+ let release;
43
+ let client;
33
44
  try {
45
+ const { Client } = await import("pg");
46
+ client = new Client({
47
+ connectionString: maintenance ? resolveDatabaseConnectionUrl("maintenance", databaseUrl) : databaseUrl,
48
+ ssl: getSslConfig(),
49
+ ...maintenance ? { connectionTimeoutMillis: 5e3, query_timeout: 5e3 } : {}
50
+ });
34
51
  await client.connect();
35
- const result = await client.query(`
52
+ let connection = client;
53
+ if (maintenance) {
54
+ const physical = { query: client.query.bind(client), release: () => void 0 };
55
+ const pool = { connect: async () => physical, get ended() {
56
+ return clientEnded;
57
+ } };
58
+ lifecycle = configureDatabasePool(pool, { id: "scheduler-lazy-probe", purpose: "maintenance", tables: ["scheduled_jobs"] });
59
+ await lifecycle.ready();
60
+ const guarded = await pool.connect();
61
+ connection = guarded;
62
+ release = guarded.release;
63
+ }
64
+ const result = await connection.query(`
36
65
  select
37
66
  count(*)::int as enabled_schedules,
38
67
  count(*) filter (where next_run_at <= now())::int as due_schedules
@@ -61,7 +90,18 @@ async function probeEnabledSchedules(env = process.env) {
61
90
  errorMessage: error instanceof Error ? error.message : String(error)
62
91
  };
63
92
  } finally {
64
- await client.end().catch(() => void 0);
93
+ try {
94
+ release?.();
95
+ } finally {
96
+ try {
97
+ if (client) {
98
+ await client.end();
99
+ clientEnded = true;
100
+ }
101
+ } finally {
102
+ lifecycle?.dispose();
103
+ }
104
+ }
65
105
  }
66
106
  }
67
107
  function startLazySchedulerSupervisor(options) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/scheduler-supervisor.ts"],
4
- "sourcesContent": ["/**\n * Lazy local scheduler supervisor.\n *\n * Keeps the server runtime from spawning the local scheduler polling engine\n * until at least one enabled schedule exists. The scheduler process itself is\n * still the existing `mercato scheduler start` command, so schedule execution,\n * locking, RBAC checks, and queue/command targets remain unchanged.\n */\n\nimport { spawn as nodeSpawn } from 'node:child_process'\nimport type { ChildProcess, SpawnOptions } from 'node:child_process'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\n\nexport type SchedulerScheduleProbeResult = {\n enabledSchedules: number\n dueSchedules: number\n error?: boolean\n errorMessage?: string\n}\n\nexport type LazySchedulerSupervisorProbeFn = (\n env: NodeJS.ProcessEnv,\n) => Promise<SchedulerScheduleProbeResult>\n\nexport type LazySchedulerSupervisorSpawnFn = (\n command: string,\n args: readonly string[],\n options: SpawnOptions,\n) => ChildProcess\n\nexport type LazySchedulerSupervisorOptions = {\n mercatoBin: string\n appDir: string\n runtimeEnv: NodeJS.ProcessEnv\n pollMs: number\n restartOnUnexpectedExit: boolean\n spawnFn?: LazySchedulerSupervisorSpawnFn\n probeFn?: LazySchedulerSupervisorProbeFn\n logger?: Pick<Console, 'log' | 'warn' | 'error'>\n onSpawn?: (child: ChildProcess) => void\n onChildExit?: (code: number | null, signal: NodeJS.Signals | null) => void\n}\n\nexport type LazySchedulerSupervisorHandle = {\n readonly started: boolean\n getActiveChild(): ChildProcess | undefined\n close(): Promise<void>\n done: Promise<void>\n}\n\nconst PROBE_ERROR_LOG_THROTTLE_MS = 60_000\n\nfunction coerceCount(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.floor(value))\n if (typeof value === 'bigint') return Number(value)\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : 0\n }\n return 0\n}\n\nfunction isMissingScheduledJobsTableError(error: unknown): boolean {\n return Boolean(\n error\n && typeof error === 'object'\n && 'code' in error\n && (error as { code?: unknown }).code === '42P01',\n )\n}\n\nexport async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env): Promise<SchedulerScheduleProbeResult> {\n const databaseUrl = env.DATABASE_URL?.trim()\n if (!databaseUrl) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: 'DATABASE_URL is not set',\n }\n }\n\n const { Client } = await import('pg')\n const client = new Client({\n connectionString: databaseUrl,\n ssl: getSslConfig(),\n })\n\n try {\n await client.connect()\n const result = await client.query(`\n select\n count(*)::int as enabled_schedules,\n count(*) filter (where next_run_at <= now())::int as due_schedules\n from scheduled_jobs\n where is_enabled = true\n and deleted_at is null\n `)\n const row = result.rows[0] ?? {}\n return {\n enabledSchedules: coerceCount(row.enabled_schedules),\n dueSchedules: coerceCount(row.due_schedules),\n error: false,\n }\n } catch (error) {\n if (isMissingScheduledJobsTableError(error)) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: false,\n }\n }\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n }\n } finally {\n await client.end().catch(() => undefined)\n }\n}\n\nexport function startLazySchedulerSupervisor(\n options: LazySchedulerSupervisorOptions,\n): LazySchedulerSupervisorHandle {\n const logger = options.logger ?? console\n const probe = options.probeFn ?? probeEnabledSchedules\n const spawnFn: LazySchedulerSupervisorSpawnFn =\n options.spawnFn ?? ((command, args, opts) => nodeSpawn(command, args as string[], opts))\n\n let stopping = false\n let started = false\n let starting = false\n let activeChild: ChildProcess | undefined\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let lastProbeErrorLoggedAt = 0\n let doneResolve: (() => void) | null = null\n const done = new Promise<void>((resolve) => {\n doneResolve = resolve\n })\n\n logger.log('[lazy-scheduler] Watching for enabled schedules before starting the polling engine.')\n\n function logProbeError(message: string): void {\n const now = Date.now()\n if (now - lastProbeErrorLoggedAt < PROBE_ERROR_LOG_THROTTLE_MS) return\n lastProbeErrorLoggedAt = now\n logger.warn(`[lazy-scheduler] Schedule probe failed: ${message}`)\n }\n\n function spawnScheduler(): void {\n if (stopping || activeChild || starting) return\n starting = true\n logger.log('[lazy-scheduler] Enabled schedule detected - starting scheduler polling engine.')\n\n let child: ChildProcess\n try {\n child = spawnFn('node', [options.mercatoBin, 'scheduler', 'start'], {\n stdio: 'inherit',\n env: options.runtimeEnv,\n cwd: options.appDir,\n })\n } catch (error) {\n starting = false\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[lazy-scheduler] Failed to spawn scheduler: ${message}`)\n return\n }\n\n activeChild = child\n started = true\n starting = false\n options.onSpawn?.(child)\n\n child.on('exit', (code, signal) => {\n activeChild = undefined\n options.onChildExit?.(code, signal)\n if (stopping) return\n const expected = signal === 'SIGTERM' || signal === 'SIGINT'\n if (expected) return\n const reason = code !== null ? `code ${code}` : `signal ${signal ?? 'unknown'}`\n logger.warn(`[lazy-scheduler] Scheduler polling engine exited (${reason}).`)\n if (!options.restartOnUnexpectedExit) return\n void (async () => {\n const result = await safeProbe()\n if (!result || result.error) return\n if (result.enabledSchedules > 0) {\n logger.warn('[lazy-scheduler] Restarting scheduler because enabled schedules still exist.')\n spawnScheduler()\n }\n })()\n })\n }\n\n async function safeProbe(): Promise<SchedulerScheduleProbeResult | null> {\n try {\n return await probe(options.runtimeEnv)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logProbeError(message)\n return null\n }\n }\n\n async function tickOnce(): Promise<void> {\n if (stopping || activeChild || starting) return\n const result = await safeProbe()\n if (!result) return\n if (result.error) {\n if (result.errorMessage) logProbeError(result.errorMessage)\n return\n }\n if (result.enabledSchedules > 0) {\n spawnScheduler()\n }\n }\n\n function scheduleNext(): void {\n if (stopping || activeChild) return\n pollTimer = setTimeout(() => {\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Poll cycle failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n }, options.pollMs)\n pollTimer.unref?.()\n }\n\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Initial poll failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) {\n await done\n return\n }\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n\n const child = activeChild\n if (child) {\n await new Promise<void>((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) return resolve()\n child.once('exit', () => resolve())\n try {\n if (!child.killed) child.kill('SIGTERM')\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Failed to send SIGTERM to scheduler: ${message}`)\n resolve()\n }\n })\n activeChild = undefined\n }\n\n doneResolve?.()\n doneResolve = null\n }\n\n return {\n get started() {\n return started\n },\n getActiveChild: () => activeChild,\n close,\n done,\n }\n}\n"],
5
- "mappings": "AASA,SAAS,SAAS,iBAAiB;AAEnC,SAAS,oBAAoB;AAuC7B,MAAM,8BAA8B;AAEpC,SAAS,YAAY,OAAwB;AAC3C,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;AAC7F,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK;AAClD,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,SAAS,OAAO,KAAK;AAC3B,WAAO,OAAO,SAAS,MAAM,IAAI,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,CAAC,IAAI;AAAA,EACrE;AACA,SAAO;A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G;AAEH,iBAAe,QAAuB;AACpC,QAAI,UAAU;AACZ,YAAM;AACN;AAAA,IACF;AACA,eAAW;AACX,QAAI,WAAW;AACb,mBAAa,SAAS;AACtB,kBAAY;AAAA,IACd;AAEA,UAAM,QAAQ;AACd,QAAI,OAAO;AACT,YAAM,IAAI,QAAc,CAAC,YAAY;AACnC,YAAI,MAAM,aAAa,QAAQ,MAAM,eAAe,KAAM,QAAO,QAAQ;AACzE,cAAM,KAAK,QAAQ,MAAM,QAAQ,CAAC;AAClC,YAAI;AACF,cAAI,CAAC,MAAM,OAAQ,OAAM,KAAK,SAAS;AAAA,QACzC,SAAS,OAAO;AACd,gBAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,iBAAO,KAAK,yDAAyD,OAAO,EAAE;AAC9E,kBAAQ;AAAA,QACV;AAAA,MACF,CAAC;AACD,oBAAc;AAAA,IAChB;AAEA,kBAAc;AACd,kBAAc;AAAA,EAChB;AAEA,SAAO;AAAA,IACL,IAAI,UAAU;AACZ,aAAO;AAAA,IACT;AAAA,IACA,gBAAgB,MAAM;AAAA,IACtB;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * Lazy local scheduler supervisor.\n *\n * Keeps the server runtime from spawning the local scheduler polling engine\n * until at least one enabled schedule exists. The scheduler process itself is\n * still the existing `mercato scheduler start` command, so schedule execution,\n * locking, RBAC checks, and queue/command targets remain unchanged.\n */\n\nimport { spawn as nodeSpawn } from 'node:child_process'\nimport type { ChildProcess, SpawnOptions } from 'node:child_process'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\nimport { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'\nimport type { DatabasePoolLifecycle } from '@open-mercato/shared/lib/db/runtime'\n\nexport type SchedulerScheduleProbeResult = {\n enabledSchedules: number\n dueSchedules: number\n error?: boolean\n errorMessage?: string\n}\n\nexport type LazySchedulerSupervisorProbeFn = (\n env: NodeJS.ProcessEnv,\n) => Promise<SchedulerScheduleProbeResult>\n\nexport type LazySchedulerSupervisorSpawnFn = (\n command: string,\n args: readonly string[],\n options: SpawnOptions,\n) => ChildProcess\n\nexport type LazySchedulerSupervisorOptions = {\n mercatoBin: string\n appDir: string\n runtimeEnv: NodeJS.ProcessEnv\n pollMs: number\n restartOnUnexpectedExit: boolean\n spawnFn?: LazySchedulerSupervisorSpawnFn\n probeFn?: LazySchedulerSupervisorProbeFn\n logger?: Pick<Console, 'log' | 'warn' | 'error'>\n onSpawn?: (child: ChildProcess) => void\n onChildExit?: (code: number | null, signal: NodeJS.Signals | null) => void\n}\n\nexport type LazySchedulerSupervisorHandle = {\n readonly started: boolean\n getActiveChild(): ChildProcess | undefined\n close(): Promise<void>\n done: Promise<void>\n}\n\nconst PROBE_ERROR_LOG_THROTTLE_MS = 60_000\n\nfunction coerceCount(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.floor(value))\n if (typeof value === 'bigint') return Number(value)\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : 0\n }\n return 0\n}\n\nfunction isMissingScheduledJobsTableError(error: unknown): boolean {\n return Boolean(\n error\n && typeof error === 'object'\n && 'code' in error\n && (error as { code?: unknown }).code === '42P01',\n )\n}\n\nexport async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env): Promise<SchedulerScheduleProbeResult> {\n const databaseUrl = env.DATABASE_URL?.trim()\n if (!databaseUrl) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: 'DATABASE_URL is not set',\n }\n }\n\n if (isDatabaseRuntimeEnabled()) {\n return runWithFreshDatabaseExecutionContext({\n kind: 'maintenance', tenantId: null, source: 'scheduler', operation: 'scheduler.lazy-probe',\n }, () => probeScheduleConnection(databaseUrl, true))\n }\n return probeScheduleConnection(databaseUrl, false)\n}\n\nasync function probeScheduleConnection(databaseUrl: string, maintenance: boolean): Promise<SchedulerScheduleProbeResult> {\n let clientEnded = false\n let lifecycle: DatabasePoolLifecycle | undefined\n let release: (() => void) | undefined\n let client: InstanceType<typeof import('pg').Client> | undefined\n try {\n const { Client } = await import('pg')\n client = new Client({\n connectionString: maintenance ? resolveDatabaseConnectionUrl('maintenance', databaseUrl) : databaseUrl,\n ssl: getSslConfig(),\n ...(maintenance ? { connectionTimeoutMillis: 5000, query_timeout: 5000 } : {}),\n })\n\n await client.connect()\n let connection: Pick<InstanceType<typeof Client>, 'query'> = client\n if (maintenance) {\n const physical = { query: client.query.bind(client), release: () => undefined }\n const pool = { connect: async () => physical, get ended() { return clientEnded } }\n lifecycle = configureDatabasePool(pool, { id: 'scheduler-lazy-probe', purpose: 'maintenance', tables: ['scheduled_jobs'] })\n await lifecycle.ready()\n const guarded = await pool.connect()\n connection = guarded\n release = guarded.release\n }\n const result = await connection.query(`\n select\n count(*)::int as enabled_schedules,\n count(*) filter (where next_run_at <= now())::int as due_schedules\n from scheduled_jobs\n where is_enabled = true\n and deleted_at is null\n `)\n const row = result.rows[0] ?? {}\n return {\n enabledSchedules: coerceCount(row.enabled_schedules),\n dueSchedules: coerceCount(row.due_schedules),\n error: false,\n }\n } catch (error) {\n if (isMissingScheduledJobsTableError(error)) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: false,\n }\n }\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n }\n } finally {\n try { release?.() } finally {\n try {\n if (client) {\n await client.end()\n clientEnded = true\n }\n } finally { lifecycle?.dispose() }\n }\n }\n}\n\nexport function startLazySchedulerSupervisor(\n options: LazySchedulerSupervisorOptions,\n): LazySchedulerSupervisorHandle {\n const logger = options.logger ?? console\n const probe = options.probeFn ?? probeEnabledSchedules\n const spawnFn: LazySchedulerSupervisorSpawnFn =\n options.spawnFn ?? ((command, args, opts) => nodeSpawn(command, args as string[], opts))\n\n let stopping = false\n let started = false\n let starting = false\n let activeChild: ChildProcess | undefined\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let lastProbeErrorLoggedAt = 0\n let doneResolve: (() => void) | null = null\n const done = new Promise<void>((resolve) => {\n doneResolve = resolve\n })\n\n logger.log('[lazy-scheduler] Watching for enabled schedules before starting the polling engine.')\n\n function logProbeError(message: string): void {\n const now = Date.now()\n if (now - lastProbeErrorLoggedAt < PROBE_ERROR_LOG_THROTTLE_MS) return\n lastProbeErrorLoggedAt = now\n logger.warn(`[lazy-scheduler] Schedule probe failed: ${message}`)\n }\n\n function spawnScheduler(): void {\n if (stopping || activeChild || starting) return\n starting = true\n logger.log('[lazy-scheduler] Enabled schedule detected - starting scheduler polling engine.')\n\n let child: ChildProcess\n try {\n child = spawnFn('node', [options.mercatoBin, 'scheduler', 'start'], {\n stdio: 'inherit',\n env: options.runtimeEnv,\n cwd: options.appDir,\n })\n } catch (error) {\n starting = false\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[lazy-scheduler] Failed to spawn scheduler: ${message}`)\n return\n }\n\n activeChild = child\n started = true\n starting = false\n options.onSpawn?.(child)\n\n child.on('exit', (code, signal) => {\n activeChild = undefined\n options.onChildExit?.(code, signal)\n if (stopping) return\n const expected = signal === 'SIGTERM' || signal === 'SIGINT'\n if (expected) return\n const reason = code !== null ? `code ${code}` : `signal ${signal ?? 'unknown'}`\n logger.warn(`[lazy-scheduler] Scheduler polling engine exited (${reason}).`)\n if (!options.restartOnUnexpectedExit) return\n void (async () => {\n const result = await safeProbe()\n if (!result || result.error) return\n if (result.enabledSchedules > 0) {\n logger.warn('[lazy-scheduler] Restarting scheduler because enabled schedules still exist.')\n spawnScheduler()\n }\n })()\n })\n }\n\n async function safeProbe(): Promise<SchedulerScheduleProbeResult | null> {\n try {\n return await probe(options.runtimeEnv)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logProbeError(message)\n return null\n }\n }\n\n async function tickOnce(): Promise<void> {\n if (stopping || activeChild || starting) return\n const result = await safeProbe()\n if (!result) return\n if (result.error) {\n if (result.errorMessage) logProbeError(result.errorMessage)\n return\n }\n if (result.enabledSchedules > 0) {\n spawnScheduler()\n }\n }\n\n function scheduleNext(): void {\n if (stopping || activeChild) return\n pollTimer = setTimeout(() => {\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Poll cycle failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n }, options.pollMs)\n pollTimer.unref?.()\n }\n\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Initial poll failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) {\n await done\n return\n }\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n\n const child = activeChild\n if (child) {\n await new Promise<void>((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) return resolve()\n child.once('exit', () => resolve())\n try {\n if (!child.killed) child.kill('SIGTERM')\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Failed to send SIGTERM to scheduler: ${message}`)\n resolve()\n }\n })\n activeChild = undefined\n }\n\n doneResolve?.()\n doneResolve = null\n }\n\n return {\n get started() {\n return started\n },\n getActiveChild: () => activeChild,\n close,\n done,\n }\n}\n"],
5
+ "mappings": "AASA,SAAS,SAAS,iBAAiB;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,0BAA0B,8BAA8B,4CAA4C;AAwCpI,MAAM,8BAA8B;AAEpC,SAAS,YAAY,OAAwB;AAC3C,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;AAC7F,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KA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;AACtB,kBAAY;AAAA,IACd;AAEA,UAAM,QAAQ;AACd,QAAI,OAAO;AACT,YAAM,IAAI,QAAc,CAAC,YAAY;AACnC,YAAI,MAAM,aAAa,QAAQ,MAAM,eAAe,KAAM,QAAO,QAAQ;AACzE,cAAM,KAAK,QAAQ,MAAM,QAAQ,CAAC;AAClC,YAAI;AACF,cAAI,CAAC,MAAM,OAAQ,OAAM,KAAK,SAAS;AAAA,QACzC,SAAS,OAAO;AACd,gBAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,iBAAO,KAAK,yDAAyD,OAAO,EAAE;AAC9E,kBAAQ;AAAA,QACV;AAAA,MACF,CAAC;AACD,oBAAc;AAAA,IAChB;AAEA,kBAAc;AACd,kBAAc;AAAA,EAChB;AAEA,SAAO;AAAA,IACL,IAAI,UAAU;AACZ,aAAO;AAAA,IACT;AAAA,IACA,gBAAgB,MAAM;AAAA,IACtB;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -32,9 +32,21 @@ function normalizePath(filePath) {
32
32
  function normalizeModuleId(moduleId) {
33
33
  return moduleId.trim().toLowerCase();
34
34
  }
35
+ function normalizeSpecPath(specPath) {
36
+ return specPath.trim().replace(/\\/g, "/").replace(/^(?:\.\/)+/, "");
37
+ }
35
38
  function parseIntegrationModuleList(value) {
36
39
  return new Set((value ?? "").split(",").map(normalizeModuleId).filter(Boolean));
37
40
  }
41
+ function parseIntegrationSpecList(value) {
42
+ return new Set((value ?? "").split(",").map(normalizeSpecPath).filter(Boolean));
43
+ }
44
+ function filterIntegrationSpecsForPaths(specs, specPaths) {
45
+ if (specPaths.size === 0) return specs;
46
+ const normalizedSpecPaths = new Set(Array.from(specPaths, normalizeSpecPath).filter(Boolean));
47
+ if (normalizedSpecPaths.size === 0) return specs;
48
+ return specs.filter((spec) => normalizedSpecPaths.has(normalizeSpecPath(spec.path)));
49
+ }
38
50
  function filterIntegrationSpecsForModules(specs, modules) {
39
51
  if (modules.size === 0) return specs;
40
52
  return specs.filter((spec) => {
@@ -467,9 +479,11 @@ export {
467
479
  SKIP_METADATA_FILTERS_INTEGRATION_ENV_VAR,
468
480
  discoverIntegrationSpecFiles,
469
481
  filterIntegrationSpecsForModules,
482
+ filterIntegrationSpecsForPaths,
470
483
  isAppOwnedIntegrationSpecPath,
471
484
  normalizePath,
472
485
  parseIntegrationModuleList,
486
+ parseIntegrationSpecList,
473
487
  resolveModuleDependenciesForSpec
474
488
  };
475
489
  //# sourceMappingURL=integration-discovery.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/testing/integration-discovery.ts"],
4
- "sourcesContent": ["import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'\nimport path from 'node:path'\nimport ts from 'typescript-js'\n\nexport type IntegrationSpecDiscoveryItem = {\n path: string\n moduleName: string | null\n isOverlay: boolean\n requiredModules: string[]\n requiredEnvVars: string[]\n requiredAnyEnvVars: string[]\n}\n\nconst MODULE_INTEGRATION_DIRECTORY_NAME = '__integration__'\nconst DISCOVERY_IGNORED_DIRS = new Set([\n 'node_modules',\n '.git',\n '.next',\n 'dist',\n '.turbo',\n 'coverage',\n 'test-results',\n '.yarn',\n '.cache',\n 'tmp',\n 'temp',\n '.claude',\n '.codex',\n])\nconst INTEGRATION_META_FILE_NAMES = ['meta.ts', 'index.ts'] as const\nconst INTEGRATION_META_DEPENDENCY_KEYS = ['dependsOnModules', 'requiredModules', 'requiresModules'] as const\nconst INTEGRATION_META_ALL_DEPENDENCY_KEYS = [...INTEGRATION_META_DEPENDENCY_KEYS, 'optionalModules'] as const\nconst INTEGRATION_META_REQUIRED_ENV_KEYS = ['requiredEnvVars', 'requiresEnvVars'] as const\nconst INTEGRATION_META_REQUIRED_ANY_ENV_KEYS = ['requiredAnyEnvVars', 'requiresAnyEnvVars'] as const\nconst DEFAULT_OVERLAY_ROOT = 'packages/enterprise'\nexport const APP_ONLY_INTEGRATION_ENV_VAR = 'OM_INTEGRATION_APP_ONLY'\nexport const SKIP_METADATA_FILTERS_INTEGRATION_ENV_VAR = 'OM_INTEGRATION_SKIP_METADATA_FILTERS'\nexport const DISCOVERY_SELECTION_REPORT_INTEGRATION_ENV_VAR = 'OM_INTEGRATION_DISCOVERY_SELECTION_REPORT'\n\nexport function normalizePath(filePath: string): string {\n return filePath.split(path.sep).join('/')\n}\n\nfunction normalizeModuleId(moduleId: string): string {\n return moduleId.trim().toLowerCase()\n}\n\nexport function parseIntegrationModuleList(value: string | undefined): Set<string> {\n return new Set((value ?? '').split(',').map(normalizeModuleId).filter(Boolean))\n}\n\nexport function filterIntegrationSpecsForModules<T extends Pick<IntegrationSpecDiscoveryItem, 'moduleName' | 'requiredModules'>>(\n specs: T[],\n modules: Set<string>,\n): T[] {\n if (modules.size === 0) return specs\n return specs.filter((spec) => {\n if (spec.moduleName === null) return true\n if (modules.has(normalizeModuleId(spec.moduleName))) return true\n return spec.requiredModules.some((moduleId) => modules.has(normalizeModuleId(moduleId)))\n })\n}\n\nfunction isEnterpriseModulesEnabled(): boolean {\n const rawValue = process.env.OM_ENABLE_ENTERPRISE_MODULES?.trim().toLowerCase()\n return rawValue === 'true' || rawValue === '1' || rawValue === 'yes' || rawValue === 'on'\n}\n\nfunction isAppOnlyDiscoveryEnabled(): boolean {\n const rawValue = process.env[APP_ONLY_INTEGRATION_ENV_VAR]?.trim().toLowerCase()\n return rawValue === 'true' || rawValue === '1' || rawValue === 'yes' || rawValue === 'on'\n}\n\nfunction isMetadataFilteringDisabled(): boolean {\n const rawValue = process.env[SKIP_METADATA_FILTERS_INTEGRATION_ENV_VAR]?.trim().toLowerCase()\n return rawValue === 'true' || rawValue === '1' || rawValue === 'yes' || rawValue === 'on'\n}\n\nexport function isAppOwnedIntegrationSpecPath(relativePath: string): boolean {\n return !normalizePath(relativePath).split('/').includes('node_modules')\n}\n\nfunction writeDiscoverySelectionReport(projectRoot: string, files: readonly IntegrationSpecDiscoveryItem[]): void {\n const reportFile = process.env[DISCOVERY_SELECTION_REPORT_INTEGRATION_ENV_VAR]?.trim()\n if (!reportFile) return\n writeFileSync(reportFile, JSON.stringify({ projectRoot, paths: files.map((file) => file.path) }))\n}\n\nfunction collectNamedDirectories(rootPath: string, directoryName: string): string[] {\n let entries\n try {\n entries = readdirSync(rootPath, { withFileTypes: true, encoding: 'utf8' })\n } catch {\n return []\n }\n\n const collected: string[] = []\n for (const entry of entries) {\n if (!entry.isDirectory()) continue\n if (DISCOVERY_IGNORED_DIRS.has(entry.name)) continue\n const absolutePath = path.join(rootPath, entry.name)\n if (entry.name === directoryName) {\n collected.push(absolutePath)\n }\n collected.push(...collectNamedDirectories(absolutePath, directoryName))\n }\n return collected\n}\n\nfunction collectSpecFilesFromDirectory(directoryPath: string): string[] {\n let entries\n try {\n entries = readdirSync(directoryPath, { withFileTypes: true, encoding: 'utf8' })\n } catch {\n return []\n }\n\n const collected: string[] = []\n for (const entry of entries) {\n const absolutePath = path.join(directoryPath, entry.name)\n if (entry.isDirectory()) {\n collected.push(...collectSpecFilesFromDirectory(absolutePath))\n continue\n }\n if (entry.isFile() && entry.name.endsWith('.spec.ts')) {\n collected.push(absolutePath)\n }\n }\n return collected\n}\n\nfunction collectDirectDirectoryNames(directoryPath: string): string[] {\n let entries\n try {\n entries = readdirSync(directoryPath, { withFileTypes: true, encoding: 'utf8' })\n } catch {\n return []\n }\n return entries\n .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))\n .map((entry) => entry.name)\n}\n\nfunction collectModuleIdsFromModulesRoot(modulesRoot: string, enabledModules: Set<string>): void {\n for (const moduleName of collectDirectDirectoryNames(modulesRoot)) {\n enabledModules.add(normalizeModuleId(moduleName))\n }\n}\n\nfunction readModuleEntryId(element: ts.Expression): string[] {\n if (!ts.isObjectLiteralExpression(element)) return []\n const idProperty = element.properties.find((property): property is ts.PropertyAssignment =>\n ts.isPropertyAssignment(property)\n && (\n (ts.isIdentifier(property.name) && property.name.text === 'id')\n || (ts.isStringLiteralLike(property.name) && property.name.text === 'id')\n ),\n )\n return idProperty && ts.isStringLiteralLike(idProperty.initializer)\n ? [idProperty.initializer.text]\n : []\n}\n\nfunction isPushOntoVariable(node: ts.Node, variableName: string): node is ts.CallExpression {\n return ts.isCallExpression(node)\n && ts.isPropertyAccessExpression(node.expression)\n && node.expression.name.text === 'push'\n && ts.isIdentifier(node.expression.expression)\n && node.expression.expression.text === variableName\n}\n\n/**\n * Module ids a registry file declares for `variableName`: the entries of its array\n * literal initializer and, with `includePushes`, every `variableName.push({ id })` call.\n * Pushes are usually conditional (enterprise or env-gated modules), so including them\n * yields an upper bound of what the app can register, never narrower than the runtime set.\n */\nfunction readDeclaredModuleIdsFromConfig(\n registryPath: string,\n options: { variableName?: string; includePushes?: boolean; optional?: boolean } = {},\n): string[] {\n const variableName = options.variableName ?? 'enabledModules'\n if (options.optional && !existsSync(registryPath)) return []\n const source = readFileSync(registryPath, 'utf8')\n const sourceFile = ts.createSourceFile(\n registryPath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const declared: string[] = []\n const visit = (node: ts.Node): void => {\n if (\n ts.isVariableDeclaration(node)\n && ts.isVariableStatement(node.parent.parent)\n && node.parent.parent.parent === sourceFile\n && ts.isIdentifier(node.name)\n && node.name.text === variableName\n && node.initializer\n && ts.isArrayLiteralExpression(node.initializer)\n ) {\n declared.push(...node.initializer.elements.flatMap(readModuleEntryId))\n }\n if (options.includePushes && isPushOntoVariable(node, variableName)) {\n declared.push(...node.arguments.flatMap(readModuleEntryId))\n }\n ts.forEachChild(node, visit)\n }\n visit(sourceFile)\n return declared\n}\n\nfunction resolveTestAppRoot(): string | null {\n const configuredTestAppRoot = process.env.OM_TEST_APP_ROOT?.trim()\n return configuredTestAppRoot ? path.resolve(configuredTestAppRoot) : null\n}\n\n/**\n * Every module a standalone test app may register: its `enabledModules` literal, its\n * conditional `enabledModules.push(...)` entries, and its official-module activations.\n * Used to skip specs whose owning module the app does not ship at all.\n */\nfunction resolvePossiblyEnabledTestAppModuleIds(testAppRoot: string): Set<string> {\n return new Set(\n [\n ...readDeclaredModuleIdsFromConfig(path.join(testAppRoot, 'src', 'modules.ts'), { includePushes: true }),\n ...readDeclaredModuleIdsFromConfig(\n path.join(testAppRoot, 'src', 'official-modules.generated.ts'),\n { variableName: 'officialModuleEntries', includePushes: true, optional: true },\n ),\n ].map(normalizeModuleId),\n )\n}\n\nfunction resolveEnabledModuleIds(projectRoot: string): Set<string> {\n const testAppRoot = resolveTestAppRoot()\n if (testAppRoot) {\n return new Set(\n readDeclaredModuleIdsFromConfig(path.join(testAppRoot, 'src', 'modules.ts')).map(normalizeModuleId),\n )\n }\n\n const enabledModules = new Set<string>()\n const appModulesRoot = path.join(projectRoot, 'src', 'modules')\n const appsRoot = path.join(projectRoot, 'apps')\n const packagesRoot = path.join(projectRoot, 'packages')\n const installedPackagesRoot = path.join(projectRoot, 'node_modules', '@open-mercato')\n const enterpriseEnabled = isEnterpriseModulesEnabled()\n\n // Standalone app: src/modules at project root\n collectModuleIdsFromModulesRoot(appModulesRoot, enabledModules)\n\n for (const appName of collectDirectDirectoryNames(appsRoot)) {\n const moduleRoot = path.join(appsRoot, appName, 'src', 'modules')\n collectModuleIdsFromModulesRoot(moduleRoot, enabledModules)\n }\n for (const packageName of collectDirectDirectoryNames(packagesRoot)) {\n if (packageName === 'enterprise' && !enterpriseEnabled) {\n continue\n }\n const moduleRoot = path.join(packagesRoot, packageName, 'src', 'modules')\n collectModuleIdsFromModulesRoot(moduleRoot, enabledModules)\n }\n // Standalone app: installed @open-mercato packages in node_modules\n for (const packageName of collectDirectDirectoryNames(installedPackagesRoot)) {\n if (packageName === 'enterprise' && !enterpriseEnabled) {\n continue\n }\n const moduleRoot = path.join(installedPackagesRoot, packageName, 'src', 'modules')\n collectModuleIdsFromModulesRoot(moduleRoot, enabledModules)\n }\n const createAppTemplateModulesRoot = path.join(projectRoot, 'packages', 'create-app', 'template', 'src', 'modules')\n collectModuleIdsFromModulesRoot(createAppTemplateModulesRoot, enabledModules)\n\n return enabledModules\n}\n\nfunction extractModuleNameFromIntegrationPath(relativePath: string): string | null {\n const segments = normalizePath(relativePath).split('/')\n const integrationDirectoryIndex = segments.indexOf(MODULE_INTEGRATION_DIRECTORY_NAME)\n if (integrationDirectoryIndex <= 0) {\n return null\n }\n const moduleSegment = segments[integrationDirectoryIndex - 1]\n return moduleSegment && moduleSegment.length > 0 ? moduleSegment : null\n}\n\n/**\n * The module a spec belongs to: the directory directly under the closest `modules/`\n * ancestor of `__integration__`, provided that directory is a real module (it ships an\n * `index.ts`/`index.js`). Returns null for specs outside a module, e.g. `packages/ui`.\n */\nfunction resolveOwningModuleId(projectRoot: string, relativeSpecPath: string): string | null {\n const segments = normalizePath(relativeSpecPath).split('/')\n const integrationDirectoryIndex = segments.indexOf(MODULE_INTEGRATION_DIRECTORY_NAME)\n if (integrationDirectoryIndex <= 0) return null\n const modulesSegmentIndex = segments.lastIndexOf('modules', integrationDirectoryIndex - 1)\n if (modulesSegmentIndex === -1 || modulesSegmentIndex + 1 >= integrationDirectoryIndex) return null\n const moduleRoot = path.join(projectRoot, ...segments.slice(0, modulesSegmentIndex + 2))\n const isRealModule = ['index.ts', 'index.js'].some((fileName) => existsSync(path.join(moduleRoot, fileName)))\n return isRealModule ? normalizeModuleId(segments[modulesSegmentIndex + 1]) : null\n}\n\nfunction resolveOverlayRootPath(): string {\n const configured = process.env.OM_INTEGRATION_OVERLAY_ROOT?.trim()\n if (!configured) {\n return DEFAULT_OVERLAY_ROOT\n }\n return configured.replace(/\\/+$/, '')\n}\n\nfunction isOverlayIntegrationPath(relativePath: string, overlayRoot: string): boolean {\n return normalizePath(relativePath).startsWith(`${normalizePath(overlayRoot)}/`)\n}\n\nfunction extractStringArrayFromSource(source: string, keys: readonly string[]): string[] {\n const collected = new Set<string>()\n for (const key of keys) {\n const keyPattern = new RegExp(`${key}\\\\s*:\\\\s*\\\\[([\\\\s\\\\S]*?)\\\\]`, 'm')\n const keyMatch = source.match(keyPattern)\n if (!keyMatch?.[1]) continue\n const valuesPattern = /['\"`]([a-zA-Z0-9_.-]+)['\"`]/g\n for (const valueMatch of keyMatch[1].matchAll(valuesPattern)) {\n const value = String(valueMatch[1] ?? '').trim()\n if (value) {\n collected.add(value)\n }\n }\n }\n return Array.from(collected)\n}\n\nfunction extractDependencyListFromSource(source: string, includeOptional: boolean): string[] {\n const keys = includeOptional ? INTEGRATION_META_ALL_DEPENDENCY_KEYS : INTEGRATION_META_DEPENDENCY_KEYS\n return extractStringArrayFromSource(source, keys).map(normalizeModuleId)\n}\n\nfunction extractRequiredEnvVarsFromSource(source: string): string[] {\n return extractStringArrayFromSource(source, INTEGRATION_META_REQUIRED_ENV_KEYS)\n}\n\nfunction extractRequiredAnyEnvVarsFromSource(source: string): string[] {\n return extractStringArrayFromSource(source, INTEGRATION_META_REQUIRED_ANY_ENV_KEYS)\n}\n\nfunction readDependenciesFromMetadataFile(absolutePath: string, includeOptional: boolean): string[] {\n try {\n return extractDependencyListFromSource(readFileSync(absolutePath, 'utf8'), includeOptional)\n } catch {\n return []\n }\n}\n\nfunction readRequiredEnvVarsFromMetadataFile(absolutePath: string): string[] {\n try {\n return extractRequiredEnvVarsFromSource(readFileSync(absolutePath, 'utf8'))\n } catch {\n return []\n }\n}\n\nfunction readRequiredAnyEnvVarsFromMetadataFile(absolutePath: string): string[] {\n try {\n return extractRequiredAnyEnvVarsFromSource(readFileSync(absolutePath, 'utf8'))\n } catch {\n return []\n }\n}\n\nfunction resolveIntegrationRootDirectory(relativeSpecPath: string): string | null {\n const segments = normalizePath(relativeSpecPath).split('/')\n const integrationDirectoryIndex = segments.indexOf(MODULE_INTEGRATION_DIRECTORY_NAME)\n if (integrationDirectoryIndex === -1) {\n return null\n }\n return segments.slice(0, integrationDirectoryIndex + 1).join('/')\n}\n\nexport function resolveModuleDependenciesForSpec(\n projectRoot: string,\n relativeSpecPath: string,\n { includeOptional = false }: { includeOptional?: boolean } = {},\n): string[] {\n const requiredModules = new Set<string>()\n const normalizedSpecPath = normalizePath(relativeSpecPath)\n const absoluteSpecPath = path.join(projectRoot, normalizedSpecPath)\n const integrationRoot = resolveIntegrationRootDirectory(normalizedSpecPath)\n\n if (integrationRoot) {\n const relativeDirectory = normalizePath(path.dirname(normalizedSpecPath))\n const integrationRootAbsolute = path.join(projectRoot, integrationRoot)\n const directoryAbsolute = path.join(projectRoot, relativeDirectory)\n const relativeFromIntegrationRoot = normalizePath(path.relative(integrationRootAbsolute, directoryAbsolute))\n const pathSegments = relativeFromIntegrationRoot === '.'\n ? []\n : relativeFromIntegrationRoot.split('/').filter(Boolean)\n\n let currentDirectory = integrationRootAbsolute\n const traversal = [currentDirectory, ...pathSegments.map((segment) => {\n currentDirectory = path.join(currentDirectory, segment)\n return currentDirectory\n })]\n\n for (const directoryPath of traversal) {\n for (const metadataFileName of INTEGRATION_META_FILE_NAMES) {\n const metadataPath = path.join(directoryPath, metadataFileName)\n readDependenciesFromMetadataFile(metadataPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))\n }\n }\n }\n\n readDependenciesFromMetadataFile(absoluteSpecPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))\n const specFileName = path.basename(normalizedSpecPath, '.spec.ts')\n const perTestMetadataPath = path.join(path.dirname(absoluteSpecPath), `${specFileName}.meta.ts`)\n readDependenciesFromMetadataFile(perTestMetadataPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))\n\n return Array.from(requiredModules)\n}\n\nfunction resolveRequiredEnvVarsForSpec(projectRoot: string, relativeSpecPath: string): string[] {\n const requiredEnvVars = new Set<string>()\n const normalizedSpecPath = normalizePath(relativeSpecPath)\n const absoluteSpecPath = path.join(projectRoot, normalizedSpecPath)\n const integrationRoot = resolveIntegrationRootDirectory(normalizedSpecPath)\n\n if (integrationRoot) {\n const relativeDirectory = normalizePath(path.dirname(normalizedSpecPath))\n const integrationRootAbsolute = path.join(projectRoot, integrationRoot)\n const directoryAbsolute = path.join(projectRoot, relativeDirectory)\n const relativeFromIntegrationRoot = normalizePath(path.relative(integrationRootAbsolute, directoryAbsolute))\n const pathSegments = relativeFromIntegrationRoot === '.'\n ? []\n : relativeFromIntegrationRoot.split('/').filter(Boolean)\n\n let currentDirectory = integrationRootAbsolute\n const traversal = [currentDirectory, ...pathSegments.map((segment) => {\n currentDirectory = path.join(currentDirectory, segment)\n return currentDirectory\n })]\n\n for (const directoryPath of traversal) {\n for (const metadataFileName of INTEGRATION_META_FILE_NAMES) {\n const metadataPath = path.join(directoryPath, metadataFileName)\n readRequiredEnvVarsFromMetadataFile(metadataPath).forEach((envVar) => requiredEnvVars.add(envVar))\n }\n }\n }\n\n readRequiredEnvVarsFromMetadataFile(absoluteSpecPath).forEach((envVar) => requiredEnvVars.add(envVar))\n const specFileName = path.basename(normalizedSpecPath, '.spec.ts')\n const perTestMetadataPath = path.join(path.dirname(absoluteSpecPath), `${specFileName}.meta.ts`)\n readRequiredEnvVarsFromMetadataFile(perTestMetadataPath).forEach((envVar) => requiredEnvVars.add(envVar))\n\n return Array.from(requiredEnvVars)\n}\n\nfunction resolveRequiredAnyEnvVarsForSpec(projectRoot: string, relativeSpecPath: string): string[] {\n const requiredAnyEnvVars = new Set<string>()\n const normalizedSpecPath = normalizePath(relativeSpecPath)\n const absoluteSpecPath = path.join(projectRoot, normalizedSpecPath)\n const integrationRoot = resolveIntegrationRootDirectory(normalizedSpecPath)\n\n if (integrationRoot) {\n const relativeDirectory = normalizePath(path.dirname(normalizedSpecPath))\n const integrationRootAbsolute = path.join(projectRoot, integrationRoot)\n const directoryAbsolute = path.join(projectRoot, relativeDirectory)\n const relativeFromIntegrationRoot = normalizePath(path.relative(integrationRootAbsolute, directoryAbsolute))\n const pathSegments = relativeFromIntegrationRoot === '.'\n ? []\n : relativeFromIntegrationRoot.split('/').filter(Boolean)\n\n let currentDirectory = integrationRootAbsolute\n const traversal = [currentDirectory, ...pathSegments.map((segment) => {\n currentDirectory = path.join(currentDirectory, segment)\n return currentDirectory\n })]\n\n for (const directoryPath of traversal) {\n for (const metadataFileName of INTEGRATION_META_FILE_NAMES) {\n const metadataPath = path.join(directoryPath, metadataFileName)\n readRequiredAnyEnvVarsFromMetadataFile(metadataPath).forEach((envVar) => requiredAnyEnvVars.add(envVar))\n }\n }\n }\n\n readRequiredAnyEnvVarsFromMetadataFile(absoluteSpecPath).forEach((envVar) => requiredAnyEnvVars.add(envVar))\n const specFileName = path.basename(normalizedSpecPath, '.spec.ts')\n const perTestMetadataPath = path.join(path.dirname(absoluteSpecPath), `${specFileName}.meta.ts`)\n readRequiredAnyEnvVarsFromMetadataFile(perTestMetadataPath).forEach((envVar) => requiredAnyEnvVars.add(envVar))\n\n return Array.from(requiredAnyEnvVars)\n}\n\nfunction isEnvironmentVariableConfigured(name: string): boolean {\n const value = process.env[name]\n return typeof value === 'string' && value.trim().length > 0\n}\n\nexport function discoverIntegrationSpecFiles(projectRoot: string, legacyIntegrationRoot: string): IntegrationSpecDiscoveryItem[] {\n const discoveredByPath = new Map<string, IntegrationSpecDiscoveryItem>()\n const overlayRoot = resolveOverlayRootPath()\n const enterpriseEnabled = isEnterpriseModulesEnabled()\n const appOnly = isAppOnlyDiscoveryEnabled()\n const discoveryRoots = [\n path.join(projectRoot, 'src', 'modules'),\n path.join(projectRoot, 'apps'),\n path.join(projectRoot, 'packages'),\n ...(appOnly ? [] : [path.join(projectRoot, 'node_modules', '@open-mercato')]),\n ]\n\n for (const specFile of collectSpecFilesFromDirectory(legacyIntegrationRoot)) {\n const relativePath = normalizePath(path.relative(projectRoot, specFile))\n discoveredByPath.set(relativePath, {\n path: relativePath,\n moduleName: extractModuleNameFromIntegrationPath(relativePath),\n isOverlay: isOverlayIntegrationPath(relativePath, overlayRoot),\n requiredModules: resolveModuleDependenciesForSpec(projectRoot, relativePath),\n requiredEnvVars: resolveRequiredEnvVarsForSpec(projectRoot, relativePath),\n requiredAnyEnvVars: resolveRequiredAnyEnvVarsForSpec(projectRoot, relativePath),\n })\n }\n\n for (const root of discoveryRoots) {\n for (const integrationDirectory of collectNamedDirectories(root, MODULE_INTEGRATION_DIRECTORY_NAME)) {\n for (const specFile of collectSpecFilesFromDirectory(integrationDirectory)) {\n const relativePath = normalizePath(path.relative(projectRoot, specFile))\n discoveredByPath.set(relativePath, {\n path: relativePath,\n moduleName: extractModuleNameFromIntegrationPath(relativePath),\n isOverlay: isOverlayIntegrationPath(relativePath, overlayRoot),\n requiredModules: resolveModuleDependenciesForSpec(projectRoot, relativePath),\n requiredEnvVars: resolveRequiredEnvVarsForSpec(projectRoot, relativePath),\n requiredAnyEnvVars: resolveRequiredAnyEnvVarsForSpec(projectRoot, relativePath),\n })\n }\n }\n }\n\n const discovered = Array.from(discoveredByPath.values())\n .filter((file) => !appOnly || isAppOwnedIntegrationSpecPath(file.path))\n if (isMetadataFilteringDisabled()) {\n const selected = discovered.sort((left, right) => left.path.localeCompare(right.path))\n writeDiscoverySelectionReport(projectRoot, selected)\n return selected\n }\n const enabledModules = resolveEnabledModuleIds(projectRoot)\n const testAppRoot = resolveTestAppRoot()\n const testAppModules = testAppRoot ? resolvePossiblyEnabledTestAppModuleIds(testAppRoot) : null\n const enabledModuleNames = new Set<string>()\n for (const file of discovered) {\n if (!file.isOverlay && file.moduleName) {\n enabledModuleNames.add(file.moduleName)\n }\n }\n\n const selected = discovered\n .filter((file) => {\n if (file.requiredModules.some((moduleId) => !enabledModules.has(normalizeModuleId(moduleId)))) {\n return false\n }\n if (testAppModules && !file.isOverlay) {\n const owningModuleId = resolveOwningModuleId(projectRoot, file.path)\n if (owningModuleId && !testAppModules.has(owningModuleId)) {\n return false\n }\n }\n if (file.requiredEnvVars.some((envVar) => !isEnvironmentVariableConfigured(envVar))) {\n return false\n }\n if (\n file.requiredAnyEnvVars.length > 0 &&\n !file.requiredAnyEnvVars.some((envVar) => isEnvironmentVariableConfigured(envVar))\n ) {\n return false\n }\n if (!file.isOverlay) {\n return true\n }\n if (!enterpriseEnabled) {\n return false\n }\n if (!file.moduleName) {\n return true\n }\n if (enabledModuleNames.has(file.moduleName)) {\n return true\n }\n return enabledModules.has(normalizeModuleId(file.moduleName))\n })\n .sort((left, right) => left.path.localeCompare(right.path))\n writeDiscoverySelectionReport(projectRoot, selected)\n return selected\n}\n"],
5
- "mappings": "AAAA,SAAS,YAAY,cAAc,aAAa,qBAAqB;AACrE,OAAO,UAAU;AACjB,OAAO,QAAQ;AAWf,MAAM,oCAAoC;AAC1C,MAAM,yBAAyB,oBAAI,IAAI;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,8BAA8B,CAAC,WAAW,UAAU;AAC1D,MAAM,mCAAmC,CAAC,oBAAoB,mBAAmB,iBAAiB;AAClG,MAAM,uCAAuC,CAAC,GAAG,kCAAkC,iBAAiB;AACpG,MAAM,qCAAqC,CAAC,mBAAmB,iBAAiB;AAChF,MAAM,yCAAyC,CAAC,sBAAsB,oBAAoB;AAC1F,MAAM,uBAAuB;AACtB,MAAM,+BAA+B;AACrC,MAAM,4CAA4C;AAClD,MAAM,iDAAiD;AAEvD,SAAS,cAAc,UAA0B;AACtD,SAAO,SAAS,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;AAC1C;AAEA,SAAS,kBAAkB,UAA0B;AACnD,SAAO,SAAS,KAAK,EAAE,YAAY;AACrC;AAEO,SAAS,2BAA2B,OAAwC;AACjF,SAAO,IAAI,KAAK,SAAS,IAAI,MAAM,GAAG,EAAE,IAAI,iBAAiB,EAAE,OAAO,OAAO,CAAC;AAChF;AAEO,SAAS,iCACd,OACA,SACK;AACL,MAAI,QAAQ,SAAS,EAAG,QAAO;AAC/B,SAAO,MAAM,OAAO,CAAC,SAAS;AAC5B,QAAI,KAAK,eAAe,KAAM,QAAO;AACrC,QAAI,QAAQ,IAAI,kBAAkB,K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K,gBAAgB,KAAK,CAAC,WAAW,CAAC,gCAAgC,MAAM,CAAC,GAAG;AACnF,aAAO;AAAA,IACT;AACA,QACE,KAAK,mBAAmB,SAAS,KACjC,CAAC,KAAK,mBAAmB,KAAK,CAAC,WAAW,gCAAgC,MAAM,CAAC,GACjF;AACA,aAAO;AAAA,IACT;AACA,QAAI,CAAC,KAAK,WAAW;AACnB,aAAO;AAAA,IACT;AACA,QAAI,CAAC,mBAAmB;AACtB,aAAO;AAAA,IACT;AACA,QAAI,CAAC,KAAK,YAAY;AACpB,aAAO;AAAA,IACT;AACA,QAAI,mBAAmB,IAAI,KAAK,UAAU,GAAG;AAC3C,aAAO;AAAA,IACT;AACA,WAAO,eAAe,IAAI,kBAAkB,KAAK,UAAU,CAAC;AAAA,EAC9D,CAAC,EACA,KAAK,CAAC,MAAM,UAAU,KAAK,KAAK,cAAc,MAAM,IAAI,CAAC;AAC5D,gCAA8B,aAAa,QAAQ;AACnD,SAAO;AACT;",
4
+ "sourcesContent": ["import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'\nimport path from 'node:path'\nimport ts from 'typescript-js'\n\nexport type IntegrationSpecDiscoveryItem = {\n path: string\n moduleName: string | null\n isOverlay: boolean\n requiredModules: string[]\n requiredEnvVars: string[]\n requiredAnyEnvVars: string[]\n}\n\nconst MODULE_INTEGRATION_DIRECTORY_NAME = '__integration__'\nconst DISCOVERY_IGNORED_DIRS = new Set([\n 'node_modules',\n '.git',\n '.next',\n 'dist',\n '.turbo',\n 'coverage',\n 'test-results',\n '.yarn',\n '.cache',\n 'tmp',\n 'temp',\n '.claude',\n '.codex',\n])\nconst INTEGRATION_META_FILE_NAMES = ['meta.ts', 'index.ts'] as const\nconst INTEGRATION_META_DEPENDENCY_KEYS = ['dependsOnModules', 'requiredModules', 'requiresModules'] as const\nconst INTEGRATION_META_ALL_DEPENDENCY_KEYS = [...INTEGRATION_META_DEPENDENCY_KEYS, 'optionalModules'] as const\nconst INTEGRATION_META_REQUIRED_ENV_KEYS = ['requiredEnvVars', 'requiresEnvVars'] as const\nconst INTEGRATION_META_REQUIRED_ANY_ENV_KEYS = ['requiredAnyEnvVars', 'requiresAnyEnvVars'] as const\nconst DEFAULT_OVERLAY_ROOT = 'packages/enterprise'\nexport const APP_ONLY_INTEGRATION_ENV_VAR = 'OM_INTEGRATION_APP_ONLY'\nexport const SKIP_METADATA_FILTERS_INTEGRATION_ENV_VAR = 'OM_INTEGRATION_SKIP_METADATA_FILTERS'\nexport const DISCOVERY_SELECTION_REPORT_INTEGRATION_ENV_VAR = 'OM_INTEGRATION_DISCOVERY_SELECTION_REPORT'\n\nexport function normalizePath(filePath: string): string {\n return filePath.split(path.sep).join('/')\n}\n\nfunction normalizeModuleId(moduleId: string): string {\n return moduleId.trim().toLowerCase()\n}\n\nfunction normalizeSpecPath(specPath: string): string {\n return specPath.trim().replace(/\\\\/g, '/').replace(/^(?:\\.\\/)+/, '')\n}\n\nexport function parseIntegrationModuleList(value: string | undefined): Set<string> {\n return new Set((value ?? '').split(',').map(normalizeModuleId).filter(Boolean))\n}\n\nexport function parseIntegrationSpecList(value: string | undefined): Set<string> {\n return new Set((value ?? '').split(',').map(normalizeSpecPath).filter(Boolean))\n}\n\nexport function filterIntegrationSpecsForPaths<T extends Pick<IntegrationSpecDiscoveryItem, 'path'>>(\n specs: T[],\n specPaths: Set<string>,\n): T[] {\n if (specPaths.size === 0) return specs\n const normalizedSpecPaths = new Set(Array.from(specPaths, normalizeSpecPath).filter(Boolean))\n if (normalizedSpecPaths.size === 0) return specs\n return specs.filter((spec) => normalizedSpecPaths.has(normalizeSpecPath(spec.path)))\n}\n\nexport function filterIntegrationSpecsForModules<T extends Pick<IntegrationSpecDiscoveryItem, 'moduleName' | 'requiredModules'>>(\n specs: T[],\n modules: Set<string>,\n): T[] {\n if (modules.size === 0) return specs\n return specs.filter((spec) => {\n if (spec.moduleName === null) return true\n if (modules.has(normalizeModuleId(spec.moduleName))) return true\n return spec.requiredModules.some((moduleId) => modules.has(normalizeModuleId(moduleId)))\n })\n}\n\nfunction isEnterpriseModulesEnabled(): boolean {\n const rawValue = process.env.OM_ENABLE_ENTERPRISE_MODULES?.trim().toLowerCase()\n return rawValue === 'true' || rawValue === '1' || rawValue === 'yes' || rawValue === 'on'\n}\n\nfunction isAppOnlyDiscoveryEnabled(): boolean {\n const rawValue = process.env[APP_ONLY_INTEGRATION_ENV_VAR]?.trim().toLowerCase()\n return rawValue === 'true' || rawValue === '1' || rawValue === 'yes' || rawValue === 'on'\n}\n\nfunction isMetadataFilteringDisabled(): boolean {\n const rawValue = process.env[SKIP_METADATA_FILTERS_INTEGRATION_ENV_VAR]?.trim().toLowerCase()\n return rawValue === 'true' || rawValue === '1' || rawValue === 'yes' || rawValue === 'on'\n}\n\nexport function isAppOwnedIntegrationSpecPath(relativePath: string): boolean {\n return !normalizePath(relativePath).split('/').includes('node_modules')\n}\n\nfunction writeDiscoverySelectionReport(projectRoot: string, files: readonly IntegrationSpecDiscoveryItem[]): void {\n const reportFile = process.env[DISCOVERY_SELECTION_REPORT_INTEGRATION_ENV_VAR]?.trim()\n if (!reportFile) return\n writeFileSync(reportFile, JSON.stringify({ projectRoot, paths: files.map((file) => file.path) }))\n}\n\nfunction collectNamedDirectories(rootPath: string, directoryName: string): string[] {\n let entries\n try {\n entries = readdirSync(rootPath, { withFileTypes: true, encoding: 'utf8' })\n } catch {\n return []\n }\n\n const collected: string[] = []\n for (const entry of entries) {\n if (!entry.isDirectory()) continue\n if (DISCOVERY_IGNORED_DIRS.has(entry.name)) continue\n const absolutePath = path.join(rootPath, entry.name)\n if (entry.name === directoryName) {\n collected.push(absolutePath)\n }\n collected.push(...collectNamedDirectories(absolutePath, directoryName))\n }\n return collected\n}\n\nfunction collectSpecFilesFromDirectory(directoryPath: string): string[] {\n let entries\n try {\n entries = readdirSync(directoryPath, { withFileTypes: true, encoding: 'utf8' })\n } catch {\n return []\n }\n\n const collected: string[] = []\n for (const entry of entries) {\n const absolutePath = path.join(directoryPath, entry.name)\n if (entry.isDirectory()) {\n collected.push(...collectSpecFilesFromDirectory(absolutePath))\n continue\n }\n if (entry.isFile() && entry.name.endsWith('.spec.ts')) {\n collected.push(absolutePath)\n }\n }\n return collected\n}\n\nfunction collectDirectDirectoryNames(directoryPath: string): string[] {\n let entries\n try {\n entries = readdirSync(directoryPath, { withFileTypes: true, encoding: 'utf8' })\n } catch {\n return []\n }\n return entries\n .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))\n .map((entry) => entry.name)\n}\n\nfunction collectModuleIdsFromModulesRoot(modulesRoot: string, enabledModules: Set<string>): void {\n for (const moduleName of collectDirectDirectoryNames(modulesRoot)) {\n enabledModules.add(normalizeModuleId(moduleName))\n }\n}\n\nfunction readModuleEntryId(element: ts.Expression): string[] {\n if (!ts.isObjectLiteralExpression(element)) return []\n const idProperty = element.properties.find((property): property is ts.PropertyAssignment =>\n ts.isPropertyAssignment(property)\n && (\n (ts.isIdentifier(property.name) && property.name.text === 'id')\n || (ts.isStringLiteralLike(property.name) && property.name.text === 'id')\n ),\n )\n return idProperty && ts.isStringLiteralLike(idProperty.initializer)\n ? [idProperty.initializer.text]\n : []\n}\n\nfunction isPushOntoVariable(node: ts.Node, variableName: string): node is ts.CallExpression {\n return ts.isCallExpression(node)\n && ts.isPropertyAccessExpression(node.expression)\n && node.expression.name.text === 'push'\n && ts.isIdentifier(node.expression.expression)\n && node.expression.expression.text === variableName\n}\n\n/**\n * Module ids a registry file declares for `variableName`: the entries of its array\n * literal initializer and, with `includePushes`, every `variableName.push({ id })` call.\n * Pushes are usually conditional (enterprise or env-gated modules), so including them\n * yields an upper bound of what the app can register, never narrower than the runtime set.\n */\nfunction readDeclaredModuleIdsFromConfig(\n registryPath: string,\n options: { variableName?: string; includePushes?: boolean; optional?: boolean } = {},\n): string[] {\n const variableName = options.variableName ?? 'enabledModules'\n if (options.optional && !existsSync(registryPath)) return []\n const source = readFileSync(registryPath, 'utf8')\n const sourceFile = ts.createSourceFile(\n registryPath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const declared: string[] = []\n const visit = (node: ts.Node): void => {\n if (\n ts.isVariableDeclaration(node)\n && ts.isVariableStatement(node.parent.parent)\n && node.parent.parent.parent === sourceFile\n && ts.isIdentifier(node.name)\n && node.name.text === variableName\n && node.initializer\n && ts.isArrayLiteralExpression(node.initializer)\n ) {\n declared.push(...node.initializer.elements.flatMap(readModuleEntryId))\n }\n if (options.includePushes && isPushOntoVariable(node, variableName)) {\n declared.push(...node.arguments.flatMap(readModuleEntryId))\n }\n ts.forEachChild(node, visit)\n }\n visit(sourceFile)\n return declared\n}\n\nfunction resolveTestAppRoot(): string | null {\n const configuredTestAppRoot = process.env.OM_TEST_APP_ROOT?.trim()\n return configuredTestAppRoot ? path.resolve(configuredTestAppRoot) : null\n}\n\n/**\n * Every module a standalone test app may register: its `enabledModules` literal, its\n * conditional `enabledModules.push(...)` entries, and its official-module activations.\n * Used to skip specs whose owning module the app does not ship at all.\n */\nfunction resolvePossiblyEnabledTestAppModuleIds(testAppRoot: string): Set<string> {\n return new Set(\n [\n ...readDeclaredModuleIdsFromConfig(path.join(testAppRoot, 'src', 'modules.ts'), { includePushes: true }),\n ...readDeclaredModuleIdsFromConfig(\n path.join(testAppRoot, 'src', 'official-modules.generated.ts'),\n { variableName: 'officialModuleEntries', includePushes: true, optional: true },\n ),\n ].map(normalizeModuleId),\n )\n}\n\nfunction resolveEnabledModuleIds(projectRoot: string): Set<string> {\n const testAppRoot = resolveTestAppRoot()\n if (testAppRoot) {\n return new Set(\n readDeclaredModuleIdsFromConfig(path.join(testAppRoot, 'src', 'modules.ts')).map(normalizeModuleId),\n )\n }\n\n const enabledModules = new Set<string>()\n const appModulesRoot = path.join(projectRoot, 'src', 'modules')\n const appsRoot = path.join(projectRoot, 'apps')\n const packagesRoot = path.join(projectRoot, 'packages')\n const installedPackagesRoot = path.join(projectRoot, 'node_modules', '@open-mercato')\n const enterpriseEnabled = isEnterpriseModulesEnabled()\n\n // Standalone app: src/modules at project root\n collectModuleIdsFromModulesRoot(appModulesRoot, enabledModules)\n\n for (const appName of collectDirectDirectoryNames(appsRoot)) {\n const moduleRoot = path.join(appsRoot, appName, 'src', 'modules')\n collectModuleIdsFromModulesRoot(moduleRoot, enabledModules)\n }\n for (const packageName of collectDirectDirectoryNames(packagesRoot)) {\n if (packageName === 'enterprise' && !enterpriseEnabled) {\n continue\n }\n const moduleRoot = path.join(packagesRoot, packageName, 'src', 'modules')\n collectModuleIdsFromModulesRoot(moduleRoot, enabledModules)\n }\n // Standalone app: installed @open-mercato packages in node_modules\n for (const packageName of collectDirectDirectoryNames(installedPackagesRoot)) {\n if (packageName === 'enterprise' && !enterpriseEnabled) {\n continue\n }\n const moduleRoot = path.join(installedPackagesRoot, packageName, 'src', 'modules')\n collectModuleIdsFromModulesRoot(moduleRoot, enabledModules)\n }\n const createAppTemplateModulesRoot = path.join(projectRoot, 'packages', 'create-app', 'template', 'src', 'modules')\n collectModuleIdsFromModulesRoot(createAppTemplateModulesRoot, enabledModules)\n\n return enabledModules\n}\n\nfunction extractModuleNameFromIntegrationPath(relativePath: string): string | null {\n const segments = normalizePath(relativePath).split('/')\n const integrationDirectoryIndex = segments.indexOf(MODULE_INTEGRATION_DIRECTORY_NAME)\n if (integrationDirectoryIndex <= 0) {\n return null\n }\n const moduleSegment = segments[integrationDirectoryIndex - 1]\n return moduleSegment && moduleSegment.length > 0 ? moduleSegment : null\n}\n\n/**\n * The module a spec belongs to: the directory directly under the closest `modules/`\n * ancestor of `__integration__`, provided that directory is a real module (it ships an\n * `index.ts`/`index.js`). Returns null for specs outside a module, e.g. `packages/ui`.\n */\nfunction resolveOwningModuleId(projectRoot: string, relativeSpecPath: string): string | null {\n const segments = normalizePath(relativeSpecPath).split('/')\n const integrationDirectoryIndex = segments.indexOf(MODULE_INTEGRATION_DIRECTORY_NAME)\n if (integrationDirectoryIndex <= 0) return null\n const modulesSegmentIndex = segments.lastIndexOf('modules', integrationDirectoryIndex - 1)\n if (modulesSegmentIndex === -1 || modulesSegmentIndex + 1 >= integrationDirectoryIndex) return null\n const moduleRoot = path.join(projectRoot, ...segments.slice(0, modulesSegmentIndex + 2))\n const isRealModule = ['index.ts', 'index.js'].some((fileName) => existsSync(path.join(moduleRoot, fileName)))\n return isRealModule ? normalizeModuleId(segments[modulesSegmentIndex + 1]) : null\n}\n\nfunction resolveOverlayRootPath(): string {\n const configured = process.env.OM_INTEGRATION_OVERLAY_ROOT?.trim()\n if (!configured) {\n return DEFAULT_OVERLAY_ROOT\n }\n return configured.replace(/\\/+$/, '')\n}\n\nfunction isOverlayIntegrationPath(relativePath: string, overlayRoot: string): boolean {\n return normalizePath(relativePath).startsWith(`${normalizePath(overlayRoot)}/`)\n}\n\nfunction extractStringArrayFromSource(source: string, keys: readonly string[]): string[] {\n const collected = new Set<string>()\n for (const key of keys) {\n const keyPattern = new RegExp(`${key}\\\\s*:\\\\s*\\\\[([\\\\s\\\\S]*?)\\\\]`, 'm')\n const keyMatch = source.match(keyPattern)\n if (!keyMatch?.[1]) continue\n const valuesPattern = /['\"`]([a-zA-Z0-9_.-]+)['\"`]/g\n for (const valueMatch of keyMatch[1].matchAll(valuesPattern)) {\n const value = String(valueMatch[1] ?? '').trim()\n if (value) {\n collected.add(value)\n }\n }\n }\n return Array.from(collected)\n}\n\nfunction extractDependencyListFromSource(source: string, includeOptional: boolean): string[] {\n const keys = includeOptional ? INTEGRATION_META_ALL_DEPENDENCY_KEYS : INTEGRATION_META_DEPENDENCY_KEYS\n return extractStringArrayFromSource(source, keys).map(normalizeModuleId)\n}\n\nfunction extractRequiredEnvVarsFromSource(source: string): string[] {\n return extractStringArrayFromSource(source, INTEGRATION_META_REQUIRED_ENV_KEYS)\n}\n\nfunction extractRequiredAnyEnvVarsFromSource(source: string): string[] {\n return extractStringArrayFromSource(source, INTEGRATION_META_REQUIRED_ANY_ENV_KEYS)\n}\n\nfunction readDependenciesFromMetadataFile(absolutePath: string, includeOptional: boolean): string[] {\n try {\n return extractDependencyListFromSource(readFileSync(absolutePath, 'utf8'), includeOptional)\n } catch {\n return []\n }\n}\n\nfunction readRequiredEnvVarsFromMetadataFile(absolutePath: string): string[] {\n try {\n return extractRequiredEnvVarsFromSource(readFileSync(absolutePath, 'utf8'))\n } catch {\n return []\n }\n}\n\nfunction readRequiredAnyEnvVarsFromMetadataFile(absolutePath: string): string[] {\n try {\n return extractRequiredAnyEnvVarsFromSource(readFileSync(absolutePath, 'utf8'))\n } catch {\n return []\n }\n}\n\nfunction resolveIntegrationRootDirectory(relativeSpecPath: string): string | null {\n const segments = normalizePath(relativeSpecPath).split('/')\n const integrationDirectoryIndex = segments.indexOf(MODULE_INTEGRATION_DIRECTORY_NAME)\n if (integrationDirectoryIndex === -1) {\n return null\n }\n return segments.slice(0, integrationDirectoryIndex + 1).join('/')\n}\n\nexport function resolveModuleDependenciesForSpec(\n projectRoot: string,\n relativeSpecPath: string,\n { includeOptional = false }: { includeOptional?: boolean } = {},\n): string[] {\n const requiredModules = new Set<string>()\n const normalizedSpecPath = normalizePath(relativeSpecPath)\n const absoluteSpecPath = path.join(projectRoot, normalizedSpecPath)\n const integrationRoot = resolveIntegrationRootDirectory(normalizedSpecPath)\n\n if (integrationRoot) {\n const relativeDirectory = normalizePath(path.dirname(normalizedSpecPath))\n const integrationRootAbsolute = path.join(projectRoot, integrationRoot)\n const directoryAbsolute = path.join(projectRoot, relativeDirectory)\n const relativeFromIntegrationRoot = normalizePath(path.relative(integrationRootAbsolute, directoryAbsolute))\n const pathSegments = relativeFromIntegrationRoot === '.'\n ? []\n : relativeFromIntegrationRoot.split('/').filter(Boolean)\n\n let currentDirectory = integrationRootAbsolute\n const traversal = [currentDirectory, ...pathSegments.map((segment) => {\n currentDirectory = path.join(currentDirectory, segment)\n return currentDirectory\n })]\n\n for (const directoryPath of traversal) {\n for (const metadataFileName of INTEGRATION_META_FILE_NAMES) {\n const metadataPath = path.join(directoryPath, metadataFileName)\n readDependenciesFromMetadataFile(metadataPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))\n }\n }\n }\n\n readDependenciesFromMetadataFile(absoluteSpecPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))\n const specFileName = path.basename(normalizedSpecPath, '.spec.ts')\n const perTestMetadataPath = path.join(path.dirname(absoluteSpecPath), `${specFileName}.meta.ts`)\n readDependenciesFromMetadataFile(perTestMetadataPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))\n\n return Array.from(requiredModules)\n}\n\nfunction resolveRequiredEnvVarsForSpec(projectRoot: string, relativeSpecPath: string): string[] {\n const requiredEnvVars = new Set<string>()\n const normalizedSpecPath = normalizePath(relativeSpecPath)\n const absoluteSpecPath = path.join(projectRoot, normalizedSpecPath)\n const integrationRoot = resolveIntegrationRootDirectory(normalizedSpecPath)\n\n if (integrationRoot) {\n const relativeDirectory = normalizePath(path.dirname(normalizedSpecPath))\n const integrationRootAbsolute = path.join(projectRoot, integrationRoot)\n const directoryAbsolute = path.join(projectRoot, relativeDirectory)\n const relativeFromIntegrationRoot = normalizePath(path.relative(integrationRootAbsolute, directoryAbsolute))\n const pathSegments = relativeFromIntegrationRoot === '.'\n ? []\n : relativeFromIntegrationRoot.split('/').filter(Boolean)\n\n let currentDirectory = integrationRootAbsolute\n const traversal = [currentDirectory, ...pathSegments.map((segment) => {\n currentDirectory = path.join(currentDirectory, segment)\n return currentDirectory\n })]\n\n for (const directoryPath of traversal) {\n for (const metadataFileName of INTEGRATION_META_FILE_NAMES) {\n const metadataPath = path.join(directoryPath, metadataFileName)\n readRequiredEnvVarsFromMetadataFile(metadataPath).forEach((envVar) => requiredEnvVars.add(envVar))\n }\n }\n }\n\n readRequiredEnvVarsFromMetadataFile(absoluteSpecPath).forEach((envVar) => requiredEnvVars.add(envVar))\n const specFileName = path.basename(normalizedSpecPath, '.spec.ts')\n const perTestMetadataPath = path.join(path.dirname(absoluteSpecPath), `${specFileName}.meta.ts`)\n readRequiredEnvVarsFromMetadataFile(perTestMetadataPath).forEach((envVar) => requiredEnvVars.add(envVar))\n\n return Array.from(requiredEnvVars)\n}\n\nfunction resolveRequiredAnyEnvVarsForSpec(projectRoot: string, relativeSpecPath: string): string[] {\n const requiredAnyEnvVars = new Set<string>()\n const normalizedSpecPath = normalizePath(relativeSpecPath)\n const absoluteSpecPath = path.join(projectRoot, normalizedSpecPath)\n const integrationRoot = resolveIntegrationRootDirectory(normalizedSpecPath)\n\n if (integrationRoot) {\n const relativeDirectory = normalizePath(path.dirname(normalizedSpecPath))\n const integrationRootAbsolute = path.join(projectRoot, integrationRoot)\n const directoryAbsolute = path.join(projectRoot, relativeDirectory)\n const relativeFromIntegrationRoot = normalizePath(path.relative(integrationRootAbsolute, directoryAbsolute))\n const pathSegments = relativeFromIntegrationRoot === '.'\n ? []\n : relativeFromIntegrationRoot.split('/').filter(Boolean)\n\n let currentDirectory = integrationRootAbsolute\n const traversal = [currentDirectory, ...pathSegments.map((segment) => {\n currentDirectory = path.join(currentDirectory, segment)\n return currentDirectory\n })]\n\n for (const directoryPath of traversal) {\n for (const metadataFileName of INTEGRATION_META_FILE_NAMES) {\n const metadataPath = path.join(directoryPath, metadataFileName)\n readRequiredAnyEnvVarsFromMetadataFile(metadataPath).forEach((envVar) => requiredAnyEnvVars.add(envVar))\n }\n }\n }\n\n readRequiredAnyEnvVarsFromMetadataFile(absoluteSpecPath).forEach((envVar) => requiredAnyEnvVars.add(envVar))\n const specFileName = path.basename(normalizedSpecPath, '.spec.ts')\n const perTestMetadataPath = path.join(path.dirname(absoluteSpecPath), `${specFileName}.meta.ts`)\n readRequiredAnyEnvVarsFromMetadataFile(perTestMetadataPath).forEach((envVar) => requiredAnyEnvVars.add(envVar))\n\n return Array.from(requiredAnyEnvVars)\n}\n\nfunction isEnvironmentVariableConfigured(name: string): boolean {\n const value = process.env[name]\n return typeof value === 'string' && value.trim().length > 0\n}\n\nexport function discoverIntegrationSpecFiles(projectRoot: string, legacyIntegrationRoot: string): IntegrationSpecDiscoveryItem[] {\n const discoveredByPath = new Map<string, IntegrationSpecDiscoveryItem>()\n const overlayRoot = resolveOverlayRootPath()\n const enterpriseEnabled = isEnterpriseModulesEnabled()\n const appOnly = isAppOnlyDiscoveryEnabled()\n const discoveryRoots = [\n path.join(projectRoot, 'src', 'modules'),\n path.join(projectRoot, 'apps'),\n path.join(projectRoot, 'packages'),\n ...(appOnly ? [] : [path.join(projectRoot, 'node_modules', '@open-mercato')]),\n ]\n\n for (const specFile of collectSpecFilesFromDirectory(legacyIntegrationRoot)) {\n const relativePath = normalizePath(path.relative(projectRoot, specFile))\n discoveredByPath.set(relativePath, {\n path: relativePath,\n moduleName: extractModuleNameFromIntegrationPath(relativePath),\n isOverlay: isOverlayIntegrationPath(relativePath, overlayRoot),\n requiredModules: resolveModuleDependenciesForSpec(projectRoot, relativePath),\n requiredEnvVars: resolveRequiredEnvVarsForSpec(projectRoot, relativePath),\n requiredAnyEnvVars: resolveRequiredAnyEnvVarsForSpec(projectRoot, relativePath),\n })\n }\n\n for (const root of discoveryRoots) {\n for (const integrationDirectory of collectNamedDirectories(root, MODULE_INTEGRATION_DIRECTORY_NAME)) {\n for (const specFile of collectSpecFilesFromDirectory(integrationDirectory)) {\n const relativePath = normalizePath(path.relative(projectRoot, specFile))\n discoveredByPath.set(relativePath, {\n path: relativePath,\n moduleName: extractModuleNameFromIntegrationPath(relativePath),\n isOverlay: isOverlayIntegrationPath(relativePath, overlayRoot),\n requiredModules: resolveModuleDependenciesForSpec(projectRoot, relativePath),\n requiredEnvVars: resolveRequiredEnvVarsForSpec(projectRoot, relativePath),\n requiredAnyEnvVars: resolveRequiredAnyEnvVarsForSpec(projectRoot, relativePath),\n })\n }\n }\n }\n\n const discovered = Array.from(discoveredByPath.values())\n .filter((file) => !appOnly || isAppOwnedIntegrationSpecPath(file.path))\n if (isMetadataFilteringDisabled()) {\n const selected = discovered.sort((left, right) => left.path.localeCompare(right.path))\n writeDiscoverySelectionReport(projectRoot, selected)\n return selected\n }\n const enabledModules = resolveEnabledModuleIds(projectRoot)\n const testAppRoot = resolveTestAppRoot()\n const testAppModules = testAppRoot ? resolvePossiblyEnabledTestAppModuleIds(testAppRoot) : null\n const enabledModuleNames = new Set<string>()\n for (const file of discovered) {\n if (!file.isOverlay && file.moduleName) {\n enabledModuleNames.add(file.moduleName)\n }\n }\n\n const selected = discovered\n .filter((file) => {\n if (file.requiredModules.some((moduleId) => !enabledModules.has(normalizeModuleId(moduleId)))) {\n return false\n }\n if (testAppModules && !file.isOverlay) {\n const owningModuleId = resolveOwningModuleId(projectRoot, file.path)\n if (owningModuleId && !testAppModules.has(owningModuleId)) {\n return false\n }\n }\n if (file.requiredEnvVars.some((envVar) => !isEnvironmentVariableConfigured(envVar))) {\n return false\n }\n if (\n file.requiredAnyEnvVars.length > 0 &&\n !file.requiredAnyEnvVars.some((envVar) => isEnvironmentVariableConfigured(envVar))\n ) {\n return false\n }\n if (!file.isOverlay) {\n return true\n }\n if (!enterpriseEnabled) {\n return false\n }\n if (!file.moduleName) {\n return true\n }\n if (enabledModuleNames.has(file.moduleName)) {\n return true\n }\n return enabledModules.has(normalizeModuleId(file.moduleName))\n })\n .sort((left, right) => left.path.localeCompare(right.path))\n writeDiscoverySelectionReport(projectRoot, selected)\n return selected\n}\n"],
5
+ "mappings": "AAAA,SAAS,YAAY,cAAc,aAAa,qBAAqB;AACrE,OAAO,UAAU;AACjB,OAAO,QAAQ;AAWf,MAAM,oCAAoC;AAC1C,MAAM,yBAAyB,oBAAI,IAAI;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,MAAM,8BAA8B,CAAC,WAAW,UAAU;AAC1D,MAAM,mCAAmC,CAAC,oBAAoB,mBAAmB,iBAAiB;AAClG,MAAM,uCAAuC,CAAC,GAAG,kCAAkC,iBAAiB;AACpG,M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