@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
@@ -0,0 +1,952 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import type { ModuleEntry } from './modules-config'
4
+ import { createResolver } from './resolver'
5
+ import {
6
+ builtInEnableCommand,
7
+ builtInPresetText,
8
+ builtInWarnings,
9
+ cardUrl,
10
+ CORE_PACKAGE,
11
+ createCatalogSearcher,
12
+ ENTERPRISE_ENABLE_STEP,
13
+ entryWarnings,
14
+ installFields,
15
+ installVersion,
16
+ latestLine,
17
+ newAppInstallText,
18
+ peerLookup,
19
+ rankModules,
20
+ receiptSourceOf,
21
+ resolveLine,
22
+ resolveRef,
23
+ SEARCH_MAX_LIMIT,
24
+ sharedModuleIdWarning,
25
+ statusOn,
26
+ stripVersion,
27
+ toModuleCard,
28
+ unknownModuleMessage,
29
+ type AgentPolicy,
30
+ type BuiltInCard,
31
+ type BuiltInIndex,
32
+ type BuiltInModule,
33
+ type CatalogEntry,
34
+ type CatalogIndex,
35
+ type CatalogSearcher,
36
+ type ModuleCard,
37
+ type ReceiptSource,
38
+ } from './module-search-index'
39
+ import { parseModuleInfoArgs, parseModuleSearchArgs } from './module-search-args'
40
+
41
+ export const DEFAULT_MODULES_INDEX_URL = 'https://modules.openmercato.com/modules.json'
42
+ export const MODULES_SITE_URL = 'https://modules.openmercato.com'
43
+ export const MODULE_INDEX_TIMEOUT_MS = 4000
44
+ export const MODULE_INDEX_TTL_MS = 10 * 60 * 1000
45
+ export const MODULE_INDEX_CACHE_FILE = path.join('.mercato', 'cache', 'modules-index.json')
46
+ export const MODULE_INDEX_UNAVAILABLE_EXIT_CODE = 2
47
+ export const MODULE_INDEX_UNAVAILABLE_MESSAGE =
48
+ 'Module index unavailable. Check your connection or set OM_MODULES_INDEX_URL.'
49
+
50
+ export type FetchResponseLike = {
51
+ status: number
52
+ ok: boolean
53
+ headers: { get(name: string): string | null }
54
+ json(): Promise<unknown>
55
+ }
56
+
57
+ export type FetchLike = (
58
+ input: string,
59
+ init?: { headers?: Record<string, string>; signal?: AbortSignal },
60
+ ) => Promise<FetchResponseLike>
61
+
62
+ export type LoadedModuleIndex = {
63
+ index: CatalogIndex
64
+ builtIn: BuiltInIndex | null
65
+ /** Why the built-in module list is missing (`builtIn` is null), or null when it loaded. */
66
+ builtInUnavailable: string | null
67
+ source: 'network' | 'cache' | 'stale-cache'
68
+ fetchedAt: string
69
+ searcher: CatalogSearcher
70
+ }
71
+
72
+ export type LoadIndexOptions = {
73
+ appRoot: string
74
+ url?: string
75
+ builtInUrl?: string
76
+ timeoutMs?: number
77
+ ttlMs?: number
78
+ fetchImpl?: FetchLike
79
+ now?: () => number
80
+ }
81
+
82
+ type CacheFile = {
83
+ cacheVersion: 1
84
+ url: string
85
+ builtInUrl: string
86
+ fetchedAt: string
87
+ etag: string | null
88
+ builtInEtag: string | null
89
+ index: CatalogIndex
90
+ builtIn: BuiltInIndex | null
91
+ }
92
+
93
+ export class ModuleIndexUnavailableError extends Error {
94
+ readonly detail: string
95
+
96
+ constructor(detail: string) {
97
+ super(`${MODULE_INDEX_UNAVAILABLE_MESSAGE} (${detail})`)
98
+ this.name = 'ModuleIndexUnavailableError'
99
+ this.detail = detail
100
+ }
101
+ }
102
+
103
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
104
+ typeof value === 'object' && value !== null && !Array.isArray(value)
105
+ const isString = (value: unknown): value is string => typeof value === 'string'
106
+ const isStringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every(isString)
107
+ const isNullableString = (value: unknown): value is string | null => value === null || isString(value)
108
+ const isArrayOf = (value: unknown, item: (value: unknown) => boolean): boolean => Array.isArray(value) && value.every(item)
109
+ const isRecordOf = (value: unknown, item: (value: unknown) => boolean): boolean =>
110
+ isRecord(value) && Object.values(value).every(item)
111
+ const isAbsentOr = (value: unknown, check: (value: unknown) => boolean): boolean => value === undefined || check(value)
112
+
113
+ const ANATOMY_LISTS = ['aclFeatures', 'eventsEmitted', 'eventsConsumed', 'env', 'hosts', 'tables', 'publicRoutes'] as const
114
+
115
+ // The anatomy lists search indexes and `module info` prints; a module without anatomy has null.
116
+ function isAnatomy(value: unknown): boolean {
117
+ if (value === null || value === undefined) return true
118
+ if (!isRecord(value)) return false
119
+ const lists = value.lists
120
+ if (lists === undefined) return true
121
+ return (
122
+ isRecord(lists) &&
123
+ ANATOMY_LISTS.every((key) => isAbsentOr(lists[key], isStringArray)) &&
124
+ isAbsentOr(lists.credentials, (credentials) =>
125
+ isArrayOf(credentials, (credential) => isRecord(credential) && isString(credential.key)),
126
+ )
127
+ )
128
+ }
129
+
130
+ function isAgentPolicy(value: unknown): boolean {
131
+ return (
132
+ isRecord(value) &&
133
+ isString(value.decision) &&
134
+ isArrayOf(value.reasons, (reason) => isRecord(reason) && isString(reason.code) && isString(reason.text))
135
+ )
136
+ }
137
+
138
+ function isBuiltFor(value: unknown): boolean {
139
+ return (
140
+ isRecord(value) &&
141
+ isString(value.kind) &&
142
+ isNullableString(value.range) &&
143
+ isStringArray(value.lines) &&
144
+ isAbsentOr(value.ranges, (ranges) => isRecordOf(ranges, isString))
145
+ )
146
+ }
147
+
148
+ function isCompat(value: unknown): boolean {
149
+ return (
150
+ isRecord(value) &&
151
+ isRecordOf(
152
+ value.lines,
153
+ (cell) =>
154
+ isRecord(cell) &&
155
+ isString(cell.status) &&
156
+ isAbsentOr(cell.at, isNullableString) &&
157
+ isAbsentOr(cell.moduleVersion, isNullableString),
158
+ ) &&
159
+ isStringArray(value.verifiedOn) &&
160
+ isAbsentOr(value.builtFor, isBuiltFor) &&
161
+ isAbsentOr(value.inPresets, isStringArray) &&
162
+ isAbsentOr(value.inEmptyPreset, isStringArray) &&
163
+ isAbsentOr(value.ships, (ships) => isRecordOf(ships, isString)) &&
164
+ isAbsentOr(value.isolation, (isolation) =>
165
+ isRecordOf(isolation, (cell) => isRecord(cell) && isString(cell.status) && isNullableString(cell.moduleVersion)),
166
+ )
167
+ )
168
+ }
169
+
170
+ function isSignals(value: unknown): boolean {
171
+ if (value === null || value === undefined) return true
172
+ return (
173
+ isRecord(value) &&
174
+ isAbsentOr(value.supplyChain, (item) => isRecord(item) && isString(item.status) && isStringArray(item.reasons)) &&
175
+ isAbsentOr(value.hygiene, (item) => isRecord(item) && isString(item.status) && isStringArray(item.failing)) &&
176
+ isAbsentOr(value.anatomy, isString)
177
+ )
178
+ }
179
+
180
+ // Every field search, `module info` and their output read, nested ones too: an entry that passes is never the reason
181
+ // a command throws, so a malformed index is refused before it can replace a working cached copy.
182
+ function isCatalogEntry(value: unknown): value is CatalogEntry {
183
+ if (!isRecord(value)) return false
184
+ const version = value.version
185
+ const install = value.install
186
+ const links = value.links
187
+ const license = value.license
188
+ return (
189
+ isString(value.locator) &&
190
+ isString(value.path) &&
191
+ (value.npm === null || isString(value.npm)) &&
192
+ isString(value.title) &&
193
+ isString(value.summary) &&
194
+ isString(value.whenToUse) &&
195
+ isString(value.type) &&
196
+ isString(value.kind) &&
197
+ isString(value.category) &&
198
+ isStringArray(value.tags) &&
199
+ isArrayOf(value.providers, (provider) => isRecord(provider) && isString(provider.name) && isString(provider.label)) &&
200
+ isStringArray(value.moduleIds) &&
201
+ isAbsentOr(value.requires, (requires) =>
202
+ isArrayOf(
203
+ requires,
204
+ (requirement) => isRecord(requirement) && isString(requirement.raw) && isAbsentOr(requirement.resolvesTo, isNullableString),
205
+ ),
206
+ ) &&
207
+ isStringArray(value.renamedFrom) &&
208
+ isString(value.status) &&
209
+ typeof value.listed === 'boolean' &&
210
+ typeof value.featured === 'boolean' &&
211
+ isNullableString(value.tier) &&
212
+ isRecord(license) &&
213
+ isNullableString(license.spdx) &&
214
+ isString(license.kind) &&
215
+ isRecord(version) &&
216
+ isNullableString(version.latest) &&
217
+ isNullableString(version.preview) &&
218
+ isNullableString(version.installableFrom) &&
219
+ isNullableString(version.gitRef) &&
220
+ isRecordOf(version.recommended, isNullableString) &&
221
+ isCompat(value.compat) &&
222
+ isAnatomy(value.anatomy) &&
223
+ isSignals(value.signals) &&
224
+ isRecordOf(value.agentPolicy, isAgentPolicy) &&
225
+ isRecord(install) &&
226
+ isString(install.cli) &&
227
+ isAbsentOr(install.moduleFlag, isNullableString) &&
228
+ isRecord(links) &&
229
+ isString(links.page) &&
230
+ isString(links.md)
231
+ )
232
+ }
233
+
234
+ export function parseCatalogIndex(value: unknown): CatalogIndex | null {
235
+ if (!isRecord(value) || value.schemaVersion !== 1) return null
236
+ if (!isString(value.generatedAt) || !isString(value.dataVersion) || !isString(value.site)) return null
237
+ if (!Array.isArray(value.lines) || !Array.isArray(value.entries)) return null
238
+ if (!isAbsentOr(value.dataAsOf, isRecord)) return null
239
+ if (!value.lines.every((line) => isRecord(line) && isString(line.key) && isString(line.version) && isString(line.source))) {
240
+ return null
241
+ }
242
+ if (!value.entries.every(isCatalogEntry)) return null
243
+ const lines = value.lines.filter(
244
+ (line): line is CatalogIndex['lines'][number] =>
245
+ line.source === 'latest' || line.source === 'previous' || line.source === 'develop',
246
+ )
247
+ return { ...(value as CatalogIndex), lines }
248
+ }
249
+
250
+ export function parseBuiltInIndex(value: unknown): BuiltInIndex | null {
251
+ if (!isRecord(value) || value.schemaVersion !== 1 || !isString(value.coreVersion) || !Array.isArray(value.modules)) {
252
+ return null
253
+ }
254
+ const valid = value.modules.every(
255
+ (coreModule) =>
256
+ isRecord(coreModule) &&
257
+ isString(coreModule.id) &&
258
+ isString(coreModule.title) &&
259
+ isString(coreModule.description) &&
260
+ isString(coreModule.category) &&
261
+ isString(coreModule.install) &&
262
+ isString(coreModule.page) &&
263
+ isAbsentOr(coreModule.requires, isStringArray) &&
264
+ isAbsentOr(coreModule.inPresets, isStringArray) &&
265
+ isAbsentOr(coreModule.inEmptyPreset, isStringArray) &&
266
+ isAnatomy(coreModule.anatomy),
267
+ )
268
+ return valid ? (value as BuiltInIndex) : null
269
+ }
270
+
271
+ function parseCacheFile(value: unknown): CacheFile | null {
272
+ if (!isRecord(value) || value.cacheVersion !== 1) return null
273
+ if (!isString(value.url) || !isString(value.builtInUrl) || !isString(value.fetchedAt)) return null
274
+ const index = parseCatalogIndex(value.index)
275
+ if (!index) return null
276
+ const builtIn = value.builtIn === null ? null : parseBuiltInIndex(value.builtIn)
277
+ return {
278
+ cacheVersion: 1,
279
+ url: value.url,
280
+ builtInUrl: value.builtInUrl,
281
+ fetchedAt: value.fetchedAt,
282
+ etag: isString(value.etag) ? value.etag : null,
283
+ builtInEtag: isString(value.builtInEtag) ? value.builtInEtag : null,
284
+ index,
285
+ builtIn,
286
+ }
287
+ }
288
+
289
+ export function defaultBuiltInUrl(indexUrl: string): string {
290
+ const url = new URL(indexUrl)
291
+ url.search = ''
292
+ url.hash = ''
293
+ url.pathname = url.pathname.replace(/[^/]*$/, 'built-in.json')
294
+ return url.toString()
295
+ }
296
+
297
+ function readCache(file: string): CacheFile | null {
298
+ try {
299
+ return parseCacheFile(JSON.parse(fs.readFileSync(file, 'utf8')))
300
+ } catch {
301
+ return null
302
+ }
303
+ }
304
+
305
+ function writeCache(file: string, cache: CacheFile): void {
306
+ try {
307
+ fs.mkdirSync(path.dirname(file), { recursive: true })
308
+ const temporary = `${file}.${process.pid}.tmp`
309
+ fs.writeFileSync(temporary, JSON.stringify(cache))
310
+ fs.renameSync(temporary, file)
311
+ } catch {
312
+ return
313
+ }
314
+ }
315
+
316
+ async function fetchOnce(
317
+ fetchImpl: FetchLike,
318
+ url: string,
319
+ etag: string | null,
320
+ timeoutMs: number,
321
+ ): Promise<FetchResponseLike> {
322
+ const headers: Record<string, string> = { accept: 'application/json' }
323
+ if (etag) headers['if-none-match'] = etag
324
+ return fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs) })
325
+ }
326
+
327
+ async function fetchWithRetry(
328
+ fetchImpl: FetchLike,
329
+ url: string,
330
+ etag: string | null,
331
+ timeoutMs: number,
332
+ ): Promise<FetchResponseLike> {
333
+ let lastError: unknown = null
334
+ for (let attempt = 0; attempt < 2; attempt += 1) {
335
+ try {
336
+ const response = await fetchOnce(fetchImpl, url, etag, timeoutMs)
337
+ if (response.status >= 500) {
338
+ lastError = new Error(`${url} answered ${response.status}`)
339
+ continue
340
+ }
341
+ return response
342
+ } catch (error: unknown) {
343
+ lastError = error
344
+ }
345
+ }
346
+ throw lastError instanceof Error ? lastError : new Error(String(lastError))
347
+ }
348
+
349
+ async function fetchJson<T>(
350
+ fetchImpl: FetchLike,
351
+ url: string,
352
+ etag: string | null,
353
+ timeoutMs: number,
354
+ parse: (value: unknown) => T | null,
355
+ ): Promise<{ notModified: true } | { notModified: false; value: T; etag: string | null }> {
356
+ const response = await fetchWithRetry(fetchImpl, url, etag, timeoutMs)
357
+ if (response.status === 304) return { notModified: true }
358
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`)
359
+ const value = parse(await response.json())
360
+ if (value === null) throw new Error(`${url} is not a module index this CLI understands`)
361
+ return { notModified: false, value, etag: response.headers.get('etag') }
362
+ }
363
+
364
+ function searcherOf(index: CatalogIndex, builtIn: BuiltInIndex | null): CatalogSearcher | null {
365
+ try {
366
+ return createCatalogSearcher(index, builtIn)
367
+ } catch {
368
+ return null
369
+ }
370
+ }
371
+
372
+ export async function loadIndex(options: LoadIndexOptions): Promise<LoadedModuleIndex> {
373
+ const url = options.url ?? DEFAULT_MODULES_INDEX_URL
374
+ const builtInUrl = options.builtInUrl ?? defaultBuiltInUrl(url)
375
+ const timeoutMs = options.timeoutMs ?? MODULE_INDEX_TIMEOUT_MS
376
+ const ttlMs = options.ttlMs ?? MODULE_INDEX_TTL_MS
377
+ const fetchImpl: FetchLike = options.fetchImpl ?? ((input, init) => fetch(input, init))
378
+ const now = options.now ?? (() => Date.now())
379
+ const cacheFile = path.join(options.appRoot, MODULE_INDEX_CACHE_FILE)
380
+ const cached = readCache(cacheFile)
381
+ let usable = cached && cached.url === url && cached.builtInUrl === builtInUrl ? cached : null
382
+
383
+ // a copy without the built-in list is not fresh: the next run asks for built-in.json again
384
+ if (usable && usable.builtIn && now() - Date.parse(usable.fetchedAt) < ttlMs) {
385
+ const searcher = searcherOf(usable.index, usable.builtIn)
386
+ if (searcher) {
387
+ return { index: usable.index, builtIn: usable.builtIn, builtInUnavailable: null, source: 'cache', fetchedAt: usable.fetchedAt, searcher }
388
+ }
389
+ // a copy this CLI cannot search is no copy: download a new one
390
+ usable = null
391
+ }
392
+
393
+ try {
394
+ const indexResult = await fetchJson(fetchImpl, url, usable?.etag ?? null, timeoutMs, parseCatalogIndex)
395
+ let index: CatalogIndex
396
+ let etag: string | null
397
+ if (indexResult.notModified) {
398
+ if (!usable) throw new Error(`${url} answered 304 without a cached copy`)
399
+ index = usable.index
400
+ etag = usable.etag
401
+ } else {
402
+ index = indexResult.value
403
+ etag = indexResult.etag
404
+ }
405
+ let builtIn = usable?.builtIn ?? null
406
+ let builtInEtag = usable?.builtInEtag ?? null
407
+ let builtInUnavailable: string | null = null
408
+ try {
409
+ const builtInResult = await fetchJson(
410
+ fetchImpl,
411
+ builtInUrl,
412
+ usable?.builtIn ? builtInEtag : null,
413
+ timeoutMs,
414
+ parseBuiltInIndex,
415
+ )
416
+ if (!builtInResult.notModified) {
417
+ builtIn = builtInResult.value
418
+ builtInEtag = builtInResult.etag
419
+ }
420
+ } catch (error: unknown) {
421
+ builtIn = usable?.builtIn ?? null
422
+ if (!builtIn) builtInUnavailable = error instanceof Error ? error.message : String(error)
423
+ }
424
+ // built before the copy is saved, so an index the CLI cannot search never replaces one it can
425
+ const searcher = createCatalogSearcher(index, builtIn)
426
+ const fetchedAt = new Date(now()).toISOString()
427
+ writeCache(cacheFile, {
428
+ cacheVersion: 1,
429
+ url,
430
+ builtInUrl,
431
+ fetchedAt,
432
+ etag,
433
+ builtInEtag,
434
+ index,
435
+ builtIn,
436
+ })
437
+ return { index, builtIn, builtInUnavailable, source: 'network', fetchedAt, searcher }
438
+ } catch (error: unknown) {
439
+ const searcher = usable ? searcherOf(usable.index, usable.builtIn) : null
440
+ if (usable && searcher) {
441
+ return {
442
+ index: usable.index,
443
+ builtIn: usable.builtIn,
444
+ builtInUnavailable: usable.builtIn ? null : 'the cached copy has no built-in module list',
445
+ source: 'stale-cache',
446
+ fetchedAt: usable.fetchedAt,
447
+ searcher,
448
+ }
449
+ }
450
+ const detail = error instanceof Error ? error.message : String(error)
451
+ throw new ModuleIndexUnavailableError(detail)
452
+ }
453
+ }
454
+
455
+ export type AppContext = {
456
+ omVersion: string | null
457
+ enabledModules: ModuleEntry[] | null
458
+ }
459
+
460
+ function readJsonFile(file: string): unknown {
461
+ try {
462
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
463
+ } catch {
464
+ return null
465
+ }
466
+ }
467
+
468
+ export function detectAppLine(appRoot: string): string | null {
469
+ const installed = readJsonFile(path.join(appRoot, 'node_modules', '@open-mercato', 'core', 'package.json'))
470
+ if (isRecord(installed) && isString(installed.version)) return installed.version
471
+ const manifest = readJsonFile(path.join(appRoot, 'package.json'))
472
+ if (!isRecord(manifest)) return null
473
+ for (const field of ['dependencies', 'devDependencies'] as const) {
474
+ const deps = manifest[field]
475
+ if (isRecord(deps) && isString(deps[CORE_PACKAGE])) {
476
+ const range = deps[CORE_PACKAGE].trim()
477
+ const match = /\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?/.exec(range)
478
+ return match ? match[0] : null
479
+ }
480
+ }
481
+ return null
482
+ }
483
+
484
+ export type ReadEnabledModules = (modulesPath: string, env: NodeJS.ProcessEnv) => ModuleEntry[]
485
+
486
+ export function detectAppContext(
487
+ appRoot: string,
488
+ readEnabled: ReadEnabledModules | null,
489
+ env: NodeJS.ProcessEnv = process.env,
490
+ ): AppContext {
491
+ const modulesPath = path.join(appRoot, 'src', 'modules.ts')
492
+ let enabledModules: ModuleEntry[] | null = null
493
+ if (readEnabled && fs.existsSync(modulesPath)) {
494
+ try {
495
+ enabledModules = readEnabled(modulesPath, env)
496
+ } catch {
497
+ enabledModules = null
498
+ }
499
+ }
500
+ return { omVersion: detectAppLine(appRoot), enabledModules }
501
+ }
502
+
503
+ export type ModuleSearchJson = {
504
+ schemaVersion: 1
505
+ query: string
506
+ line: string | null
507
+ omVersion: string | null
508
+ results: ModuleCard[]
509
+ builtIn: BuiltInCard[]
510
+ /** Present (true) when the built-in module list could not be loaded, so `builtIn` may miss modules core has. */
511
+ builtInUnavailable?: true
512
+ total: number
513
+ hidden: number
514
+ dataVersion: string
515
+ generatedAt: string
516
+ receiptSource: ReceiptSource | null
517
+ /** Set when nothing matched the query and the results are for this spelling of it (`stirpe` -> `stripe`). */
518
+ didYouMean?: string
519
+ }
520
+
521
+ export type ModuleSearchView = {
522
+ json: ModuleSearchJson
523
+ entries: Map<string, CatalogEntry>
524
+ lineNote: string | null
525
+ allLines: boolean
526
+ }
527
+
528
+ export type ModuleSearchRequest = {
529
+ query: string | null
530
+ category?: string | null
531
+ kinds?: ('module' | 'provider' | 'library' | 'tool' | 'built-in')[] | null
532
+ allLines?: boolean
533
+ limit?: number
534
+ }
535
+
536
+ function builtInEnabled(id: string, enabled: ModuleEntry[] | null): boolean | null {
537
+ if (!enabled) return null
538
+ return enabled.some((coreModule) => coreModule.id === id && (coreModule.from ?? CORE_PACKAGE) === CORE_PACKAGE)
539
+ }
540
+
541
+ export function buildSearchView(
542
+ searcher: CatalogSearcher,
543
+ request: ModuleSearchRequest,
544
+ app: AppContext,
545
+ ): ModuleSearchView {
546
+ const resolved = app.omVersion ? resolveLine(app.omVersion, searcher.index.lines) : null
547
+ const rankInput = {
548
+ query: request.query ?? '',
549
+ ...(app.omVersion ? { omVersion: app.omVersion } : {}),
550
+ ...(request.category ? { category: request.category } : {}),
551
+ ...(request.kinds ? { kind: request.kinds } : {}),
552
+ }
553
+ const unfiltered = rankModules(searcher, rankInput)
554
+ const line = unfiltered.line
555
+ const allLines = request.allLines === true || line === null
556
+ const ranked = allLines ? unfiltered : rankModules(searcher, { ...rankInput, verifiedModulesOnly: true })
557
+ const kept = ranked.modules
558
+ const hidden = allLines ? 0 : unfiltered.modules.filter(
559
+ (hit) => hit.meta.entry.kind === 'module' && (line === null || !hit.meta.entry.version.recommended[line]),
560
+ ).length
561
+ const limit = Math.min(SEARCH_MAX_LIMIT, Math.max(1, Math.floor(request.limit ?? 10)))
562
+ const results = kept.slice(0, limit).map((hit) => toModuleCard(searcher, hit, line, ranked.latest))
563
+ const entries = new Map<string, CatalogEntry>()
564
+ for (const hit of kept.slice(0, limit)) entries.set(hit.meta.entry.locator, hit.meta.entry)
565
+ const builtIn = ranked.builtIn.map((card) => ({ ...card, enabled: builtInEnabled(card.id, app.enabledModules) }))
566
+ const lineNote =
567
+ resolved && resolved.line === null
568
+ ? `Open Mercato ${app.omVersion} is not a line the catalog tests (${resolved.note ?? 'unknown version'}). Showing modules for every line.`
569
+ : null
570
+ return {
571
+ json: {
572
+ schemaVersion: 1,
573
+ query: request.query ?? '',
574
+ line,
575
+ omVersion: app.omVersion,
576
+ results,
577
+ builtIn,
578
+ total: unfiltered.modules.length,
579
+ hidden,
580
+ dataVersion: searcher.index.dataVersion,
581
+ generatedAt: searcher.index.generatedAt,
582
+ receiptSource: receiptSourceOf(searcher),
583
+ ...(ranked.didYouMean ? { didYouMean: ranked.didYouMean } : {}),
584
+ },
585
+ entries,
586
+ lineNote,
587
+ allLines,
588
+ }
589
+ }
590
+
591
+ const ORIGIN_LABEL: Record<string, string> = { official: 'official', community: 'community', '3rd-party': '3rd-party' }
592
+
593
+ function levelLabel(entry: CatalogEntry, line: string | null): string {
594
+ const level = entry.quality ? 'OM QUALITY' : entry.tier === 'verified' ? 'VERIFIED' : 'LISTED'
595
+ if (line === null) return level
596
+ const status = statusOn(entry, line)
597
+ return status === 'verified' ? `${level} · ${line}` : `${level} · ${status} on ${line}`
598
+ }
599
+
600
+ function policyLabel(policy: AgentPolicy | null): string | null {
601
+ if (!policy) return null
602
+ const reasons = policy.reasons.slice(0, 2).map((reason) => reason.code.toLowerCase().replace(/_/g, '-'))
603
+ return reasons.length > 0 ? `${policy.decision} (${reasons.join(', ')})` : policy.decision
604
+ }
605
+
606
+ function licenseLabel(entry: CatalogEntry): string {
607
+ return entry.license.spdx ?? entry.license.kind
608
+ }
609
+
610
+ const steps = (command: string) => command.split(' && ')
611
+
612
+ /**
613
+ * The install line a person copies: the command, then `yarn generate` after a `yarn add` of a library or a provider
614
+ * and after `npx create-mercato-module install` (`yarn mercato module add` runs it itself), then `yarn db:migrate`
615
+ * after a module install (also the enterprise step) that adds tables or migrations or whose anatomy is unknown.
616
+ * `--json` keeps the bare command (tools@1).
617
+ */
618
+ export function withFollowUpSteps(command: string, entry: CatalogEntry): string {
619
+ const cmm = command.startsWith('npx create-mercato-module install')
620
+ const ofModules = entry.kind === 'module' || entry.kind === 'provider'
621
+ const moduleInstall =
622
+ (cmm && ofModules) || command.includes('yarn mercato module add') || command.startsWith(ENTERPRISE_ENABLE_STEP)
623
+ const addsPackage = command.startsWith('yarn add ') && (entry.kind === 'library' || entry.kind === 'provider')
624
+ const generate = (addsPackage || cmm) && !steps(command).includes('yarn generate')
625
+ const tables = entry.anatomy?.lists?.tables
626
+ const adds = tables === undefined || tables.length > 0 || (entry.anatomy?.counts?.migrations ?? 0) > 0
627
+ const migrate = moduleInstall && adds && !steps(command).includes('yarn db:migrate')
628
+ return [command, ...(generate ? ['yarn generate'] : []), ...(migrate ? ['yarn db:migrate'] : [])].join(' && ')
629
+ }
630
+
631
+ function installText(
632
+ install: Pick<ModuleCard, 'install' | 'presetNote' | 'installEmptyPreset'>,
633
+ entry: CatalogEntry,
634
+ ): string {
635
+ if (install.presetNote === undefined) return withFollowUpSteps(install.install, entry)
636
+ const empty = install.installEmptyPreset ?? null
637
+ return newAppInstallText(entry.moduleIds, empty === null ? null : withFollowUpSteps(empty, entry))
638
+ }
639
+
640
+ function entryHeading(entry: CatalogEntry, line: string | null): string {
641
+ const name = entry.npm ?? entry.locator.replace(/^github:/, '')
642
+ const version = installVersion(entry, line)
643
+ const origin = ORIGIN_LABEL[entry.type] ?? entry.type
644
+ return `${name}${version ? ` ${version}` : ''} ${levelLabel(entry, line)} ${origin} · ${licenseLabel(entry)}`
645
+ }
646
+
647
+ /** `today` (YYYY-MM-DD) decides whether `installable from` is still ahead (Yarn age gate). */
648
+ export function renderSearchHuman(view: ModuleSearchView, today: string = new Date().toISOString().slice(0, 10)): string[] {
649
+ const { json } = view
650
+ const out: string[] = []
651
+ if (view.lineNote) out.push(view.lineNote, '')
652
+ if (json.didYouMean) out.push(`Nothing matched "${json.query}". Showing results for "${json.didYouMean}".`, '')
653
+ if (json.builtIn.length > 0) {
654
+ out.push('Already in Open Mercato core:')
655
+ const idWidth = Math.max(...json.builtIn.map((card) => card.id.length))
656
+ const titleWidth = Math.max(...json.builtIn.map((card) => card.title.length))
657
+ for (const card of json.builtIn) {
658
+ const action = card.enabled ? 'Already enabled.' : card.enabled === false ? card.install : (card.presetNote ?? card.install)
659
+ out.push(` ${card.id.padEnd(idWidth)} ${card.title.padEnd(titleWidth)} ${action}`)
660
+ }
661
+ out.push('')
662
+ }
663
+ for (const card of json.results) {
664
+ const entry = view.entries.get(card.locator)
665
+ if (!entry) continue
666
+ out.push(entryHeading(entry, json.line))
667
+ if (card.summary) out.push(` ${card.summary}`)
668
+ const details = [
669
+ card.matchedOn.length > 0 ? `matched: ${card.matchedOn.join(', ')}` : null,
670
+ policyLabel(card.agentPolicy) ? `agent policy: ${policyLabel(card.agentPolicy)}` : null,
671
+ ].filter((item): item is string => item !== null)
672
+ if (details.length > 0) out.push(` ${details.join(' · ')}`)
673
+ if (card.installableFrom && card.installableFrom > today && card.status !== 'verified') {
674
+ out.push(` installable from: ${card.installableFrom}`)
675
+ }
676
+ out.push(` install: ${installText(card, entry)}`)
677
+ out.push(` more: ${card.card}`)
678
+ out.push('')
679
+ }
680
+ const hiddenLine =
681
+ json.hidden > 0 && json.line !== null
682
+ ? json.hidden === 1
683
+ ? `1 more module is listed but not verified on ${json.line}. Use --all-lines.`
684
+ : `${json.hidden} more modules are listed but not verified on ${json.line}. Use --all-lines.`
685
+ : null
686
+ if (json.results.length === 0 && json.builtIn.length === 0) {
687
+ const what = json.query ? `"${json.query}"` : 'the filters'
688
+ out.push(hiddenLine ? `No modules verified on ${json.line} matched ${what}.` : `No modules matched ${what}.`)
689
+ if (hiddenLine) out.push(hiddenLine)
690
+ out.push(`Browse the catalog: ${MODULES_SITE_URL}`)
691
+ } else if (hiddenLine) {
692
+ out.push(hiddenLine)
693
+ }
694
+ while (out.length > 0 && out[out.length - 1] === '') out.pop()
695
+ return out
696
+ }
697
+
698
+ export type ModuleInfoJson =
699
+ | {
700
+ schemaVersion: 1
701
+ line: string | null
702
+ entry: CatalogEntry | null
703
+ candidates: string[]
704
+ anatomy: null
705
+ warnings: string[]
706
+ untrusted: null
707
+ card: string | null
708
+ }
709
+ | { schemaVersion: 1; error: string; candidates: string[] }
710
+
711
+ export type ModuleInfoView = {
712
+ json: ModuleInfoJson
713
+ builtIn: BuiltInModule | null
714
+ builtInEnabled: boolean | null
715
+ found: boolean
716
+ }
717
+
718
+ export function buildInfoView(searcher: CatalogSearcher, ref: string, app: AppContext, today: string): ModuleInfoView {
719
+ const builtInModules = searcher.builtIn?.modules ?? []
720
+ const entries = searcher.index.entries
721
+ const latest = latestLine(searcher.index.lines)?.key ?? null
722
+ const line = app.omVersion ? resolveLine(app.omVersion, searcher.index.lines).line : latest
723
+ const resolved = resolveRef(ref, entries, builtInModules)
724
+ if (resolved.kind === 'builtin') {
725
+ const coreModule = resolved.builtIn
726
+ return {
727
+ json: {
728
+ schemaVersion: 1,
729
+ line,
730
+ entry: null,
731
+ candidates: resolved.candidates,
732
+ anatomy: null,
733
+ warnings: builtInWarnings(coreModule, line),
734
+ untrusted: null,
735
+ card: cardUrl(searcher, coreModule.page),
736
+ },
737
+ builtIn: coreModule,
738
+ builtInEnabled: builtInEnabled(coreModule.id, app.enabledModules),
739
+ found: true,
740
+ }
741
+ }
742
+ if (resolved.kind === 'none') {
743
+ const id = stripVersion(ref).name.trim().toLowerCase()
744
+ const shared = entries.filter((entry) => entry.moduleIds.includes(id))
745
+ if (shared.length > 1) {
746
+ return {
747
+ json: {
748
+ schemaVersion: 1,
749
+ line,
750
+ entry: null,
751
+ candidates: resolved.candidates,
752
+ anatomy: null,
753
+ warnings: [sharedModuleIdWarning(id, shared.length)],
754
+ untrusted: null,
755
+ card: null,
756
+ },
757
+ builtIn: null,
758
+ builtInEnabled: null,
759
+ found: true,
760
+ }
761
+ }
762
+ return {
763
+ json: { schemaVersion: 1, error: unknownModuleMessage(ref, resolved.candidates), candidates: resolved.candidates },
764
+ builtIn: null,
765
+ builtInEnabled: null,
766
+ found: false,
767
+ }
768
+ }
769
+ const entry = resolved.entry
770
+ return {
771
+ json: {
772
+ schemaVersion: 1,
773
+ line,
774
+ entry,
775
+ candidates: [],
776
+ anatomy: null,
777
+ warnings: entryWarnings(entry, today, line, receiptSourceOf(searcher)),
778
+ untrusted: null,
779
+ card: cardUrl(searcher, entry.links.md),
780
+ },
781
+ builtIn: null,
782
+ builtInEnabled: null,
783
+ found: true,
784
+ }
785
+ }
786
+
787
+ function plural(count: number, one: string, many: string): string {
788
+ return `${count} ${count === 1 ? one : many}`
789
+ }
790
+
791
+ function anatomyLine(entry: CatalogEntry): string | null {
792
+ const lists = entry.anatomy?.lists
793
+ if (!lists) return null
794
+ const parts = [
795
+ lists.tables && lists.tables.length > 0 ? plural(lists.tables.length, 'table', 'tables') : null,
796
+ lists.aclFeatures && lists.aclFeatures.length > 0 ? plural(lists.aclFeatures.length, 'permission', 'permissions') : null,
797
+ lists.eventsEmitted && lists.eventsEmitted.length > 0 ? `emits ${plural(lists.eventsEmitted.length, 'event', 'events')}` : null,
798
+ lists.publicRoutes && lists.publicRoutes.length > 0
799
+ ? plural(lists.publicRoutes.length, 'public route', 'public routes')
800
+ : null,
801
+ ].filter((item): item is string => item !== null)
802
+ return parts.length > 0 ? parts.join(' · ') : null
803
+ }
804
+
805
+ export function renderInfoHuman(view: ModuleInfoView, searcher: CatalogSearcher): string[] {
806
+ const { json } = view
807
+ if ('error' in json) return [json.error]
808
+ const out: string[] = []
809
+ if (view.builtIn) {
810
+ const coreModule = view.builtIn
811
+ out.push(`${coreModule.id} is built into Open Mercato core: ${coreModule.title}.`)
812
+ if (coreModule.description) out.push(` ${coreModule.description}`)
813
+ const presetNote = view.builtInEnabled === false ? null : builtInPresetText(coreModule, json.line)
814
+ if (view.builtInEnabled) out.push(' Already enabled.')
815
+ else if (presetNote) out.push(` ${presetNote}`)
816
+ else out.push(` enable: ${coreModule.install || builtInEnableCommand(coreModule.id)}`)
817
+ if (json.candidates.length > 0) out.push(` catalog modules with the same id: ${json.candidates.join(', ')}`)
818
+ if (json.card) out.push(` more: ${json.card}`)
819
+ return out
820
+ }
821
+ const entry = json.entry
822
+ if (!entry) {
823
+ out.push(...json.warnings)
824
+ if (json.candidates.length > 0) out.push(`Candidates: ${json.candidates.join(', ')}`)
825
+ return out
826
+ }
827
+ const line = json.line
828
+ out.push(entryHeading(entry, line))
829
+ out.push(` ${entry.title}: ${entry.summary}`)
830
+ if (entry.whenToUse) out.push(` ${entry.whenToUse}`)
831
+ const lines = searcher.index.lines.map((item) => `${item.key} ${statusOn(entry, item.key)}`)
832
+ if (lines.length > 0) out.push(` lines: ${lines.join(' · ')}`)
833
+ const policy = line ? (entry.agentPolicy[line] ?? null) : null
834
+ if (policy && line) {
835
+ out.push(` agent policy on ${line}: ${policy.decision}`)
836
+ for (const reason of policy.reasons.slice(0, 5)) out.push(` ${reason.code}: ${reason.text}`)
837
+ }
838
+ const adds = anatomyLine(entry)
839
+ if (adds) out.push(` adds: ${adds}`)
840
+ const lists = entry.anatomy?.lists
841
+ const settings = [...(lists?.env ?? []), ...(lists?.credentials ?? []).map((credential) => credential.key)]
842
+ if (settings.length > 0) out.push(` needs settings: ${settings.slice(0, 10).join(', ')}`)
843
+ if (lists?.hosts && lists.hosts.length > 0) out.push(` talks to: ${lists.hosts.slice(0, 10).join(', ')}`)
844
+ const install = installFields(entry, line, latestLine(searcher.index.lines)?.key ?? null, peerLookup(searcher))
845
+ out.push(` install: ${installText(install, entry)}`)
846
+ for (const warning of json.warnings) out.push(` warning: ${warning}`)
847
+ out.push(` install plan: ${json.card ?? entry.links.md}`)
848
+ out.push(` more: ${cardUrl(searcher, entry.links.page)}`)
849
+ return out
850
+ }
851
+
852
+ export type ModuleSearchDeps = {
853
+ appRoot?: string
854
+ env?: NodeJS.ProcessEnv
855
+ fetchImpl?: FetchLike
856
+ now?: () => number
857
+ stdout?: (line: string) => void
858
+ stderr?: (line: string) => void
859
+ readEnabledModules?: ReadEnabledModules | null
860
+ }
861
+
862
+ const SEARCH_USAGE =
863
+ 'Usage: yarn mercato module search [<query>] [--category <id>] [--kind <kind>] [--all-lines] [--limit <n>] [--json] (a query, a --category or a --kind)'
864
+ const INFO_USAGE = 'Usage: yarn mercato module info <package-or-module-id> [--json]'
865
+
866
+ export const BUILT_IN_UNAVAILABLE_MESSAGE =
867
+ 'Built-in module list unavailable; results may miss modules already in Open Mercato core.'
868
+
869
+ type LoadedForCommand = { searcher: CatalogSearcher; app: AppContext; builtInUnavailable: boolean }
870
+
871
+ async function loadForCommand(deps: ModuleSearchDeps): Promise<LoadedForCommand> {
872
+ const env = deps.env ?? process.env
873
+ const appRoot = deps.appRoot ?? createResolver().getAppDir()
874
+ const stderr = deps.stderr ?? ((line: string) => console.error(line))
875
+ const url = env.OM_MODULES_INDEX_URL?.trim() || DEFAULT_MODULES_INDEX_URL
876
+ const builtInUrl = env.OM_MODULES_BUILTIN_URL?.trim() || undefined
877
+ const loaded = await loadIndex({
878
+ appRoot,
879
+ url,
880
+ ...(builtInUrl ? { builtInUrl } : {}),
881
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
882
+ ...(deps.now ? { now: deps.now } : {}),
883
+ })
884
+ if (loaded.source === 'stale-cache') stderr(`Using cached module index from ${loaded.fetchedAt}.`)
885
+ if (loaded.builtInUnavailable !== null) {
886
+ stderr(BUILT_IN_UNAVAILABLE_MESSAGE)
887
+ stderr(`Reason: ${loaded.builtInUnavailable}`)
888
+ }
889
+ const app = detectAppContext(appRoot, deps.readEnabledModules ?? null, env)
890
+ return {
891
+ searcher: loaded.searcher,
892
+ app,
893
+ builtInUnavailable: loaded.builtInUnavailable !== null,
894
+ }
895
+ }
896
+
897
+ function handleLoadError(error: unknown, stderr: (line: string) => void): number {
898
+ if (error instanceof ModuleIndexUnavailableError) {
899
+ stderr(MODULE_INDEX_UNAVAILABLE_MESSAGE)
900
+ stderr(`Reason: ${error.detail}`)
901
+ return MODULE_INDEX_UNAVAILABLE_EXIT_CODE
902
+ }
903
+ throw error
904
+ }
905
+
906
+ export async function runModuleSearch(args: string[], deps: ModuleSearchDeps = {}): Promise<number> {
907
+ const stdout = deps.stdout ?? ((line: string) => console.log(line))
908
+ const stderr = deps.stderr ?? ((line: string) => console.error(line))
909
+ const parsed = parseModuleSearchArgs(args)
910
+ if (!parsed.query && !parsed.category && !parsed.kinds) {
911
+ stderr(SEARCH_USAGE)
912
+ return 1
913
+ }
914
+ let loaded: LoadedForCommand
915
+ try {
916
+ loaded = await loadForCommand(deps)
917
+ } catch (error: unknown) {
918
+ return handleLoadError(error, stderr)
919
+ }
920
+ const view = buildSearchView(
921
+ loaded.searcher,
922
+ { query: parsed.query, category: parsed.category, kinds: parsed.kinds, allLines: parsed.allLines, limit: parsed.limit },
923
+ loaded.app,
924
+ )
925
+ if (loaded.builtInUnavailable) view.json.builtInUnavailable = true
926
+ const today = new Date(deps.now ? deps.now() : Date.now()).toISOString().slice(0, 10)
927
+ if (parsed.json) stdout(JSON.stringify(view.json, null, 2))
928
+ else for (const line of renderSearchHuman(view, today)) stdout(line)
929
+ return 0
930
+ }
931
+
932
+ export async function runModuleInfo(args: string[], deps: ModuleSearchDeps = {}): Promise<number> {
933
+ const stdout = deps.stdout ?? ((line: string) => console.log(line))
934
+ const stderr = deps.stderr ?? ((line: string) => console.error(line))
935
+ const parsed = parseModuleInfoArgs(args)
936
+ if (!parsed.ref) {
937
+ stderr(INFO_USAGE)
938
+ return 1
939
+ }
940
+ let loaded: LoadedForCommand
941
+ try {
942
+ loaded = await loadForCommand(deps)
943
+ } catch (error: unknown) {
944
+ return handleLoadError(error, stderr)
945
+ }
946
+ const today = new Date(deps.now ? deps.now() : Date.now()).toISOString().slice(0, 10)
947
+ const view = buildInfoView(loaded.searcher, parsed.ref, loaded.app, today)
948
+ if (parsed.json) stdout(JSON.stringify(view.json, null, 2))
949
+ else if (view.found) for (const line of renderInfoHuman(view, loaded.searcher)) stdout(line)
950
+ else for (const line of renderInfoHuman(view, loaded.searcher)) stderr(line)
951
+ return view.found ? 0 : 1
952
+ }