@open-mercato/cli 0.6.7-develop.6828.1.ab1620a63e → 0.6.7-develop.6842.1.8cd8a8883c

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 (76) hide show
  1. package/.turbo/turbo-build.log +3 -3
  2. package/dist/agentic/guides/module-facts.json +110 -110
  3. package/dist/agentic/guides/modules/ai_assistant.md +1 -1
  4. package/dist/agentic/guides/modules/api_docs.md +1 -1
  5. package/dist/agentic/guides/modules/api_keys.md +1 -1
  6. package/dist/agentic/guides/modules/attachments.md +1 -1
  7. package/dist/agentic/guides/modules/audit_logs.md +1 -1
  8. package/dist/agentic/guides/modules/auth.md +1 -1
  9. package/dist/agentic/guides/modules/business_rules.md +1 -1
  10. package/dist/agentic/guides/modules/catalog.md +1 -1
  11. package/dist/agentic/guides/modules/channel_gmail.md +1 -1
  12. package/dist/agentic/guides/modules/channel_imap.md +1 -1
  13. package/dist/agentic/guides/modules/checkout.md +1 -1
  14. package/dist/agentic/guides/modules/communication_channels.md +1 -1
  15. package/dist/agentic/guides/modules/configs.md +1 -1
  16. package/dist/agentic/guides/modules/content.md +1 -1
  17. package/dist/agentic/guides/modules/currencies.md +1 -1
  18. package/dist/agentic/guides/modules/customer_accounts.md +1 -1
  19. package/dist/agentic/guides/modules/customers.md +1 -1
  20. package/dist/agentic/guides/modules/dashboards.md +1 -1
  21. package/dist/agentic/guides/modules/data_sync.md +1 -1
  22. package/dist/agentic/guides/modules/design_system.md +1 -1
  23. package/dist/agentic/guides/modules/dictionaries.md +1 -1
  24. package/dist/agentic/guides/modules/directory.md +1 -1
  25. package/dist/agentic/guides/modules/entities.md +1 -1
  26. package/dist/agentic/guides/modules/events.md +1 -1
  27. package/dist/agentic/guides/modules/feature_toggles.md +1 -1
  28. package/dist/agentic/guides/modules/gateway_stripe.md +1 -1
  29. package/dist/agentic/guides/modules/generators.md +1 -1
  30. package/dist/agentic/guides/modules/inbox_ops.md +1 -1
  31. package/dist/agentic/guides/modules/integrations.md +1 -1
  32. package/dist/agentic/guides/modules/messages.md +1 -1
  33. package/dist/agentic/guides/modules/notifications.md +1 -1
  34. package/dist/agentic/guides/modules/onboarding.md +1 -1
  35. package/dist/agentic/guides/modules/payment_gateways.md +1 -1
  36. package/dist/agentic/guides/modules/perspectives.md +1 -1
  37. package/dist/agentic/guides/modules/planner.md +1 -1
  38. package/dist/agentic/guides/modules/portal.md +1 -1
  39. package/dist/agentic/guides/modules/progress.md +1 -1
  40. package/dist/agentic/guides/modules/query_index.md +1 -1
  41. package/dist/agentic/guides/modules/record_locks.md +1 -1
  42. package/dist/agentic/guides/modules/resources.md +1 -1
  43. package/dist/agentic/guides/modules/sales.md +1 -1
  44. package/dist/agentic/guides/modules/scheduler.md +1 -1
  45. package/dist/agentic/guides/modules/search.md +1 -1
  46. package/dist/agentic/guides/modules/security.md +1 -1
  47. package/dist/agentic/guides/modules/shipping_carriers.md +1 -1
  48. package/dist/agentic/guides/modules/sso.md +1 -1
  49. package/dist/agentic/guides/modules/staff.md +1 -1
  50. package/dist/agentic/guides/modules/storage_s3.md +1 -1
  51. package/dist/agentic/guides/modules/sync_akeneo.md +1 -1
  52. package/dist/agentic/guides/modules/sync_excel.md +1 -1
  53. package/dist/agentic/guides/modules/system_status_overlays.md +1 -1
  54. package/dist/agentic/guides/modules/translations.md +1 -1
  55. package/dist/agentic/guides/modules/webhooks.md +1 -1
  56. package/dist/agentic/guides/modules/wms.md +1 -1
  57. package/dist/agentic/guides/modules/workflows.md +1 -1
  58. package/dist/agentic/guides/upstream/AGENTS.md +2 -1
  59. package/dist/agentic/guides/upstream/manifest.json +2 -2
  60. package/dist/agentic/shared/ai/agentic.config.json +1 -0
  61. package/dist/agentic/shared/ai/trackers/github.md +2 -1
  62. package/dist/bin.js +13 -1
  63. package/dist/bin.js.map +2 -2
  64. package/dist/lib/load-env.js +24 -0
  65. package/dist/lib/load-env.js.map +7 -0
  66. package/dist/lib/telemetry-init.js +358 -0
  67. package/dist/lib/telemetry-init.js.map +7 -0
  68. package/dist/mercato.js +15 -1
  69. package/dist/mercato.js.map +2 -2
  70. package/package.json +6 -5
  71. package/src/bin.ts +33 -1
  72. package/src/lib/__tests__/load-env.test.ts +65 -0
  73. package/src/lib/__tests__/telemetry-init.test.ts +298 -0
  74. package/src/lib/load-env.ts +30 -0
  75. package/src/lib/telemetry-init.ts +461 -0
  76. package/src/mercato.ts +18 -1
@@ -0,0 +1,461 @@
1
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
2
+ import { dirname, join, resolve } from 'node:path'
3
+
4
+ /**
5
+ * `mercato telemetry init` — wire `@open-mercato/telemetry` into an app that was
6
+ * scaffolded before telemetry existed. Deterministic, idempotent, and safe to
7
+ * re-run: each step detects whether it is already applied and skips.
8
+ *
9
+ * The web-tier wiring lives in app-owned source files (a dependency bump cannot
10
+ * touch them), so this patches them in place using the same idioms the rest of
11
+ * the CLI uses: JSON edits, detect-before-append for `.env`, a ts-morph edit for
12
+ * `next.config.ts`, and anchored insertion for `instrumentation.ts` + the API
13
+ * dispatcher. When a file's shape is not recognized (a customized dispatcher, an
14
+ * unusual next.config), the step degrades to printing the exact snippet and
15
+ * flags it as a manual step rather than editing code it does not understand.
16
+ *
17
+ * Worker/scheduler telemetry is not handled here — it ships transitively via
18
+ * `@open-mercato/cli`'s telemetry dependency once the app updates its packages.
19
+ */
20
+
21
+ const BULLMQ_OTEL_VERSION = '^1.3.1'
22
+
23
+ type StepStatus = 'created' | 'patched' | 'skipped' | 'manual'
24
+
25
+ type StepResult = {
26
+ file: string
27
+ status: StepStatus
28
+ detail: string
29
+ /** Snippet to show when the step needs manual work. */
30
+ manualSnippet?: string
31
+ }
32
+
33
+ type TelemetryInitOptions = {
34
+ dryRun: boolean
35
+ }
36
+
37
+ const ENV_BLOCK = `
38
+ # --- Telemetry & Observability (vendor-neutral OTLP: traces, logs, metrics, errors) ---
39
+ # Off by default: leave TELEMETRY_BACKEND unset (or =noop) for a hard no-op
40
+ # (the OpenTelemetry SDK is never loaded). Set to 'console' for local span/metric
41
+ # output, or an OTLP backend to export: 'signoz' | 'newrelic' | 'otlp' (generic).
42
+ # All three OTLP names use the same exporter — they differ only by the endpoint +
43
+ # headers below. Any OTLP backend is a one-line swap; no code change.
44
+ # TELEMETRY_BACKEND=otlp
45
+ # Logs use the shared logger facade and its OM_LOG_LEVEL / OM_LOG_PRETTY /
46
+ # OM_LOG_DESTINATION controls. Telemetry adds remote export; it does not create
47
+ # a second local output path.
48
+ # TELEMETRY_SAMPLING_RATIO=1.0 # 0.0–1.0 (default 1.0 dev / 0.1 prod)
49
+ # TELEMETRY_TRUST_INBOUND_TRACE=false # default false: root-per-request (ignore an
50
+ # # inbound traceparent from a proxy/LB). Set true
51
+ # # only behind a trusted upstream whose trace continues.
52
+ # # This also enables richer bullmq-otel spans;
53
+ # # otherwise async queues use metadata._trace.
54
+ #
55
+ # OTLP endpoint + auth — pick ONE vendor (use your region's host):
56
+ # SigNoz Cloud:
57
+ # OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.<region>.signoz.cloud:443
58
+ # OTEL_EXPORTER_OTLP_HEADERS=signoz-ingestion-key=<your-ingestion-key>
59
+ # New Relic (OTLP-native; EU host shown, US is https://otlp.nr-data.net):
60
+ # OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.eu01.nr-data.net
61
+ # OTEL_EXPORTER_OTLP_HEADERS=api-key=<your-ingest-license-key>
62
+ #
63
+ # Resource identity: keep one stable service name across environments and
64
+ # separate envs via the deployment.environment resource attribute.
65
+ # OTEL_SERVICE_NAME=open-mercato
66
+ # OTEL_RESOURCE_ATTRIBUTES=deployment.environment=local
67
+ `
68
+
69
+ const INSTRUMENTATION_TS = `import { isTelemetryBackendEnabled } from '@open-mercato/shared/lib/telemetry/runtime'
70
+
71
+ export async function register(): Promise<void> {
72
+ // Initialize telemetry (no-op unless TELEMETRY_BACKEND is set). OTEL's NodeSDK
73
+ // is Node-only and incompatible with the edge runtime, so the telemetry
74
+ // bootstrap — which can pull in the SDK — is imported only on the Node.js
75
+ // runtime. The helper owns init + graceful degrade + shutdown flush.
76
+ if (
77
+ process.env.NEXT_RUNTIME === 'nodejs'
78
+ && isTelemetryBackendEnabled()
79
+ ) {
80
+ const { registerTelemetryForNextjs } = await import('@open-mercato/telemetry/nextjs')
81
+ await registerTelemetryForNextjs()
82
+ }
83
+ }
84
+ `
85
+
86
+ const DISPATCHER_SNIPPET = ` // add near the other imports:
87
+ import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
88
+
89
+ // in the dispatcher's success path, just before returning the response:
90
+ getTelemetryRuntime()?.recordHttpDuration(method, match.route.path, finalResponse.status, startedAt)
91
+
92
+ // in the dispatcher's catch (error) block, before re-throwing:
93
+ getTelemetryRuntime()?.reportError(error, {
94
+ attributes: { 'http.request.method': method, 'http.route': match.route.path, 'http.response.status_code': 500 },
95
+ })
96
+ getTelemetryRuntime()?.recordHttpDuration(method, match.route.path, 500, startedAt)`
97
+
98
+ function parseArgs(args: string[]): TelemetryInitOptions {
99
+ return {
100
+ dryRun: args.includes('--dry-run') || args.includes('-n'),
101
+ }
102
+ }
103
+
104
+ /** Read the version an app already pins its `@open-mercato/*` deps to (lockstep). */
105
+ function resolveOpenMercatoVersion(pkg: Record<string, unknown>): string {
106
+ for (const field of ['dependencies', 'devDependencies'] as const) {
107
+ const deps = pkg[field]
108
+ if (deps && typeof deps === 'object') {
109
+ for (const [name, version] of Object.entries(deps as Record<string, string>)) {
110
+ if (name.startsWith('@open-mercato/') && typeof version === 'string') return version
111
+ }
112
+ }
113
+ }
114
+ return '*'
115
+ }
116
+
117
+ function patchPackageJson(appDir: string, options: TelemetryInitOptions): StepResult {
118
+ const file = 'package.json'
119
+ const path = join(appDir, file)
120
+ const raw = readFileSync(path, 'utf8')
121
+ const pkg = JSON.parse(raw) as {
122
+ dependencies?: Record<string, string>
123
+ optionalDependencies?: Record<string, string>
124
+ }
125
+ const version = resolveOpenMercatoVersion(pkg)
126
+ const hasTelemetry = Boolean(pkg.dependencies?.['@open-mercato/telemetry'])
127
+ const hasBullmqOtel = Boolean(pkg.optionalDependencies?.['bullmq-otel'])
128
+ if (hasTelemetry && hasBullmqOtel) {
129
+ return { file, status: 'skipped', detail: '@open-mercato/telemetry already installed' }
130
+ }
131
+
132
+ const deps = { ...(pkg.dependencies ?? {}) }
133
+ if (!hasTelemetry) deps['@open-mercato/telemetry'] = version
134
+ const optDeps = { ...(pkg.optionalDependencies ?? {}) }
135
+ if (!hasBullmqOtel) optDeps['bullmq-otel'] = BULLMQ_OTEL_VERSION
136
+
137
+ const next = {
138
+ ...pkg,
139
+ dependencies: sortRecord(deps),
140
+ optionalDependencies: sortRecord(optDeps),
141
+ }
142
+ if (!options.dryRun) writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`)
143
+ return {
144
+ file,
145
+ status: 'patched',
146
+ detail: `+@open-mercato/telemetry@${version}${hasBullmqOtel ? '' : ` +bullmq-otel@${BULLMQ_OTEL_VERSION} (optional)`} — run \`yarn install\``,
147
+ }
148
+ }
149
+
150
+ function sortRecord(record: Record<string, string>): Record<string, string> {
151
+ return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)))
152
+ }
153
+
154
+ function patchEnvFile(appDir: string, relativePath: string, options: TelemetryInitOptions): StepResult | null {
155
+ const path = join(appDir, relativePath)
156
+ if (!existsSync(path)) return null
157
+ const content = readFileSync(path, 'utf8')
158
+ if (content.includes('TELEMETRY_BACKEND')) {
159
+ return { file: relativePath, status: 'skipped', detail: 'TELEMETRY_* block already present' }
160
+ }
161
+ const next = `${content.replace(/\s*$/, '')}\n${ENV_BLOCK}`
162
+ if (!options.dryRun) writeFileSync(path, next)
163
+ return { file: relativePath, status: 'patched', detail: 'appended commented TELEMETRY_* / OTEL_* block' }
164
+ }
165
+
166
+ function patchInstrumentation(appDir: string, options: TelemetryInitOptions): StepResult {
167
+ const file = 'src/instrumentation.ts'
168
+ const path = join(appDir, file)
169
+ if (!existsSync(path)) {
170
+ if (!options.dryRun) {
171
+ mkdirSync(dirname(path), { recursive: true })
172
+ writeFileSync(path, INSTRUMENTATION_TS)
173
+ }
174
+ return { file, status: 'created', detail: 'Node-runtime-guarded registerTelemetryForNextjs() bootstrap' }
175
+ }
176
+ const content = readFileSync(path, 'utf8')
177
+ if (content.includes('registerTelemetryForNextjs')) {
178
+ if (content.includes('isTelemetryBackendEnabled')) {
179
+ return { file, status: 'skipped', detail: 'telemetry already wired' }
180
+ }
181
+ const migrated =
182
+ `import { isTelemetryBackendEnabled } from '@open-mercato/shared/lib/telemetry/runtime'\n` +
183
+ content.replace(
184
+ `if (process.env.NEXT_RUNTIME === 'nodejs') {`,
185
+ `if (process.env.NEXT_RUNTIME === 'nodejs' && isTelemetryBackendEnabled()) {`,
186
+ )
187
+ if (!options.dryRun) writeFileSync(path, migrated)
188
+ return { file, status: 'patched', detail: 'added the explicit backend import guard' }
189
+ }
190
+ const anchor = content.match(/export\s+async\s+function\s+register\s*\([^)]*\)\s*:\s*Promise<void>\s*\{/)
191
+ if (!anchor || anchor.index === undefined) {
192
+ return {
193
+ file,
194
+ status: 'manual',
195
+ detail: 'register() not found — add the telemetry bootstrap manually',
196
+ manualSnippet: INSTRUMENTATION_TS,
197
+ }
198
+ }
199
+ const insertAt = anchor.index + anchor[0].length
200
+ const block =
201
+ `\n // Initialize telemetry (no-op unless TELEMETRY_BACKEND is set); Node-only.` +
202
+ `\n if (process.env.NEXT_RUNTIME === 'nodejs' && isTelemetryBackendEnabled()) {` +
203
+ `\n const { registerTelemetryForNextjs } = await import('@open-mercato/telemetry/nextjs')` +
204
+ `\n await registerTelemetryForNextjs()` +
205
+ `\n }`
206
+ const importLine = `import { isTelemetryBackendEnabled } from '@open-mercato/shared/lib/telemetry/runtime'\n`
207
+ const withImport = content.includes('isTelemetryBackendEnabled')
208
+ ? content
209
+ : importLine + content
210
+ const shiftedInsertAt = insertAt + (withImport.length - content.length)
211
+ const next = withImport.slice(0, shiftedInsertAt) + block + withImport.slice(shiftedInsertAt)
212
+ if (!options.dryRun) writeFileSync(path, next)
213
+ return { file, status: 'patched', detail: 'inserted registerTelemetryForNextjs() into register()' }
214
+ }
215
+
216
+ async function patchNextConfig(appDir: string, options: TelemetryInitOptions): Promise<StepResult> {
217
+ const file = 'next.config.ts'
218
+ const path = join(appDir, file)
219
+ if (!existsSync(path)) {
220
+ return { file, status: 'manual', detail: 'next.config.ts not found', manualSnippet: nextConfigSnippet() }
221
+ }
222
+ // Use ts-morph to *detect* the real `serverExternalPackages` array literal
223
+ // (robust against a match inside a comment/string), then do the *insertion*
224
+ // via a formatting-preserving text splice so the user's config stays tidy.
225
+ const { Project, SyntaxKind } = await import('ts-morph')
226
+ const project = new Project({ skipAddingFilesFromTsConfig: true, skipFileDependencyResolution: true })
227
+ const sf = project.addSourceFileAtPath(path)
228
+
229
+ const telemetryConfigImport = sf
230
+ .getImportDeclarations()
231
+ .find((decl) => [
232
+ '@open-mercato/telemetry/nextjs',
233
+ '@open-mercato/telemetry/nextjs-config',
234
+ ].includes(decl.getModuleSpecifierValue()))
235
+ const hasImport = Boolean(telemetryConfigImport)
236
+ const hasCanonicalImport =
237
+ telemetryConfigImport?.getModuleSpecifierValue() === '@open-mercato/telemetry/nextjs-config'
238
+
239
+ const arrayProp = sf
240
+ .getDescendantsOfKind(SyntaxKind.PropertyAssignment)
241
+ .find((prop) => prop.getName() === 'serverExternalPackages')
242
+ const arrayInit = arrayProp?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression)
243
+ if (!arrayInit) {
244
+ return {
245
+ file,
246
+ status: 'manual',
247
+ detail: 'serverExternalPackages array not found',
248
+ manualSnippet: nextConfigSnippet(),
249
+ }
250
+ }
251
+ const hasSpread = arrayInit.getElements().some((el) => el.getText().includes('telemetryServerExternalPackages'))
252
+ if (hasCanonicalImport && hasSpread) {
253
+ return { file, status: 'skipped', detail: 'telemetryServerExternalPackages already wired' }
254
+ }
255
+
256
+ let text = readFileSync(path, 'utf8')
257
+ // Splice the array first, using the AST node's byte offsets (formatting-agnostic:
258
+ // handles both single-line and multi-line arrays). Do this before modifying
259
+ // imports, because either an inserted import or the legacy import migration
260
+ // shifts the array offsets captured from the original source.
261
+ if (!hasSpread) {
262
+ const start = arrayInit.getStart()
263
+ const end = arrayInit.getEnd()
264
+ text = text.slice(0, start) + insertSpread(text.slice(start, end)) + text.slice(end)
265
+ }
266
+ text = text.replace(
267
+ "from '@open-mercato/telemetry/nextjs'",
268
+ "from '@open-mercato/telemetry/nextjs-config'",
269
+ )
270
+ if (!hasImport) {
271
+ const importRegex = /^import[^\n]*$/gm
272
+ let lastImport: RegExpExecArray | null = null
273
+ let match: RegExpExecArray | null
274
+ while ((match = importRegex.exec(text)) !== null) lastImport = match
275
+ const insertAt = lastImport ? lastImport.index + lastImport[0].length : 0
276
+ text =
277
+ text.slice(0, insertAt) +
278
+ `\nimport { telemetryServerExternalPackages } from '@open-mercato/telemetry/nextjs-config'` +
279
+ text.slice(insertAt)
280
+ }
281
+ if (!options.dryRun) writeFileSync(path, text)
282
+ return { file, status: 'patched', detail: 'spread telemetryServerExternalPackages into serverExternalPackages' }
283
+ }
284
+
285
+ /** Add `...telemetryServerExternalPackages` as the last element of an array literal, preserving its style. */
286
+ function insertSpread(arrayText: string): string {
287
+ const inner = arrayText.slice(1, -1)
288
+ if (inner.includes('\n')) {
289
+ const elementIndent = inner.match(/\n([ \t]+)\S/)?.[1] ?? ' '
290
+ const closeIndent = arrayText.match(/\n([ \t]*)\]$/)?.[1] ?? ''
291
+ const trimmed = inner.replace(/\s*$/, '')
292
+ const separator = trimmed === '' || trimmed.endsWith(',') ? '' : ','
293
+ return `[${trimmed}${separator}\n${elementIndent}...telemetryServerExternalPackages,\n${closeIndent}]`
294
+ }
295
+ const flat = inner.trim()
296
+ return flat === '' ? '[...telemetryServerExternalPackages]' : `[${flat}, ...telemetryServerExternalPackages]`
297
+ }
298
+
299
+ function nextConfigSnippet(): string {
300
+ return (
301
+ `import { telemetryServerExternalPackages } from '@open-mercato/telemetry/nextjs-config'\n` +
302
+ `// serverExternalPackages: [ ...existing, ...telemetryServerExternalPackages ]`
303
+ )
304
+ }
305
+
306
+ /**
307
+ * Auto-patch the catch-all API dispatcher — but only when it still matches the
308
+ * known scaffold shape (all anchors present, telemetry not yet wired). On any
309
+ * mismatch, print the snippet and mark it manual rather than editing an
310
+ * unrecognized (customized) handler.
311
+ */
312
+ function patchDispatcher(appDir: string, options: TelemetryInitOptions): StepResult {
313
+ const file = 'src/app/api/[...slug]/route.ts'
314
+ const path = join(appDir, file)
315
+ if (!existsSync(path)) {
316
+ return { file, status: 'manual', detail: 'dispatcher not found', manualSnippet: DISPATCHER_SNIPPET }
317
+ }
318
+ let content = readFileSync(path, 'utf8')
319
+ if (
320
+ content.includes("from '@open-mercato/shared/lib/telemetry/runtime'")
321
+ && content.includes('getTelemetryRuntime()?.recordHttpDuration')
322
+ ) {
323
+ return { file, status: 'skipped', detail: 'telemetry already wired' }
324
+ }
325
+ if (
326
+ content.includes("import { reportError } from '@open-mercato/telemetry'")
327
+ && content.includes("import { recordHttpDuration } from '@open-mercato/telemetry/nextjs'")
328
+ ) {
329
+ content = content
330
+ .replace(
331
+ "import { reportError } from '@open-mercato/telemetry'\nimport { recordHttpDuration } from '@open-mercato/telemetry/nextjs'",
332
+ "import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'",
333
+ )
334
+ .replace(/\brecordHttpDuration\(/g, 'getTelemetryRuntime()?.recordHttpDuration(')
335
+ .replace(/\breportError\(/g, 'getTelemetryRuntime()?.reportError(')
336
+ if (!options.dryRun) writeFileSync(path, content)
337
+ return { file, status: 'patched', detail: 'migrated dispatcher to the default-off runtime bridge' }
338
+ }
339
+
340
+ const importAnchor = "import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'"
341
+ const returnMatch = content.match(/^([ \t]*)return finalResponse\s*$/m)
342
+ // The handleRequest catch is the first `} catch (error) {` after the success return.
343
+ const catchRegex = /^([ \t]*)\}\s*catch\s*\(error\)\s*\{[ \t]*$/gm
344
+ const catchMatch = findCatchAfter(content, catchRegex, returnMatch?.index ?? -1)
345
+
346
+ if (!content.includes(importAnchor) || !returnMatch || returnMatch.index === undefined || !catchMatch) {
347
+ return {
348
+ file,
349
+ status: 'manual',
350
+ detail: 'dispatcher shape not recognized — apply the snippet by hand',
351
+ manualSnippet: DISPATCHER_SNIPPET,
352
+ }
353
+ }
354
+
355
+ // 1) imports
356
+ content = content.replace(
357
+ importAnchor,
358
+ `${importAnchor}\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'`,
359
+ )
360
+
361
+ // 2) success-path metric (re-match after the import edit shifted offsets)
362
+ const ret = content.match(/^([ \t]*)return finalResponse\s*$/m)
363
+ if (!ret || ret.index === undefined) {
364
+ return { file, status: 'manual', detail: 'success-path anchor lost', manualSnippet: DISPATCHER_SNIPPET }
365
+ }
366
+ const retIndent = ret[1]
367
+ content =
368
+ content.slice(0, ret.index) +
369
+ `${retIndent}getTelemetryRuntime()?.recordHttpDuration(method, match.route.path, finalResponse.status, startedAt)\n` +
370
+ content.slice(ret.index)
371
+
372
+ // 3) catch-block error funnel + 500 metric
373
+ const catch2 = findCatchAfter(content, /^([ \t]*)\}\s*catch\s*\(error\)\s*\{[ \t]*$/gm, content.indexOf('return finalResponse'))
374
+ if (!catch2) {
375
+ return { file, status: 'manual', detail: 'catch anchor lost', manualSnippet: DISPATCHER_SNIPPET }
376
+ }
377
+ const bodyIndent = `${catch2.indent} `
378
+ const insertAt = catch2.index + catch2.length
379
+ const block =
380
+ `\n${bodyIndent}getTelemetryRuntime()?.reportError(error, {` +
381
+ `\n${bodyIndent} attributes: { 'http.request.method': method, 'http.route': match.route.path, 'http.response.status_code': 500 },` +
382
+ `\n${bodyIndent}})` +
383
+ `\n${bodyIndent}getTelemetryRuntime()?.recordHttpDuration(method, match.route.path, 500, startedAt)`
384
+ content = content.slice(0, insertAt) + block + content.slice(insertAt)
385
+
386
+ if (!options.dryRun) writeFileSync(path, content)
387
+ return { file, status: 'patched', detail: 'wired reportError (5xx) + http.server.request.duration metric' }
388
+ }
389
+
390
+ function findCatchAfter(
391
+ content: string,
392
+ regex: RegExp,
393
+ afterIndex: number,
394
+ ): { index: number; length: number; indent: string } | null {
395
+ regex.lastIndex = 0
396
+ let match: RegExpExecArray | null
397
+ while ((match = regex.exec(content)) !== null) {
398
+ if (match.index > afterIndex) {
399
+ return { index: match.index, length: match[0].length, indent: match[1] }
400
+ }
401
+ }
402
+ return null
403
+ }
404
+
405
+ export async function runTelemetryInit(args: string[]): Promise<number> {
406
+ const appDir = resolve('.')
407
+ const options = parseArgs(args)
408
+
409
+ if (!existsSync(join(appDir, 'src', 'modules.ts'))) {
410
+ console.error('❌ Not an Open Mercato app directory (src/modules.ts not found)')
411
+ return 1
412
+ }
413
+ if (!existsSync(join(appDir, 'package.json'))) {
414
+ console.error('❌ package.json not found')
415
+ return 1
416
+ }
417
+
418
+ console.log('')
419
+ console.log(options.dryRun ? '🔭 Telemetry init (dry run — no files written)\n' : '🔭 Wiring @open-mercato/telemetry into this app\n')
420
+
421
+ const results: StepResult[] = []
422
+ results.push(patchPackageJson(appDir, options))
423
+ const envExample = patchEnvFile(appDir, '.env.example', options)
424
+ if (envExample) results.push(envExample)
425
+ const env = patchEnvFile(appDir, '.env', options)
426
+ if (env) results.push(env)
427
+ results.push(patchInstrumentation(appDir, options))
428
+ results.push(await patchNextConfig(appDir, options))
429
+ results.push(patchDispatcher(appDir, options))
430
+
431
+ const icon: Record<StepStatus, string> = { created: '✍️ ', patched: '✅', skipped: '⏭️ ', manual: '⚠️ ' }
432
+ for (const result of results) {
433
+ console.log(`${icon[result.status]} ${result.file} — ${result.detail}`)
434
+ }
435
+
436
+ const manual = results.filter((result) => result.status === 'manual')
437
+ for (const result of manual) {
438
+ if (!result.manualSnippet) continue
439
+ console.log('')
440
+ console.log(`── manual step for ${result.file} ──`)
441
+ console.log(result.manualSnippet)
442
+ }
443
+
444
+ console.log('')
445
+ const changed = results.some((result) => result.status === 'patched' || result.status === 'created')
446
+ if (options.dryRun) {
447
+ console.log('Dry run complete — re-run without --dry-run to apply.')
448
+ } else if (changed) {
449
+ console.log('Next steps:')
450
+ console.log(' 1. yarn install (resolve @open-mercato/telemetry + the OTEL SDK)')
451
+ console.log(' 2. set TELEMETRY_BACKEND + OTEL_EXPORTER_OTLP_* in .env')
452
+ console.log(' 3. yarn typecheck && yarn build (verify the wiring)')
453
+ } else {
454
+ console.log('Nothing to do — telemetry is already wired.')
455
+ }
456
+ if (manual.length > 0) {
457
+ console.log('')
458
+ console.log(`⚠️ ${manual.length} file(s) need a manual edit (shown above) — the rest were applied automatically.`)
459
+ }
460
+ return 0
461
+ }
package/src/mercato.ts CHANGED
@@ -867,7 +867,10 @@ async function buildAllModules(): Promise<Module[]> {
867
867
  export async function run(argv = process.argv) {
868
868
  const [, , ...parts] = argv
869
869
  const [first, second, ...remaining] = parts
870
- await ensureEnvLoaded({ createIfMissing: first !== 'deploy', quiet: first === 'deploy' })
870
+ await ensureEnvLoaded({
871
+ createIfMissing: first !== 'deploy' && first !== 'telemetry',
872
+ quiet: first === 'deploy' || first === 'telemetry',
873
+ })
871
874
 
872
875
  // Handle init command directly
873
876
  if (first === 'init') {
@@ -1332,6 +1335,20 @@ export async function run(argv = process.argv) {
1332
1335
  return exitCode
1333
1336
  }
1334
1337
 
1338
+ // Handle telemetry command (bootstrap-free) — wires @open-mercato/telemetry
1339
+ // into an app scaffolded before telemetry existed.
1340
+ if (first === 'telemetry') {
1341
+ if (second === 'init') {
1342
+ const { runTelemetryInit } = await import('./lib/telemetry-init')
1343
+ return runTelemetryInit(remaining.filter(Boolean))
1344
+ }
1345
+ console.log('Usage: yarn mercato telemetry init [--dry-run]')
1346
+ console.log(' Wires @open-mercato/telemetry into this app (package.json, .env,')
1347
+ console.log(' instrumentation.ts, next.config.ts, and the API dispatcher).')
1348
+ console.log(' Idempotent and safe to re-run. Use --dry-run to preview changes.')
1349
+ return second && second !== 'help' && second !== '--help' && second !== '-h' ? 1 : 0
1350
+ }
1351
+
1335
1352
  if (first === 'module') {
1336
1353
  try {
1337
1354
  const subcommand = second