@open-mercato/cli 0.10.1-develop.7756.1.8f5dec1b96 → 0.10.1-develop.7759.1.416727583e

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 (120) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/agentic/guides/module-facts.json +162 -162
  3. package/dist/agentic/guides/module-facts.v2.json +162 -162
  4. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  5. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  6. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  7. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  8. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  9. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  10. package/dist/agentic/guides/modules/auth/index.md +1 -1
  11. package/dist/agentic/guides/modules/availability/index.md +1 -1
  12. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  13. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  14. package/dist/agentic/guides/modules/cart/index.md +1 -1
  15. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  16. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  17. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  21. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  22. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  23. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  24. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  25. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  26. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  27. package/dist/agentic/guides/modules/configs/index.md +1 -1
  28. package/dist/agentic/guides/modules/content/index.md +1 -1
  29. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  30. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  31. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  32. package/dist/agentic/guides/modules/customers/index.md +1 -1
  33. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  34. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  35. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  36. package/dist/agentic/guides/modules/devices/index.md +1 -1
  37. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  38. package/dist/agentic/guides/modules/directory/index.md +1 -1
  39. package/dist/agentic/guides/modules/documents/index.md +1 -1
  40. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  41. package/dist/agentic/guides/modules/entities/index.md +1 -1
  42. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  43. package/dist/agentic/guides/modules/events/index.md +1 -1
  44. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  45. package/dist/agentic/guides/modules/forms/index.md +1 -1
  46. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  47. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  48. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  49. package/dist/agentic/guides/modules/generators/index.md +1 -1
  50. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  51. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  52. package/dist/agentic/guides/modules/messages/index.md +1 -1
  53. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  54. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  55. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  56. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  57. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  58. package/dist/agentic/guides/modules/planner/index.md +1 -1
  59. package/dist/agentic/guides/modules/portal/index.md +1 -1
  60. package/dist/agentic/guides/modules/progress/index.md +1 -1
  61. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  62. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  63. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  64. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  65. package/dist/agentic/guides/modules/resources/index.md +1 -1
  66. package/dist/agentic/guides/modules/sales/index.md +1 -1
  67. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  68. package/dist/agentic/guides/modules/search/index.md +1 -1
  69. package/dist/agentic/guides/modules/security/index.md +1 -1
  70. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  71. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  72. package/dist/agentic/guides/modules/sso/index.md +1 -1
  73. package/dist/agentic/guides/modules/staff/index.md +1 -1
  74. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  75. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  76. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  77. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  78. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  79. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  80. package/dist/agentic/guides/modules/translations/index.md +1 -1
  81. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  82. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  83. package/dist/agentic/guides/modules/wms/index.md +1 -1
  84. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  85. package/dist/agentic/guides/reference-module-facts.json +1 -1
  86. package/dist/agentic/guides/upstream/manifest.json +1 -1
  87. package/dist/lib/__integration__/TC-INT-007.spec.js +17 -0
  88. package/dist/lib/__integration__/TC-INT-007.spec.js.map +2 -2
  89. package/dist/lib/module-install.js +46 -8
  90. package/dist/lib/module-install.js.map +2 -2
  91. package/dist/lib/module-search-args.js +97 -0
  92. package/dist/lib/module-search-args.js.map +7 -0
  93. package/dist/lib/module-search-index.js +677 -0
  94. package/dist/lib/module-search-index.js.map +7 -0
  95. package/dist/lib/module-search.js +668 -0
  96. package/dist/lib/module-search.js.map +7 -0
  97. package/dist/lib/modules-config.js +105 -27
  98. package/dist/lib/modules-config.js.map +2 -2
  99. package/dist/lib/resolver.js +21 -1
  100. package/dist/lib/resolver.js.map +2 -2
  101. package/dist/mercato.js +32 -15
  102. package/dist/mercato.js.map +2 -2
  103. package/package.json +8 -7
  104. package/src/__tests__/mercato.test.ts +57 -0
  105. package/src/lib/__fixtures__/module-search/README.md +97 -0
  106. package/src/lib/__fixtures__/module-search/built-in.json +235 -0
  107. package/src/lib/__fixtures__/module-search/catalog-parity.json +4076 -0
  108. package/src/lib/__fixtures__/module-search/modules-index.json +1980 -0
  109. package/src/lib/__integration__/TC-INT-007.spec.ts +22 -0
  110. package/src/lib/__tests__/module-install.test.ts +220 -14
  111. package/src/lib/__tests__/module-search.test.ts +929 -0
  112. package/src/lib/__tests__/modules-config.test.ts +273 -1
  113. package/src/lib/__tests__/resolver.enterprise.test.ts +60 -0
  114. package/src/lib/module-install.ts +54 -10
  115. package/src/lib/module-search-args.ts +116 -0
  116. package/src/lib/module-search-index.ts +1033 -0
  117. package/src/lib/module-search.ts +952 -0
  118. package/src/lib/modules-config.ts +153 -36
  119. package/src/lib/resolver.ts +23 -1
  120. package/src/mercato.ts +36 -11
@@ -1,7 +1,12 @@
1
1
  import fs from 'node:fs'
2
2
  import os from 'node:os'
3
3
  import path from 'node:path'
4
- import { ensureModuleRegistration, setModuleRegistrationSource } from '../modules-config'
4
+ import {
5
+ assertModuleNotGatedOff,
6
+ ensureModuleRegistration,
7
+ ModuleGatedOffError,
8
+ setModuleRegistrationSource,
9
+ } from '../modules-config'
5
10
 
6
11
  describe('modules-config', () => {
7
12
  let tmpDir: string
@@ -133,6 +138,273 @@ describe('modules-config', () => {
133
138
  expect(updated).toContain("enabledModules.push({ id: 'example_customers_sync', from: '@app' })")
134
139
  })
135
140
 
141
+ describe('env-gated registrations', () => {
142
+ const flagNames = [
143
+ 'OM_ENABLE_STORAGE_S3',
144
+ 'OM_ENABLE_ENTERPRISE_MODULES',
145
+ 'OM_ENABLE_ENTERPRISE_MODULES_SSO',
146
+ 'OM_ENABLE_ENTERPRISE_MODULES_SECURITY',
147
+ 'OM_ENABLE_ENTERPRISE_MODULES_AGENTS',
148
+ ]
149
+ const originalEnv = Object.fromEntries(flagNames.map((name) => [name, process.env[name]]))
150
+
151
+ afterEach(() => {
152
+ for (const name of flagNames) {
153
+ if (originalEnv[name] === undefined) delete process.env[name]
154
+ else process.env[name] = originalEnv[name]
155
+ }
156
+ })
157
+
158
+ function writeGatedModulesFile(): string {
159
+ const filePath = path.join(tmpDir, 'modules.ts')
160
+ fs.writeFileSync(
161
+ filePath,
162
+ [
163
+ "import { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'",
164
+ '',
165
+ 'export const enabledModules = [',
166
+ " { id: 'auth', from: '@open-mercato/core' },",
167
+ ']',
168
+ '',
169
+ 'if (parseBooleanWithDefault(process.env.OM_ENABLE_STORAGE_S3, false)) {',
170
+ " enabledModules.push({ id: 'storage_s3', from: '@open-mercato/storage-s3' })",
171
+ '}',
172
+ '',
173
+ 'const enterpriseModulesEnabled = parseBooleanWithDefault(process.env.OM_ENABLE_ENTERPRISE_MODULES, false)',
174
+ 'const enterpriseSsoEnabled = parseBooleanWithDefault(process.env.OM_ENABLE_ENTERPRISE_MODULES_SSO, false)',
175
+ '',
176
+ 'if (enterpriseModulesEnabled && enterpriseSsoEnabled) {',
177
+ " enabledModules.push({ id: 'sso', from: '@open-mercato/enterprise' })",
178
+ '}',
179
+ ].join('\n'),
180
+ )
181
+ return filePath
182
+ }
183
+
184
+ it('refuses to add a second entry for a module gated by a disabled env flag and names the flag', () => {
185
+ delete process.env.OM_ENABLE_STORAGE_S3
186
+ const filePath = writeGatedModulesFile()
187
+ const before = fs.readFileSync(filePath, 'utf8')
188
+
189
+ expect(() =>
190
+ ensureModuleRegistration(filePath, { id: 'storage_s3', from: '@open-mercato/storage-s3' }),
191
+ ).toThrow(/storage_s3.*OM_ENABLE_STORAGE_S3=true/s)
192
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(before)
193
+ })
194
+
195
+ it('treats a gated module whose env flag is on as already registered', () => {
196
+ process.env.OM_ENABLE_STORAGE_S3 = 'true'
197
+ const filePath = writeGatedModulesFile()
198
+ const before = fs.readFileSync(filePath, 'utf8')
199
+
200
+ const result = ensureModuleRegistration(filePath, {
201
+ id: 'storage_s3',
202
+ from: '@open-mercato/storage-s3',
203
+ })
204
+
205
+ expect(result).toEqual({ changed: false, registeredAs: '@open-mercato/storage-s3' })
206
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(before)
207
+ })
208
+
209
+ it('names only the env flags still off when a gate reads them through variables', () => {
210
+ process.env.OM_ENABLE_ENTERPRISE_MODULES = 'true'
211
+ delete process.env.OM_ENABLE_ENTERPRISE_MODULES_SSO
212
+ const filePath = writeGatedModulesFile()
213
+
214
+ let message = ''
215
+ try {
216
+ ensureModuleRegistration(filePath, { id: 'sso', from: '@open-mercato/enterprise' })
217
+ } catch (error) {
218
+ message = error instanceof Error ? error.message : String(error)
219
+ }
220
+
221
+ expect(message).toContain('OM_ENABLE_ENTERPRISE_MODULES_SSO=true')
222
+ expect(message).not.toContain('OM_ENABLE_ENTERPRISE_MODULES=true')
223
+ })
224
+
225
+ it('covers every env-gated module of the create-app template', () => {
226
+ for (const name of flagNames) {
227
+ delete process.env[name]
228
+ }
229
+ const templatePath = path.resolve(__dirname, '../../../../create-app/template/src/modules.ts')
230
+ const filePath = path.join(tmpDir, 'modules.ts')
231
+ fs.copyFileSync(templatePath, filePath)
232
+ const before = fs.readFileSync(filePath, 'utf8')
233
+
234
+ const gatedModules: Array<{ id: string; from: string; flag: RegExp }> = [
235
+ { id: 'storage_s3', from: '@open-mercato/storage-s3', flag: /OM_ENABLE_STORAGE_S3=true/ },
236
+ { id: 'record_locks', from: '@open-mercato/enterprise', flag: /OM_ENABLE_ENTERPRISE_MODULES=true/ },
237
+ { id: 'system_status_overlays', from: '@open-mercato/enterprise', flag: /OM_ENABLE_ENTERPRISE_MODULES=true/ },
238
+ { id: 'sso', from: '@open-mercato/enterprise', flag: /OM_ENABLE_ENTERPRISE_MODULES_SSO=true/ },
239
+ { id: 'security', from: '@open-mercato/enterprise', flag: /OM_ENABLE_ENTERPRISE_MODULES_SECURITY=true/ },
240
+ { id: 'agent_orchestrator', from: '@open-mercato/enterprise', flag: /OM_ENABLE_ENTERPRISE_MODULES_AGENTS=true/ },
241
+ ]
242
+
243
+ for (const gated of gatedModules) {
244
+ expect(() => ensureModuleRegistration(filePath, { id: gated.id, from: gated.from })).toThrow(gated.flag)
245
+ }
246
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(before)
247
+ })
248
+
249
+ it('never suggests a flag value it cannot vouch for', () => {
250
+ process.env.OM_ENABLE_STORAGE_S3 = 'true'
251
+ const filePath = path.join(tmpDir, 'modules.ts')
252
+ fs.writeFileSync(
253
+ filePath,
254
+ [
255
+ "import { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'",
256
+ '',
257
+ 'const enableS3 = parseBooleanWithDefault(process.env.OM_ENABLE_ENTERPRISE_MODULES, false)',
258
+ 'const settings = { enableS3: false }',
259
+ '',
260
+ 'export const enabledModules = []',
261
+ '',
262
+ 'if (!parseBooleanWithDefault(process.env.OM_ENABLE_STORAGE_S3, false)) {',
263
+ " enabledModules.push({ id: 'negated', from: '@open-mercato/negated' })",
264
+ '}',
265
+ '',
266
+ 'if (parseBooleanWithDefault(process.env.OM_ENABLE_STORAGE_S3, false)) {',
267
+ " enabledModules.push({ id: 'unrelated', from: '@open-mercato/unrelated' })",
268
+ '} else {',
269
+ " enabledModules.push({ id: 'fallback', from: '@open-mercato/fallback' })",
270
+ '}',
271
+ '',
272
+ 'if (settings.enableS3) {',
273
+ " enabledModules.push({ id: 'property_gated', from: '@open-mercato/property-gated' })",
274
+ '}',
275
+ ].join('\n'),
276
+ )
277
+
278
+ for (const id of ['negated', 'fallback', 'property_gated']) {
279
+ let message = ''
280
+ try {
281
+ ensureModuleRegistration(filePath, { id, from: `@open-mercato/${id.replace('_', '-')}` })
282
+ } catch (error) {
283
+ message = error instanceof Error ? error.message : String(error)
284
+ }
285
+ expect(message).toContain('Make that condition true to enable it.')
286
+ expect(message).not.toMatch(/=true/)
287
+ }
288
+ })
289
+
290
+ function readGatedOffError(filePath: string, id: string): ModuleGatedOffError {
291
+ try {
292
+ ensureModuleRegistration(filePath, { id, from: '@open-mercato/gated' })
293
+ } catch (error) {
294
+ if (error instanceof ModuleGatedOffError) return error
295
+ throw error
296
+ }
297
+ throw new Error(`[internal] expected module "${id}" to be gated off`)
298
+ }
299
+
300
+ function writeConditionFile(statements: string[]): string {
301
+ const filePath = path.join(tmpDir, 'modules.ts')
302
+ fs.writeFileSync(
303
+ filePath,
304
+ [
305
+ "import { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'",
306
+ '',
307
+ 'const enterpriseEnabled = parseBooleanWithDefault(process.env.OM_ENABLE_ENTERPRISE_MODULES, false)',
308
+ 'const s3Disabled = !parseBooleanWithDefault(process.env.OM_ENABLE_STORAGE_S3, false)',
309
+ '',
310
+ 'export const enabledModules = []',
311
+ '',
312
+ ...statements,
313
+ ].join('\n'),
314
+ )
315
+ return filePath
316
+ }
317
+
318
+ it.each([
319
+ [
320
+ 'a negated operand inside &&',
321
+ ['if (enterpriseEnabled && !parseBooleanWithDefault(process.env.OM_ENABLE_STORAGE_S3, false)) {'],
322
+ ],
323
+ ['a comparison inside &&', ["if (enterpriseEnabled && process.env.OM_ENABLE_STORAGE_S3 !== 'true') {"]],
324
+ ['a negated variable inside &&', ['if (enterpriseEnabled && s3Disabled) {']],
325
+ ['a variable the parser does not know', ['if (enterpriseEnabled && unknownFlag) {']],
326
+ ['an || condition', ['if (enterpriseEnabled || parseBooleanWithDefault(process.env.OM_ENABLE_ENTERPRISE_MODULES_SSO, false)) {']],
327
+ ])('asks to make the condition true for %s', (_label, condition) => {
328
+ process.env.OM_ENABLE_STORAGE_S3 = 'true'
329
+ delete process.env.OM_ENABLE_ENTERPRISE_MODULES
330
+ delete process.env.OM_ENABLE_ENTERPRISE_MODULES_SSO
331
+ const filePath = writeConditionFile([
332
+ ...condition,
333
+ " enabledModules.push({ id: 'gated', from: '@open-mercato/gated' })",
334
+ '}',
335
+ ])
336
+
337
+ const error = readGatedOffError(filePath, 'gated')
338
+ expect(error.message).toContain('Make that condition true to enable it.')
339
+ expect(error.message).not.toMatch(/=true/)
340
+ expect(error.envFlags).toEqual([])
341
+ })
342
+
343
+ it('keeps an inner condition unvouched when the outer condition is not understood', () => {
344
+ process.env.OM_ENABLE_STORAGE_S3 = 'true'
345
+ delete process.env.OM_ENABLE_ENTERPRISE_MODULES
346
+ const filePath = writeConditionFile([
347
+ 'if (s3Disabled) {',
348
+ ' if (enterpriseEnabled) {',
349
+ " enabledModules.push({ id: 'gated', from: '@open-mercato/gated' })",
350
+ ' }',
351
+ '}',
352
+ ])
353
+
354
+ const error = readGatedOffError(filePath, 'gated')
355
+ expect(error.message).toContain('Make that condition true to enable it.')
356
+ expect(error.envFlags).toEqual([])
357
+ })
358
+
359
+ it('names the flags of nested positive conditions', () => {
360
+ delete process.env.OM_ENABLE_ENTERPRISE_MODULES
361
+ delete process.env.OM_ENABLE_ENTERPRISE_MODULES_SSO
362
+ const filePath = writeConditionFile([
363
+ 'if (enterpriseEnabled) {',
364
+ ' if (parseBooleanWithDefault(process.env.OM_ENABLE_ENTERPRISE_MODULES_SSO, false)) {',
365
+ " enabledModules.push({ id: 'gated', from: '@open-mercato/gated' })",
366
+ ' }',
367
+ '}',
368
+ ])
369
+
370
+ const error = readGatedOffError(filePath, 'gated')
371
+ expect(error.envFlags).toEqual(['OM_ENABLE_ENTERPRISE_MODULES', 'OM_ENABLE_ENTERPRISE_MODULES_SSO'])
372
+ expect(error.message).toContain('OM_ENABLE_ENTERPRISE_MODULES=true and OM_ENABLE_ENTERPRISE_MODULES_SSO=true')
373
+ })
374
+
375
+ it('throws a ModuleGatedOffError carrying the flags for a gated template module', () => {
376
+ delete process.env.OM_ENABLE_STORAGE_S3
377
+ const templatePath = path.resolve(__dirname, '../../../../create-app/template/src/modules.ts')
378
+ const filePath = path.join(tmpDir, 'modules.ts')
379
+ fs.copyFileSync(templatePath, filePath)
380
+
381
+ let thrown: unknown
382
+ try {
383
+ assertModuleNotGatedOff(filePath, 'storage_s3')
384
+ } catch (error) {
385
+ thrown = error
386
+ }
387
+
388
+ expect(thrown).toBeInstanceOf(ModuleGatedOffError)
389
+ const gatedOff = thrown as ModuleGatedOffError
390
+ expect(gatedOff.code).toBe('MODULE_GATED_OFF')
391
+ expect(gatedOff.moduleId).toBe('storage_s3')
392
+ expect(gatedOff.envFlags).toEqual(['OM_ENABLE_STORAGE_S3'])
393
+ expect(gatedOff.message).toContain('OM_ENABLE_STORAGE_S3=true')
394
+ expect(() => assertModuleNotGatedOff(filePath, 'auth')).not.toThrow()
395
+ })
396
+
397
+ it('ignores inactive gated entries when switching the source of an active registration', () => {
398
+ delete process.env.OM_ENABLE_STORAGE_S3
399
+ const filePath = writeGatedModulesFile()
400
+
401
+ expect(() => setModuleRegistrationSource(filePath, 'storage_s3', '@app')).toThrow(
402
+ /Could not find module entry for "storage_s3"/,
403
+ )
404
+ expect(setModuleRegistrationSource(filePath, 'auth', '@app')).toEqual({ changed: true })
405
+ })
406
+ })
407
+
136
408
  describe('preserves the rest of the file when appending a module', () => {
137
409
  const appendEntry = (source: string): string => {
138
410
  const filePath = path.join(tmpDir, 'modules.ts')
@@ -144,6 +144,66 @@ describe('resolver enterprise module toggle', () => {
144
144
  expect(modules).toEqual([{ id: 'customers', from: '@open-mercato/core' }])
145
145
  })
146
146
 
147
+ it('keeps one registration per module id and warns about duplicates', () => {
148
+ process.env.OM_ENABLE_ENTERPRISE_MODULES = 'true'
149
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'resolver-duplicate-'))
150
+ fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true })
151
+ fs.writeFileSync(
152
+ path.join(tempDir, 'src', 'modules.ts'),
153
+ `
154
+ import { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'
155
+
156
+ export const enabledModules = [
157
+ { id: 'customers', from: '@open-mercato/core' },
158
+ { id: 'record_locks', from: '@open-mercato/enterprise' },
159
+ ]
160
+
161
+ if (parseBooleanWithDefault(process.env.OM_ENABLE_ENTERPRISE_MODULES, false)) {
162
+ enabledModules.push({ id: 'record_locks', from: '@open-mercato/enterprise' })
163
+ }
164
+ `,
165
+ 'utf8',
166
+ )
167
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
168
+
169
+ try {
170
+ const modules = createResolver(tempDir).loadEnabledModules()
171
+ expect(modules.filter((entry) => entry.id === 'record_locks')).toHaveLength(1)
172
+ expect(modules.map((entry) => entry.id)).toEqual(['customers', 'record_locks'])
173
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('Module "record_locks" is registered more than once'))
174
+ } finally {
175
+ warn.mockRestore()
176
+ }
177
+ })
178
+
179
+ it('carries the full dev bootstrap mark from a dropped duplicate onto the kept registration', () => {
180
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'resolver-duplicate-bootstrap-'))
181
+ fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true })
182
+ fs.writeFileSync(
183
+ path.join(tempDir, 'src', 'modules.ts'),
184
+ `
185
+ export const enabledModules = [
186
+ { id: 'events', from: '@open-mercato/events' },
187
+ { id: 'events', from: '@open-mercato/events', overrides: { cli: { start: null } } },
188
+ { id: 'queue', from: '@open-mercato/core', overrides: { workers: { 'queue:process': null } } },
189
+ { id: 'queue', from: '@open-mercato/core' },
190
+ ]
191
+ `,
192
+ 'utf8',
193
+ )
194
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
195
+
196
+ try {
197
+ expect(createResolver(tempDir).loadEnabledModules()).toEqual([
198
+ { id: 'events', from: '@open-mercato/events', devSupervisorRequiresFullBootstrap: true },
199
+ { id: 'queue', from: '@open-mercato/core', devSupervisorRequiresFullBootstrap: true },
200
+ ])
201
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('Module "events" is registered more than once'))
202
+ } finally {
203
+ warn.mockRestore()
204
+ }
205
+ })
206
+
147
207
  it('parses modules.ts statically without executing runtime side effects', () => {
148
208
  delete (globalThis as Record<string, unknown>).__resolver_evaluated__
149
209
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'resolver-enterprise-'))
@@ -8,11 +8,11 @@ import {
8
8
  validateEjectBoundaries,
9
9
  type ValidatedOfficialModulePackage,
10
10
  } from './module-package'
11
- import { ensureModuleRegistration } from './modules-config'
11
+ import { assertModuleNotGatedOff, ensureModuleRegistration } from './modules-config'
12
12
  import type { PackageResolver } from './resolver'
13
13
  import { resolveSpawnCommand } from './spawn'
14
14
 
15
- type ModuleCommandResult = {
15
+ export type ModuleCommandResult = {
16
16
  moduleId: string
17
17
  packageName: string
18
18
  from: string
@@ -87,6 +87,42 @@ function runCommand(
87
87
  })
88
88
  }
89
89
 
90
+ function readFileIfExists(filePath: string): string | null {
91
+ return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : null
92
+ }
93
+
94
+ function isDeclaredAppDependency(appDir: string, packageName: string): boolean {
95
+ const packageJsonContent = readFileIfExists(path.join(appDir, 'package.json'))
96
+ if (!packageJsonContent) {
97
+ return false
98
+ }
99
+
100
+ let packageJson: Record<string, unknown>
101
+ try {
102
+ packageJson = JSON.parse(packageJsonContent) as Record<string, unknown>
103
+ } catch (error) {
104
+ const message = error instanceof Error ? error.message : String(error)
105
+ throw new Error(`App package.json at ${path.join(appDir, 'package.json')} is not valid JSON. ${message}`)
106
+ }
107
+
108
+ return ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].some((field) => {
109
+ const dependencies = packageJson[field]
110
+ return typeof dependencies === 'object' && dependencies !== null && packageName in dependencies
111
+ })
112
+ }
113
+
114
+ function isGatedOffError(error: unknown): boolean {
115
+ return error instanceof Error && (error as { code?: unknown }).code === 'MODULE_GATED_OFF'
116
+ }
117
+
118
+ function withLeftoverPackageHint(error: unknown, resolver: PackageResolver, packageName: string): Error {
119
+ const message = error instanceof Error ? error.message : String(error)
120
+ const removeArgs = [...resolveInstallTarget(resolver).args.slice(0, -1), 'remove', packageName]
121
+ return new Error(
122
+ `${message} The package "${packageName}" stayed in package.json. To remove it, run: yarn ${removeArgs.join(' ')}`,
123
+ )
124
+ }
125
+
90
126
  async function installPackageSpec(
91
127
  resolver: PackageResolver,
92
128
  packageSpec: string,
@@ -221,6 +257,7 @@ async function registerResolvedOfficialModule(
221
257
  packageName: string,
222
258
  eject: boolean,
223
259
  ): Promise<ModuleCommandResult> {
260
+ assertModuleNotGatedOff(resolver.getModulesConfigPath(), modulePackage.metadata.moduleId)
224
261
  const from = prepareRegistrationSource(modulePackage, resolver, packageName, eject)
225
262
 
226
263
  const registration = ensureModuleRegistration(
@@ -231,14 +268,10 @@ async function registerResolvedOfficialModule(
231
268
  },
232
269
  )
233
270
 
234
- if (!registration.changed) {
235
- throw new Error(
236
- `Module "${modulePackage.metadata.moduleId}" from "${from}" is already enabled in modules.ts.`,
237
- )
271
+ if (registration.changed) {
272
+ await runGeneratorsWithRegistrationNotice(resolver, modulePackage.metadata.moduleId)
238
273
  }
239
274
 
240
- await runGeneratorsWithRegistrationNotice(resolver, modulePackage.metadata.moduleId)
241
-
242
275
  return {
243
276
  moduleId: modulePackage.metadata.moduleId,
244
277
  packageName,
@@ -258,10 +291,21 @@ export async function addOfficialModule(
258
291
  const packageName = parsePackageNameFromSpec(safePackageSpec)
259
292
  assertPackageName(packageName)
260
293
 
294
+ const wasDeclaredBefore = isDeclaredAppDependency(resolver.getAppDir(), packageName)
295
+ const modulesConfigBefore = readFileIfExists(resolver.getModulesConfigPath())
296
+
261
297
  await installPackageSpec(resolver, safePackageSpec)
262
298
 
263
- const modulePackage = resolveInstalledOfficialModulePackage(resolver, packageName, moduleId)
264
- return registerResolvedOfficialModule(resolver, modulePackage, packageName, eject)
299
+ try {
300
+ const modulePackage = resolveInstalledOfficialModulePackage(resolver, packageName, moduleId)
301
+ return await registerResolvedOfficialModule(resolver, modulePackage, packageName, eject)
302
+ } catch (error) {
303
+ const moduleWasRegistered = readFileIfExists(resolver.getModulesConfigPath()) !== modulesConfigBefore
304
+ if (wasDeclaredBefore || moduleWasRegistered || isGatedOffError(error)) {
305
+ throw error
306
+ }
307
+ throw withLeftoverPackageHint(error, resolver, packageName)
308
+ }
265
309
  }
266
310
 
267
311
  export async function enableOfficialModule(
@@ -0,0 +1,116 @@
1
+ export const MODULE_SEARCH_KINDS = ['module', 'provider', 'library', 'tool', 'built-in'] as const
2
+ export type ModuleSearchKind = (typeof MODULE_SEARCH_KINDS)[number]
3
+
4
+ export type ParsedModuleSearchArgs = {
5
+ query: string | null
6
+ category: string | null
7
+ kinds: ModuleSearchKind[] | null
8
+ allLines: boolean
9
+ limit: number
10
+ json: boolean
11
+ }
12
+
13
+ export type ParsedModuleInfoArgs = {
14
+ ref: string | null
15
+ json: boolean
16
+ }
17
+
18
+ export const MODULE_SEARCH_DEFAULT_LIMIT = 10
19
+ export const MODULE_SEARCH_MAX_LIMIT = 20
20
+ const QUERY_MAX_LENGTH = 200
21
+ const CATEGORY_PATTERN = /^[a-z0-9][a-z0-9-]{0,40}$/
22
+
23
+ function readValue(args: string[], index: number, flag: string): string {
24
+ const next = args[index + 1]
25
+ if (next === undefined || next.startsWith('--')) {
26
+ throw new Error(`${flag} requires a value`)
27
+ }
28
+ return next
29
+ }
30
+
31
+ function splitFlag(arg: string): { flag: string; inline: string | null } {
32
+ const eq = arg.indexOf('=')
33
+ return eq === -1 ? { flag: arg, inline: null } : { flag: arg.slice(0, eq), inline: arg.slice(eq + 1) }
34
+ }
35
+
36
+ function parseKinds(value: string): ModuleSearchKind[] {
37
+ const kinds = value
38
+ .split(',')
39
+ .map((item) => item.trim())
40
+ .filter((item) => item !== '')
41
+ if (kinds.length === 0) throw new Error('--kind requires a value')
42
+ return kinds.map((kind) => {
43
+ const match = MODULE_SEARCH_KINDS.find((candidate) => candidate === kind)
44
+ if (!match) throw new Error(`--kind must be one of: ${MODULE_SEARCH_KINDS.join(', ')}`)
45
+ return match
46
+ })
47
+ }
48
+
49
+ function parseLimit(value: string): number {
50
+ if (!/^\d+$/.test(value)) throw new Error(`--limit must be a whole number between 1 and ${MODULE_SEARCH_MAX_LIMIT}`)
51
+ const limit = Number(value)
52
+ if (limit < 1 || limit > MODULE_SEARCH_MAX_LIMIT) {
53
+ throw new Error(`--limit must be a whole number between 1 and ${MODULE_SEARCH_MAX_LIMIT}`)
54
+ }
55
+ return limit
56
+ }
57
+
58
+ export function parseModuleSearchArgs(args: string[]): ParsedModuleSearchArgs {
59
+ const words: string[] = []
60
+ let category: string | null = null
61
+ let kinds: ModuleSearchKind[] | null = null
62
+ let allLines = false
63
+ let limit = MODULE_SEARCH_DEFAULT_LIMIT
64
+ let json = false
65
+
66
+ for (let index = 0; index < args.length; index += 1) {
67
+ const arg = args[index]
68
+ if (!arg) continue
69
+ if (!arg.startsWith('--')) {
70
+ words.push(arg)
71
+ continue
72
+ }
73
+ const { flag, inline } = splitFlag(arg)
74
+ if (flag === '--json' || flag === '--all-lines') {
75
+ if (inline !== null) throw new Error(`${flag} does not accept a value`)
76
+ if (flag === '--json') json = true
77
+ else allLines = true
78
+ continue
79
+ }
80
+ if (flag === '--category' || flag === '--kind' || flag === '--limit') {
81
+ const value = inline ?? readValue(args, index, flag)
82
+ if (inline === null) index += 1
83
+ if (flag === '--category') {
84
+ if (!CATEGORY_PATTERN.test(value)) throw new Error('--category expects a catalog category id, for example payments-finance')
85
+ category = value
86
+ } else if (flag === '--kind') {
87
+ kinds = parseKinds(value)
88
+ } else {
89
+ limit = parseLimit(value)
90
+ }
91
+ continue
92
+ }
93
+ throw new Error(`Unsupported option: ${flag}`)
94
+ }
95
+
96
+ const query = words.join(' ').trim()
97
+ if (query.length > QUERY_MAX_LENGTH) throw new Error(`The query is longer than ${QUERY_MAX_LENGTH} characters`)
98
+ return { query: query === '' ? null : query, category, kinds, allLines, limit, json }
99
+ }
100
+
101
+ export function parseModuleInfoArgs(args: string[]): ParsedModuleInfoArgs {
102
+ let ref: string | null = null
103
+ let json = false
104
+ for (const arg of args) {
105
+ if (!arg) continue
106
+ if (arg === '--json') {
107
+ json = true
108
+ continue
109
+ }
110
+ if (arg.startsWith('--')) throw new Error(`Unsupported option: ${splitFlag(arg).flag}`)
111
+ if (ref !== null) throw new Error('module info takes one package name or module id')
112
+ ref = arg.trim()
113
+ }
114
+ if (ref !== null && ref.length > 220) throw new Error('The package name or module id is too long')
115
+ return { ref: ref === '' ? null : ref, json }
116
+ }