@open-mercato/cli 0.10.1-develop.7758.1.fb3a60392f → 0.10.1-develop.7760.1.67d99945c0

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 (108) 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/module-search-args.js +97 -0
  88. package/dist/lib/module-search-args.js.map +7 -0
  89. package/dist/lib/module-search-index.js +677 -0
  90. package/dist/lib/module-search-index.js.map +7 -0
  91. package/dist/lib/module-search.js +668 -0
  92. package/dist/lib/module-search.js.map +7 -0
  93. package/dist/lib/modules-config.js +5 -0
  94. package/dist/lib/modules-config.js.map +2 -2
  95. package/dist/mercato.js +13 -3
  96. package/dist/mercato.js.map +2 -2
  97. package/package.json +8 -7
  98. package/src/__tests__/mercato.test.ts +57 -0
  99. package/src/lib/__fixtures__/module-search/README.md +97 -0
  100. package/src/lib/__fixtures__/module-search/built-in.json +235 -0
  101. package/src/lib/__fixtures__/module-search/catalog-parity.json +4076 -0
  102. package/src/lib/__fixtures__/module-search/modules-index.json +1980 -0
  103. package/src/lib/__tests__/module-search.test.ts +929 -0
  104. package/src/lib/module-search-args.ts +116 -0
  105. package/src/lib/module-search-index.ts +1033 -0
  106. package/src/lib/module-search.ts +952 -0
  107. package/src/lib/modules-config.ts +8 -0
  108. package/src/mercato.ts +17 -3
@@ -0,0 +1,668 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createResolver } from "./resolver.js";
4
+ import {
5
+ builtInEnableCommand,
6
+ builtInPresetText,
7
+ builtInWarnings,
8
+ cardUrl,
9
+ CORE_PACKAGE,
10
+ createCatalogSearcher,
11
+ ENTERPRISE_ENABLE_STEP,
12
+ entryWarnings,
13
+ installFields,
14
+ installVersion,
15
+ latestLine,
16
+ newAppInstallText,
17
+ peerLookup,
18
+ rankModules,
19
+ receiptSourceOf,
20
+ resolveLine,
21
+ resolveRef,
22
+ SEARCH_MAX_LIMIT,
23
+ sharedModuleIdWarning,
24
+ statusOn,
25
+ stripVersion,
26
+ toModuleCard,
27
+ unknownModuleMessage
28
+ } from "./module-search-index.js";
29
+ import { parseModuleInfoArgs, parseModuleSearchArgs } from "./module-search-args.js";
30
+ const DEFAULT_MODULES_INDEX_URL = "https://modules.openmercato.com/modules.json";
31
+ const MODULES_SITE_URL = "https://modules.openmercato.com";
32
+ const MODULE_INDEX_TIMEOUT_MS = 4e3;
33
+ const MODULE_INDEX_TTL_MS = 10 * 60 * 1e3;
34
+ const MODULE_INDEX_CACHE_FILE = path.join(".mercato", "cache", "modules-index.json");
35
+ const MODULE_INDEX_UNAVAILABLE_EXIT_CODE = 2;
36
+ const MODULE_INDEX_UNAVAILABLE_MESSAGE = "Module index unavailable. Check your connection or set OM_MODULES_INDEX_URL.";
37
+ class ModuleIndexUnavailableError extends Error {
38
+ constructor(detail) {
39
+ super(`${MODULE_INDEX_UNAVAILABLE_MESSAGE} (${detail})`);
40
+ this.name = "ModuleIndexUnavailableError";
41
+ this.detail = detail;
42
+ }
43
+ }
44
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
45
+ const isString = (value) => typeof value === "string";
46
+ const isStringArray = (value) => Array.isArray(value) && value.every(isString);
47
+ const isNullableString = (value) => value === null || isString(value);
48
+ const isArrayOf = (value, item) => Array.isArray(value) && value.every(item);
49
+ const isRecordOf = (value, item) => isRecord(value) && Object.values(value).every(item);
50
+ const isAbsentOr = (value, check) => value === void 0 || check(value);
51
+ const ANATOMY_LISTS = ["aclFeatures", "eventsEmitted", "eventsConsumed", "env", "hosts", "tables", "publicRoutes"];
52
+ function isAnatomy(value) {
53
+ if (value === null || value === void 0) return true;
54
+ if (!isRecord(value)) return false;
55
+ const lists = value.lists;
56
+ if (lists === void 0) return true;
57
+ return isRecord(lists) && ANATOMY_LISTS.every((key) => isAbsentOr(lists[key], isStringArray)) && isAbsentOr(
58
+ lists.credentials,
59
+ (credentials) => isArrayOf(credentials, (credential) => isRecord(credential) && isString(credential.key))
60
+ );
61
+ }
62
+ function isAgentPolicy(value) {
63
+ return isRecord(value) && isString(value.decision) && isArrayOf(value.reasons, (reason) => isRecord(reason) && isString(reason.code) && isString(reason.text));
64
+ }
65
+ function isBuiltFor(value) {
66
+ return isRecord(value) && isString(value.kind) && isNullableString(value.range) && isStringArray(value.lines) && isAbsentOr(value.ranges, (ranges) => isRecordOf(ranges, isString));
67
+ }
68
+ function isCompat(value) {
69
+ return isRecord(value) && isRecordOf(
70
+ value.lines,
71
+ (cell) => isRecord(cell) && isString(cell.status) && isAbsentOr(cell.at, isNullableString) && isAbsentOr(cell.moduleVersion, isNullableString)
72
+ ) && isStringArray(value.verifiedOn) && isAbsentOr(value.builtFor, isBuiltFor) && isAbsentOr(value.inPresets, isStringArray) && isAbsentOr(value.inEmptyPreset, isStringArray) && isAbsentOr(value.ships, (ships) => isRecordOf(ships, isString)) && isAbsentOr(
73
+ value.isolation,
74
+ (isolation) => isRecordOf(isolation, (cell) => isRecord(cell) && isString(cell.status) && isNullableString(cell.moduleVersion))
75
+ );
76
+ }
77
+ function isSignals(value) {
78
+ if (value === null || value === void 0) return true;
79
+ return isRecord(value) && isAbsentOr(value.supplyChain, (item) => isRecord(item) && isString(item.status) && isStringArray(item.reasons)) && isAbsentOr(value.hygiene, (item) => isRecord(item) && isString(item.status) && isStringArray(item.failing)) && isAbsentOr(value.anatomy, isString);
80
+ }
81
+ function isCatalogEntry(value) {
82
+ if (!isRecord(value)) return false;
83
+ const version = value.version;
84
+ const install = value.install;
85
+ const links = value.links;
86
+ const license = value.license;
87
+ return isString(value.locator) && isString(value.path) && (value.npm === null || isString(value.npm)) && isString(value.title) && isString(value.summary) && isString(value.whenToUse) && isString(value.type) && isString(value.kind) && isString(value.category) && isStringArray(value.tags) && isArrayOf(value.providers, (provider) => isRecord(provider) && isString(provider.name) && isString(provider.label)) && isStringArray(value.moduleIds) && isAbsentOr(
88
+ value.requires,
89
+ (requires) => isArrayOf(
90
+ requires,
91
+ (requirement) => isRecord(requirement) && isString(requirement.raw) && isAbsentOr(requirement.resolvesTo, isNullableString)
92
+ )
93
+ ) && isStringArray(value.renamedFrom) && isString(value.status) && typeof value.listed === "boolean" && typeof value.featured === "boolean" && isNullableString(value.tier) && isRecord(license) && isNullableString(license.spdx) && isString(license.kind) && isRecord(version) && isNullableString(version.latest) && isNullableString(version.preview) && isNullableString(version.installableFrom) && isNullableString(version.gitRef) && isRecordOf(version.recommended, isNullableString) && isCompat(value.compat) && isAnatomy(value.anatomy) && isSignals(value.signals) && isRecordOf(value.agentPolicy, isAgentPolicy) && isRecord(install) && isString(install.cli) && isAbsentOr(install.moduleFlag, isNullableString) && isRecord(links) && isString(links.page) && isString(links.md);
94
+ }
95
+ function parseCatalogIndex(value) {
96
+ if (!isRecord(value) || value.schemaVersion !== 1) return null;
97
+ if (!isString(value.generatedAt) || !isString(value.dataVersion) || !isString(value.site)) return null;
98
+ if (!Array.isArray(value.lines) || !Array.isArray(value.entries)) return null;
99
+ if (!isAbsentOr(value.dataAsOf, isRecord)) return null;
100
+ if (!value.lines.every((line) => isRecord(line) && isString(line.key) && isString(line.version) && isString(line.source))) {
101
+ return null;
102
+ }
103
+ if (!value.entries.every(isCatalogEntry)) return null;
104
+ const lines = value.lines.filter(
105
+ (line) => line.source === "latest" || line.source === "previous" || line.source === "develop"
106
+ );
107
+ return { ...value, lines };
108
+ }
109
+ function parseBuiltInIndex(value) {
110
+ if (!isRecord(value) || value.schemaVersion !== 1 || !isString(value.coreVersion) || !Array.isArray(value.modules)) {
111
+ return null;
112
+ }
113
+ const valid = value.modules.every(
114
+ (coreModule) => isRecord(coreModule) && isString(coreModule.id) && isString(coreModule.title) && isString(coreModule.description) && isString(coreModule.category) && isString(coreModule.install) && isString(coreModule.page) && isAbsentOr(coreModule.requires, isStringArray) && isAbsentOr(coreModule.inPresets, isStringArray) && isAbsentOr(coreModule.inEmptyPreset, isStringArray) && isAnatomy(coreModule.anatomy)
115
+ );
116
+ return valid ? value : null;
117
+ }
118
+ function parseCacheFile(value) {
119
+ if (!isRecord(value) || value.cacheVersion !== 1) return null;
120
+ if (!isString(value.url) || !isString(value.builtInUrl) || !isString(value.fetchedAt)) return null;
121
+ const index = parseCatalogIndex(value.index);
122
+ if (!index) return null;
123
+ const builtIn = value.builtIn === null ? null : parseBuiltInIndex(value.builtIn);
124
+ return {
125
+ cacheVersion: 1,
126
+ url: value.url,
127
+ builtInUrl: value.builtInUrl,
128
+ fetchedAt: value.fetchedAt,
129
+ etag: isString(value.etag) ? value.etag : null,
130
+ builtInEtag: isString(value.builtInEtag) ? value.builtInEtag : null,
131
+ index,
132
+ builtIn
133
+ };
134
+ }
135
+ function defaultBuiltInUrl(indexUrl) {
136
+ const url = new URL(indexUrl);
137
+ url.search = "";
138
+ url.hash = "";
139
+ url.pathname = url.pathname.replace(/[^/]*$/, "built-in.json");
140
+ return url.toString();
141
+ }
142
+ function readCache(file) {
143
+ try {
144
+ return parseCacheFile(JSON.parse(fs.readFileSync(file, "utf8")));
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+ function writeCache(file, cache) {
150
+ try {
151
+ fs.mkdirSync(path.dirname(file), { recursive: true });
152
+ const temporary = `${file}.${process.pid}.tmp`;
153
+ fs.writeFileSync(temporary, JSON.stringify(cache));
154
+ fs.renameSync(temporary, file);
155
+ } catch {
156
+ return;
157
+ }
158
+ }
159
+ async function fetchOnce(fetchImpl, url, etag, timeoutMs) {
160
+ const headers = { accept: "application/json" };
161
+ if (etag) headers["if-none-match"] = etag;
162
+ return fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
163
+ }
164
+ async function fetchWithRetry(fetchImpl, url, etag, timeoutMs) {
165
+ let lastError = null;
166
+ for (let attempt = 0; attempt < 2; attempt += 1) {
167
+ try {
168
+ const response = await fetchOnce(fetchImpl, url, etag, timeoutMs);
169
+ if (response.status >= 500) {
170
+ lastError = new Error(`${url} answered ${response.status}`);
171
+ continue;
172
+ }
173
+ return response;
174
+ } catch (error) {
175
+ lastError = error;
176
+ }
177
+ }
178
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
179
+ }
180
+ async function fetchJson(fetchImpl, url, etag, timeoutMs, parse) {
181
+ const response = await fetchWithRetry(fetchImpl, url, etag, timeoutMs);
182
+ if (response.status === 304) return { notModified: true };
183
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
184
+ const value = parse(await response.json());
185
+ if (value === null) throw new Error(`${url} is not a module index this CLI understands`);
186
+ return { notModified: false, value, etag: response.headers.get("etag") };
187
+ }
188
+ function searcherOf(index, builtIn) {
189
+ try {
190
+ return createCatalogSearcher(index, builtIn);
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
195
+ async function loadIndex(options) {
196
+ const url = options.url ?? DEFAULT_MODULES_INDEX_URL;
197
+ const builtInUrl = options.builtInUrl ?? defaultBuiltInUrl(url);
198
+ const timeoutMs = options.timeoutMs ?? MODULE_INDEX_TIMEOUT_MS;
199
+ const ttlMs = options.ttlMs ?? MODULE_INDEX_TTL_MS;
200
+ const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
201
+ const now = options.now ?? (() => Date.now());
202
+ const cacheFile = path.join(options.appRoot, MODULE_INDEX_CACHE_FILE);
203
+ const cached = readCache(cacheFile);
204
+ let usable = cached && cached.url === url && cached.builtInUrl === builtInUrl ? cached : null;
205
+ if (usable && usable.builtIn && now() - Date.parse(usable.fetchedAt) < ttlMs) {
206
+ const searcher = searcherOf(usable.index, usable.builtIn);
207
+ if (searcher) {
208
+ return { index: usable.index, builtIn: usable.builtIn, builtInUnavailable: null, source: "cache", fetchedAt: usable.fetchedAt, searcher };
209
+ }
210
+ usable = null;
211
+ }
212
+ try {
213
+ const indexResult = await fetchJson(fetchImpl, url, usable?.etag ?? null, timeoutMs, parseCatalogIndex);
214
+ let index;
215
+ let etag;
216
+ if (indexResult.notModified) {
217
+ if (!usable) throw new Error(`${url} answered 304 without a cached copy`);
218
+ index = usable.index;
219
+ etag = usable.etag;
220
+ } else {
221
+ index = indexResult.value;
222
+ etag = indexResult.etag;
223
+ }
224
+ let builtIn = usable?.builtIn ?? null;
225
+ let builtInEtag = usable?.builtInEtag ?? null;
226
+ let builtInUnavailable = null;
227
+ try {
228
+ const builtInResult = await fetchJson(
229
+ fetchImpl,
230
+ builtInUrl,
231
+ usable?.builtIn ? builtInEtag : null,
232
+ timeoutMs,
233
+ parseBuiltInIndex
234
+ );
235
+ if (!builtInResult.notModified) {
236
+ builtIn = builtInResult.value;
237
+ builtInEtag = builtInResult.etag;
238
+ }
239
+ } catch (error) {
240
+ builtIn = usable?.builtIn ?? null;
241
+ if (!builtIn) builtInUnavailable = error instanceof Error ? error.message : String(error);
242
+ }
243
+ const searcher = createCatalogSearcher(index, builtIn);
244
+ const fetchedAt = new Date(now()).toISOString();
245
+ writeCache(cacheFile, {
246
+ cacheVersion: 1,
247
+ url,
248
+ builtInUrl,
249
+ fetchedAt,
250
+ etag,
251
+ builtInEtag,
252
+ index,
253
+ builtIn
254
+ });
255
+ return { index, builtIn, builtInUnavailable, source: "network", fetchedAt, searcher };
256
+ } catch (error) {
257
+ const searcher = usable ? searcherOf(usable.index, usable.builtIn) : null;
258
+ if (usable && searcher) {
259
+ return {
260
+ index: usable.index,
261
+ builtIn: usable.builtIn,
262
+ builtInUnavailable: usable.builtIn ? null : "the cached copy has no built-in module list",
263
+ source: "stale-cache",
264
+ fetchedAt: usable.fetchedAt,
265
+ searcher
266
+ };
267
+ }
268
+ const detail = error instanceof Error ? error.message : String(error);
269
+ throw new ModuleIndexUnavailableError(detail);
270
+ }
271
+ }
272
+ function readJsonFile(file) {
273
+ try {
274
+ return JSON.parse(fs.readFileSync(file, "utf8"));
275
+ } catch {
276
+ return null;
277
+ }
278
+ }
279
+ function detectAppLine(appRoot) {
280
+ const installed = readJsonFile(path.join(appRoot, "node_modules", "@open-mercato", "core", "package.json"));
281
+ if (isRecord(installed) && isString(installed.version)) return installed.version;
282
+ const manifest = readJsonFile(path.join(appRoot, "package.json"));
283
+ if (!isRecord(manifest)) return null;
284
+ for (const field of ["dependencies", "devDependencies"]) {
285
+ const deps = manifest[field];
286
+ if (isRecord(deps) && isString(deps[CORE_PACKAGE])) {
287
+ const range = deps[CORE_PACKAGE].trim();
288
+ const match = /\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?/.exec(range);
289
+ return match ? match[0] : null;
290
+ }
291
+ }
292
+ return null;
293
+ }
294
+ function detectAppContext(appRoot, readEnabled, env = process.env) {
295
+ const modulesPath = path.join(appRoot, "src", "modules.ts");
296
+ let enabledModules = null;
297
+ if (readEnabled && fs.existsSync(modulesPath)) {
298
+ try {
299
+ enabledModules = readEnabled(modulesPath, env);
300
+ } catch {
301
+ enabledModules = null;
302
+ }
303
+ }
304
+ return { omVersion: detectAppLine(appRoot), enabledModules };
305
+ }
306
+ function builtInEnabled(id, enabled) {
307
+ if (!enabled) return null;
308
+ return enabled.some((coreModule) => coreModule.id === id && (coreModule.from ?? CORE_PACKAGE) === CORE_PACKAGE);
309
+ }
310
+ function buildSearchView(searcher, request, app) {
311
+ const resolved = app.omVersion ? resolveLine(app.omVersion, searcher.index.lines) : null;
312
+ const rankInput = {
313
+ query: request.query ?? "",
314
+ ...app.omVersion ? { omVersion: app.omVersion } : {},
315
+ ...request.category ? { category: request.category } : {},
316
+ ...request.kinds ? { kind: request.kinds } : {}
317
+ };
318
+ const unfiltered = rankModules(searcher, rankInput);
319
+ const line = unfiltered.line;
320
+ const allLines = request.allLines === true || line === null;
321
+ const ranked = allLines ? unfiltered : rankModules(searcher, { ...rankInput, verifiedModulesOnly: true });
322
+ const kept = ranked.modules;
323
+ const hidden = allLines ? 0 : unfiltered.modules.filter(
324
+ (hit) => hit.meta.entry.kind === "module" && (line === null || !hit.meta.entry.version.recommended[line])
325
+ ).length;
326
+ const limit = Math.min(SEARCH_MAX_LIMIT, Math.max(1, Math.floor(request.limit ?? 10)));
327
+ const results = kept.slice(0, limit).map((hit) => toModuleCard(searcher, hit, line, ranked.latest));
328
+ const entries = /* @__PURE__ */ new Map();
329
+ for (const hit of kept.slice(0, limit)) entries.set(hit.meta.entry.locator, hit.meta.entry);
330
+ const builtIn = ranked.builtIn.map((card) => ({ ...card, enabled: builtInEnabled(card.id, app.enabledModules) }));
331
+ const lineNote = resolved && resolved.line === null ? `Open Mercato ${app.omVersion} is not a line the catalog tests (${resolved.note ?? "unknown version"}). Showing modules for every line.` : null;
332
+ return {
333
+ json: {
334
+ schemaVersion: 1,
335
+ query: request.query ?? "",
336
+ line,
337
+ omVersion: app.omVersion,
338
+ results,
339
+ builtIn,
340
+ total: unfiltered.modules.length,
341
+ hidden,
342
+ dataVersion: searcher.index.dataVersion,
343
+ generatedAt: searcher.index.generatedAt,
344
+ receiptSource: receiptSourceOf(searcher),
345
+ ...ranked.didYouMean ? { didYouMean: ranked.didYouMean } : {}
346
+ },
347
+ entries,
348
+ lineNote,
349
+ allLines
350
+ };
351
+ }
352
+ const ORIGIN_LABEL = { official: "official", community: "community", "3rd-party": "3rd-party" };
353
+ function levelLabel(entry, line) {
354
+ const level = entry.quality ? "OM QUALITY" : entry.tier === "verified" ? "VERIFIED" : "LISTED";
355
+ if (line === null) return level;
356
+ const status = statusOn(entry, line);
357
+ return status === "verified" ? `${level} \xB7 ${line}` : `${level} \xB7 ${status} on ${line}`;
358
+ }
359
+ function policyLabel(policy) {
360
+ if (!policy) return null;
361
+ const reasons = policy.reasons.slice(0, 2).map((reason) => reason.code.toLowerCase().replace(/_/g, "-"));
362
+ return reasons.length > 0 ? `${policy.decision} (${reasons.join(", ")})` : policy.decision;
363
+ }
364
+ function licenseLabel(entry) {
365
+ return entry.license.spdx ?? entry.license.kind;
366
+ }
367
+ const steps = (command) => command.split(" && ");
368
+ function withFollowUpSteps(command, entry) {
369
+ const cmm = command.startsWith("npx create-mercato-module install");
370
+ const ofModules = entry.kind === "module" || entry.kind === "provider";
371
+ const moduleInstall = cmm && ofModules || command.includes("yarn mercato module add") || command.startsWith(ENTERPRISE_ENABLE_STEP);
372
+ const addsPackage = command.startsWith("yarn add ") && (entry.kind === "library" || entry.kind === "provider");
373
+ const generate = (addsPackage || cmm) && !steps(command).includes("yarn generate");
374
+ const tables = entry.anatomy?.lists?.tables;
375
+ const adds = tables === void 0 || tables.length > 0 || (entry.anatomy?.counts?.migrations ?? 0) > 0;
376
+ const migrate = moduleInstall && adds && !steps(command).includes("yarn db:migrate");
377
+ return [command, ...generate ? ["yarn generate"] : [], ...migrate ? ["yarn db:migrate"] : []].join(" && ");
378
+ }
379
+ function installText(install, entry) {
380
+ if (install.presetNote === void 0) return withFollowUpSteps(install.install, entry);
381
+ const empty = install.installEmptyPreset ?? null;
382
+ return newAppInstallText(entry.moduleIds, empty === null ? null : withFollowUpSteps(empty, entry));
383
+ }
384
+ function entryHeading(entry, line) {
385
+ const name = entry.npm ?? entry.locator.replace(/^github:/, "");
386
+ const version = installVersion(entry, line);
387
+ const origin = ORIGIN_LABEL[entry.type] ?? entry.type;
388
+ return `${name}${version ? ` ${version}` : ""} ${levelLabel(entry, line)} ${origin} \xB7 ${licenseLabel(entry)}`;
389
+ }
390
+ function renderSearchHuman(view, today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)) {
391
+ const { json } = view;
392
+ const out = [];
393
+ if (view.lineNote) out.push(view.lineNote, "");
394
+ if (json.didYouMean) out.push(`Nothing matched "${json.query}". Showing results for "${json.didYouMean}".`, "");
395
+ if (json.builtIn.length > 0) {
396
+ out.push("Already in Open Mercato core:");
397
+ const idWidth = Math.max(...json.builtIn.map((card) => card.id.length));
398
+ const titleWidth = Math.max(...json.builtIn.map((card) => card.title.length));
399
+ for (const card of json.builtIn) {
400
+ const action = card.enabled ? "Already enabled." : card.enabled === false ? card.install : card.presetNote ?? card.install;
401
+ out.push(` ${card.id.padEnd(idWidth)} ${card.title.padEnd(titleWidth)} ${action}`);
402
+ }
403
+ out.push("");
404
+ }
405
+ for (const card of json.results) {
406
+ const entry = view.entries.get(card.locator);
407
+ if (!entry) continue;
408
+ out.push(entryHeading(entry, json.line));
409
+ if (card.summary) out.push(` ${card.summary}`);
410
+ const details = [
411
+ card.matchedOn.length > 0 ? `matched: ${card.matchedOn.join(", ")}` : null,
412
+ policyLabel(card.agentPolicy) ? `agent policy: ${policyLabel(card.agentPolicy)}` : null
413
+ ].filter((item) => item !== null);
414
+ if (details.length > 0) out.push(` ${details.join(" \xB7 ")}`);
415
+ if (card.installableFrom && card.installableFrom > today && card.status !== "verified") {
416
+ out.push(` installable from: ${card.installableFrom}`);
417
+ }
418
+ out.push(` install: ${installText(card, entry)}`);
419
+ out.push(` more: ${card.card}`);
420
+ out.push("");
421
+ }
422
+ const hiddenLine = json.hidden > 0 && json.line !== null ? json.hidden === 1 ? `1 more module is listed but not verified on ${json.line}. Use --all-lines.` : `${json.hidden} more modules are listed but not verified on ${json.line}. Use --all-lines.` : null;
423
+ if (json.results.length === 0 && json.builtIn.length === 0) {
424
+ const what = json.query ? `"${json.query}"` : "the filters";
425
+ out.push(hiddenLine ? `No modules verified on ${json.line} matched ${what}.` : `No modules matched ${what}.`);
426
+ if (hiddenLine) out.push(hiddenLine);
427
+ out.push(`Browse the catalog: ${MODULES_SITE_URL}`);
428
+ } else if (hiddenLine) {
429
+ out.push(hiddenLine);
430
+ }
431
+ while (out.length > 0 && out[out.length - 1] === "") out.pop();
432
+ return out;
433
+ }
434
+ function buildInfoView(searcher, ref, app, today) {
435
+ const builtInModules = searcher.builtIn?.modules ?? [];
436
+ const entries = searcher.index.entries;
437
+ const latest = latestLine(searcher.index.lines)?.key ?? null;
438
+ const line = app.omVersion ? resolveLine(app.omVersion, searcher.index.lines).line : latest;
439
+ const resolved = resolveRef(ref, entries, builtInModules);
440
+ if (resolved.kind === "builtin") {
441
+ const coreModule = resolved.builtIn;
442
+ return {
443
+ json: {
444
+ schemaVersion: 1,
445
+ line,
446
+ entry: null,
447
+ candidates: resolved.candidates,
448
+ anatomy: null,
449
+ warnings: builtInWarnings(coreModule, line),
450
+ untrusted: null,
451
+ card: cardUrl(searcher, coreModule.page)
452
+ },
453
+ builtIn: coreModule,
454
+ builtInEnabled: builtInEnabled(coreModule.id, app.enabledModules),
455
+ found: true
456
+ };
457
+ }
458
+ if (resolved.kind === "none") {
459
+ const id = stripVersion(ref).name.trim().toLowerCase();
460
+ const shared = entries.filter((entry2) => entry2.moduleIds.includes(id));
461
+ if (shared.length > 1) {
462
+ return {
463
+ json: {
464
+ schemaVersion: 1,
465
+ line,
466
+ entry: null,
467
+ candidates: resolved.candidates,
468
+ anatomy: null,
469
+ warnings: [sharedModuleIdWarning(id, shared.length)],
470
+ untrusted: null,
471
+ card: null
472
+ },
473
+ builtIn: null,
474
+ builtInEnabled: null,
475
+ found: true
476
+ };
477
+ }
478
+ return {
479
+ json: { schemaVersion: 1, error: unknownModuleMessage(ref, resolved.candidates), candidates: resolved.candidates },
480
+ builtIn: null,
481
+ builtInEnabled: null,
482
+ found: false
483
+ };
484
+ }
485
+ const entry = resolved.entry;
486
+ return {
487
+ json: {
488
+ schemaVersion: 1,
489
+ line,
490
+ entry,
491
+ candidates: [],
492
+ anatomy: null,
493
+ warnings: entryWarnings(entry, today, line, receiptSourceOf(searcher)),
494
+ untrusted: null,
495
+ card: cardUrl(searcher, entry.links.md)
496
+ },
497
+ builtIn: null,
498
+ builtInEnabled: null,
499
+ found: true
500
+ };
501
+ }
502
+ function plural(count, one, many) {
503
+ return `${count} ${count === 1 ? one : many}`;
504
+ }
505
+ function anatomyLine(entry) {
506
+ const lists = entry.anatomy?.lists;
507
+ if (!lists) return null;
508
+ const parts = [
509
+ lists.tables && lists.tables.length > 0 ? plural(lists.tables.length, "table", "tables") : null,
510
+ lists.aclFeatures && lists.aclFeatures.length > 0 ? plural(lists.aclFeatures.length, "permission", "permissions") : null,
511
+ lists.eventsEmitted && lists.eventsEmitted.length > 0 ? `emits ${plural(lists.eventsEmitted.length, "event", "events")}` : null,
512
+ lists.publicRoutes && lists.publicRoutes.length > 0 ? plural(lists.publicRoutes.length, "public route", "public routes") : null
513
+ ].filter((item) => item !== null);
514
+ return parts.length > 0 ? parts.join(" \xB7 ") : null;
515
+ }
516
+ function renderInfoHuman(view, searcher) {
517
+ const { json } = view;
518
+ if ("error" in json) return [json.error];
519
+ const out = [];
520
+ if (view.builtIn) {
521
+ const coreModule = view.builtIn;
522
+ out.push(`${coreModule.id} is built into Open Mercato core: ${coreModule.title}.`);
523
+ if (coreModule.description) out.push(` ${coreModule.description}`);
524
+ const presetNote = view.builtInEnabled === false ? null : builtInPresetText(coreModule, json.line);
525
+ if (view.builtInEnabled) out.push(" Already enabled.");
526
+ else if (presetNote) out.push(` ${presetNote}`);
527
+ else out.push(` enable: ${coreModule.install || builtInEnableCommand(coreModule.id)}`);
528
+ if (json.candidates.length > 0) out.push(` catalog modules with the same id: ${json.candidates.join(", ")}`);
529
+ if (json.card) out.push(` more: ${json.card}`);
530
+ return out;
531
+ }
532
+ const entry = json.entry;
533
+ if (!entry) {
534
+ out.push(...json.warnings);
535
+ if (json.candidates.length > 0) out.push(`Candidates: ${json.candidates.join(", ")}`);
536
+ return out;
537
+ }
538
+ const line = json.line;
539
+ out.push(entryHeading(entry, line));
540
+ out.push(` ${entry.title}: ${entry.summary}`);
541
+ if (entry.whenToUse) out.push(` ${entry.whenToUse}`);
542
+ const lines = searcher.index.lines.map((item) => `${item.key} ${statusOn(entry, item.key)}`);
543
+ if (lines.length > 0) out.push(` lines: ${lines.join(" \xB7 ")}`);
544
+ const policy = line ? entry.agentPolicy[line] ?? null : null;
545
+ if (policy && line) {
546
+ out.push(` agent policy on ${line}: ${policy.decision}`);
547
+ for (const reason of policy.reasons.slice(0, 5)) out.push(` ${reason.code}: ${reason.text}`);
548
+ }
549
+ const adds = anatomyLine(entry);
550
+ if (adds) out.push(` adds: ${adds}`);
551
+ const lists = entry.anatomy?.lists;
552
+ const settings = [...lists?.env ?? [], ...(lists?.credentials ?? []).map((credential) => credential.key)];
553
+ if (settings.length > 0) out.push(` needs settings: ${settings.slice(0, 10).join(", ")}`);
554
+ if (lists?.hosts && lists.hosts.length > 0) out.push(` talks to: ${lists.hosts.slice(0, 10).join(", ")}`);
555
+ const install = installFields(entry, line, latestLine(searcher.index.lines)?.key ?? null, peerLookup(searcher));
556
+ out.push(` install: ${installText(install, entry)}`);
557
+ for (const warning of json.warnings) out.push(` warning: ${warning}`);
558
+ out.push(` install plan: ${json.card ?? entry.links.md}`);
559
+ out.push(` more: ${cardUrl(searcher, entry.links.page)}`);
560
+ return out;
561
+ }
562
+ const SEARCH_USAGE = "Usage: yarn mercato module search [<query>] [--category <id>] [--kind <kind>] [--all-lines] [--limit <n>] [--json] (a query, a --category or a --kind)";
563
+ const INFO_USAGE = "Usage: yarn mercato module info <package-or-module-id> [--json]";
564
+ const BUILT_IN_UNAVAILABLE_MESSAGE = "Built-in module list unavailable; results may miss modules already in Open Mercato core.";
565
+ async function loadForCommand(deps) {
566
+ const env = deps.env ?? process.env;
567
+ const appRoot = deps.appRoot ?? createResolver().getAppDir();
568
+ const stderr = deps.stderr ?? ((line) => console.error(line));
569
+ const url = env.OM_MODULES_INDEX_URL?.trim() || DEFAULT_MODULES_INDEX_URL;
570
+ const builtInUrl = env.OM_MODULES_BUILTIN_URL?.trim() || void 0;
571
+ const loaded = await loadIndex({
572
+ appRoot,
573
+ url,
574
+ ...builtInUrl ? { builtInUrl } : {},
575
+ ...deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
576
+ ...deps.now ? { now: deps.now } : {}
577
+ });
578
+ if (loaded.source === "stale-cache") stderr(`Using cached module index from ${loaded.fetchedAt}.`);
579
+ if (loaded.builtInUnavailable !== null) {
580
+ stderr(BUILT_IN_UNAVAILABLE_MESSAGE);
581
+ stderr(`Reason: ${loaded.builtInUnavailable}`);
582
+ }
583
+ const app = detectAppContext(appRoot, deps.readEnabledModules ?? null, env);
584
+ return {
585
+ searcher: loaded.searcher,
586
+ app,
587
+ builtInUnavailable: loaded.builtInUnavailable !== null
588
+ };
589
+ }
590
+ function handleLoadError(error, stderr) {
591
+ if (error instanceof ModuleIndexUnavailableError) {
592
+ stderr(MODULE_INDEX_UNAVAILABLE_MESSAGE);
593
+ stderr(`Reason: ${error.detail}`);
594
+ return MODULE_INDEX_UNAVAILABLE_EXIT_CODE;
595
+ }
596
+ throw error;
597
+ }
598
+ async function runModuleSearch(args, deps = {}) {
599
+ const stdout = deps.stdout ?? ((line) => console.log(line));
600
+ const stderr = deps.stderr ?? ((line) => console.error(line));
601
+ const parsed = parseModuleSearchArgs(args);
602
+ if (!parsed.query && !parsed.category && !parsed.kinds) {
603
+ stderr(SEARCH_USAGE);
604
+ return 1;
605
+ }
606
+ let loaded;
607
+ try {
608
+ loaded = await loadForCommand(deps);
609
+ } catch (error) {
610
+ return handleLoadError(error, stderr);
611
+ }
612
+ const view = buildSearchView(
613
+ loaded.searcher,
614
+ { query: parsed.query, category: parsed.category, kinds: parsed.kinds, allLines: parsed.allLines, limit: parsed.limit },
615
+ loaded.app
616
+ );
617
+ if (loaded.builtInUnavailable) view.json.builtInUnavailable = true;
618
+ const today = new Date(deps.now ? deps.now() : Date.now()).toISOString().slice(0, 10);
619
+ if (parsed.json) stdout(JSON.stringify(view.json, null, 2));
620
+ else for (const line of renderSearchHuman(view, today)) stdout(line);
621
+ return 0;
622
+ }
623
+ async function runModuleInfo(args, deps = {}) {
624
+ const stdout = deps.stdout ?? ((line) => console.log(line));
625
+ const stderr = deps.stderr ?? ((line) => console.error(line));
626
+ const parsed = parseModuleInfoArgs(args);
627
+ if (!parsed.ref) {
628
+ stderr(INFO_USAGE);
629
+ return 1;
630
+ }
631
+ let loaded;
632
+ try {
633
+ loaded = await loadForCommand(deps);
634
+ } catch (error) {
635
+ return handleLoadError(error, stderr);
636
+ }
637
+ const today = new Date(deps.now ? deps.now() : Date.now()).toISOString().slice(0, 10);
638
+ const view = buildInfoView(loaded.searcher, parsed.ref, loaded.app, today);
639
+ if (parsed.json) stdout(JSON.stringify(view.json, null, 2));
640
+ else if (view.found) for (const line of renderInfoHuman(view, loaded.searcher)) stdout(line);
641
+ else for (const line of renderInfoHuman(view, loaded.searcher)) stderr(line);
642
+ return view.found ? 0 : 1;
643
+ }
644
+ export {
645
+ BUILT_IN_UNAVAILABLE_MESSAGE,
646
+ DEFAULT_MODULES_INDEX_URL,
647
+ MODULES_SITE_URL,
648
+ MODULE_INDEX_CACHE_FILE,
649
+ MODULE_INDEX_TIMEOUT_MS,
650
+ MODULE_INDEX_TTL_MS,
651
+ MODULE_INDEX_UNAVAILABLE_EXIT_CODE,
652
+ MODULE_INDEX_UNAVAILABLE_MESSAGE,
653
+ ModuleIndexUnavailableError,
654
+ buildInfoView,
655
+ buildSearchView,
656
+ defaultBuiltInUrl,
657
+ detectAppContext,
658
+ detectAppLine,
659
+ loadIndex,
660
+ parseBuiltInIndex,
661
+ parseCatalogIndex,
662
+ renderInfoHuman,
663
+ renderSearchHuman,
664
+ runModuleInfo,
665
+ runModuleSearch,
666
+ withFollowUpSteps
667
+ };
668
+ //# sourceMappingURL=module-search.js.map