@zharp/cli 0.2.0 → 0.3.0

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.
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  // src/cli.ts
5
5
  var import_node_util = require("util");
6
- var import_node_fs8 = require("fs");
6
+ var import_node_fs13 = require("fs");
7
7
 
8
8
  // src/api.ts
9
9
  var import_node_zlib = require("zlib");
@@ -30,7 +30,7 @@ function resolveConnection(options) {
30
30
  function artifactsUrl(connection) {
31
31
  return `${connection.url}/api/v1/applications/${encodeURIComponent(String(connection.app))}/artifacts`;
32
32
  }
33
- var sleep = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
33
+ var sleep = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
34
34
  async function uploadArtifact(connection, artifact, options = {}) {
35
35
  const doFetch = options.fetch ?? fetch;
36
36
  const retries = options.retries ?? 3;
@@ -117,8 +117,8 @@ var consoleLogger = (prefix = "[zharp]") => ({
117
117
  });
118
118
 
119
119
  // src/native.ts
120
- var import_node_fs2 = require("fs");
121
- var import_node_path2 = require("path");
120
+ var import_node_fs4 = require("fs");
121
+ var import_node_path3 = require("path");
122
122
 
123
123
  // src/elf.ts
124
124
  var NT_GNU_BUILD_ID = 3;
@@ -317,7 +317,140 @@ function formatUuid(bytes) {
317
317
  return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
318
318
  }
319
319
 
320
+ // src/swift-names.ts
321
+ var import_node_child_process = require("child_process");
322
+ var import_node_fs2 = require("fs");
323
+ var xcrun = (tool, args, input) => {
324
+ const result = (0, import_node_child_process.spawnSync)("xcrun", [tool, ...args], { input, encoding: "utf8", maxBuffer: 512 * 1024 * 1024 });
325
+ return result.status === 0 && typeof result.stdout === "string" ? result.stdout : null;
326
+ };
327
+ var SWIFT = /\$s[0-9A-Za-z_$]{3,}/g;
328
+ var NOT_CODE = /^(type metadata(?! accessor)|full type metadata|(nominal type|protocol|protocol conformance|associated (type|conformance)|method|property|module|extension|anonymous|reflection metadata|opaque type) descriptor|reflection metadata|protocol (requirements base|witness table)(?! accessor)|value witness table|field offset|enum case for|lazy cache variable|demangling cache variable|flag for loading|metaclass for|class metadata base offset|objc metaclass|type metadata (pattern|completion|instantiation cache)|generic (type|protocol witness table) (instantiation cache|pattern))/;
329
+ function mangledNamesIn(data) {
330
+ return new Set(data.toString("latin1").match(SWIFT) ?? []);
331
+ }
332
+ function swiftNames(files, tool = process.platform === "darwin" ? xcrun : null, read5 = import_node_fs2.readFileSync) {
333
+ if (!tool) return null;
334
+ const symbols = /* @__PURE__ */ new Set();
335
+ for (const file of new Set(files)) {
336
+ for (const name of mangledNamesIn(read5(file))) symbols.add(name);
337
+ }
338
+ if (!symbols.size) return {};
339
+ const mangled = [...symbols];
340
+ const decoded = tool("swift-demangle", ["--simplified", "--compact"], `${mangled.join("\n")}
341
+ `);
342
+ if (decoded === null) return null;
343
+ const lines = decoded.split("\n");
344
+ const out = {};
345
+ mangled.forEach((name, i) => {
346
+ const readable = lines[i]?.trim();
347
+ if (readable && readable !== name && !NOT_CODE.test(readable)) out[name] = readable;
348
+ });
349
+ return out;
350
+ }
351
+
352
+ // src/source-bundle.ts
353
+ var import_node_fs3 = require("fs");
354
+ var import_node_path2 = require("path");
355
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
356
+ "node_modules",
357
+ ".git",
358
+ ".svn",
359
+ ".hg",
360
+ "build",
361
+ ".build",
362
+ ".dart_tool",
363
+ ".pub-cache",
364
+ ".gradle",
365
+ ".idea",
366
+ ".vscode",
367
+ "test",
368
+ "integration_test",
369
+ "Pods",
370
+ "Carthage",
371
+ "DerivedData",
372
+ "xcuserdata",
373
+ ".swiftpm",
374
+ "SourcePackages",
375
+ "vendor",
376
+ ".fvm",
377
+ ".symlinks",
378
+ "ephemeral"
379
+ ]);
380
+ var MAX_FILE_BYTES = 1024 * 1024;
381
+ var MAX_TOTAL_BYTES = 50 * 1024 * 1024;
382
+ var MAX_FILES = 2e4;
383
+ function collectSources(root, extensions, skipDirs = []) {
384
+ const skip = /* @__PURE__ */ new Set([...SKIP_DIRS, ...skipDirs]);
385
+ const wanted = new Set(extensions.map((e) => e.toLowerCase()));
386
+ const out = { root, files: {}, count: 0, bytes: 0, skipped: 0 };
387
+ const visit = (dir) => {
388
+ let entries;
389
+ try {
390
+ entries = (0, import_node_fs3.readdirSync)(dir, { withFileTypes: true });
391
+ } catch {
392
+ return;
393
+ }
394
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
395
+ const full = (0, import_node_path2.join)(dir, entry.name);
396
+ if (entry.isDirectory()) {
397
+ if (!skip.has(entry.name) && !/\.(xcassets|dSYM)$|Tests$/.test(entry.name)) visit(full);
398
+ continue;
399
+ }
400
+ if (!entry.isFile()) continue;
401
+ const dot = entry.name.lastIndexOf(".");
402
+ if (dot < 0 || !wanted.has(entry.name.slice(dot).toLowerCase())) continue;
403
+ const size = (0, import_node_fs3.statSync)(full).size;
404
+ if (size > MAX_FILE_BYTES || out.bytes + size > MAX_TOTAL_BYTES || out.count >= MAX_FILES) {
405
+ out.skipped += 1;
406
+ continue;
407
+ }
408
+ out.files[relativePath(root, full)] = (0, import_node_fs3.readFileSync)(full, "utf8");
409
+ out.count += 1;
410
+ out.bytes += size;
411
+ }
412
+ };
413
+ visit(root);
414
+ return out;
415
+ }
416
+ function sourceBundleArtifacts(sources, buildIds, release2) {
417
+ if (!sources.count) return [];
418
+ const data = Buffer.from(JSON.stringify({ files: sources.files }), "utf8");
419
+ return [...new Set(buildIds)].map((debugId) => ({ kind: "source-bundle", debugId, name: "sources.json", release: release2, data, gzip: true }));
420
+ }
421
+ function projectRoot(from, marker) {
422
+ let dir = (0, import_node_path2.resolve)(from);
423
+ for (; ; ) {
424
+ if (marker(dir)) return dir;
425
+ const parent = (0, import_node_path2.dirname)(dir);
426
+ if (parent === dir) return null;
427
+ dir = parent;
428
+ }
429
+ }
430
+ var FLUTTER_SOURCES = [".dart"];
431
+ var APPLE_SOURCES = [".swift", ".m", ".mm", ".h", ".c", ".cc", ".cpp", ".hpp"];
432
+ var isFlutterRoot = (dir) => (0, import_node_fs3.existsSync)((0, import_node_path2.join)(dir, "pubspec.yaml"));
433
+ var isAppleRoot = (dir) => {
434
+ try {
435
+ return (0, import_node_fs3.existsSync)((0, import_node_path2.join)(dir, "Package.swift")) || (0, import_node_fs3.readdirSync)(dir).some((name) => name.endsWith(".xcodeproj") || name.endsWith(".xcworkspace"));
436
+ } catch {
437
+ return false;
438
+ }
439
+ };
440
+
320
441
  // src/native.ts
442
+ function withSources(kind, buildIds, options, logger) {
443
+ if (options.sources === false || !buildIds.length) return [];
444
+ const root = typeof options.sources === "string" ? (0, import_node_path3.resolve)(options.sources) : kind === "apple" && process.env.SRCROOT ? process.env.SRCROOT : projectRoot(process.cwd(), kind === "flutter" ? isFlutterRoot : isAppleRoot);
445
+ if (!root || !(0, import_node_fs4.existsSync)(root)) {
446
+ logger.info(`Sources: no ${kind === "flutter" ? "Flutter project (pubspec.yaml)" : "Xcode project"} found from ${process.cwd()} \u2014 pass --sources <project folder>, or --no-sources.`);
447
+ return [];
448
+ }
449
+ const sources = collectSources(root, kind === "flutter" ? FLUTTER_SOURCES : APPLE_SOURCES);
450
+ if (!sources.count) return [];
451
+ logger.info(`With the app's sources: ${sources.count} file(s), ${formatBytes(sources.bytes)} from ${root}${sources.skipped ? ` (${sources.skipped} over the size caps left out)` : ""} \u2014 errors show the code of this build. --no-sources to leave them out.`);
452
+ return sourceBundleArtifacts(sources, buildIds, options.release);
453
+ }
321
454
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
322
455
  async function send(connection, artifacts, options) {
323
456
  const logger = options.logger ?? consoleLogger();
@@ -335,46 +468,46 @@ async function send(connection, artifacts, options) {
335
468
  }
336
469
  async function uploadProguard(mappingFile, uuid, connection, options = {}) {
337
470
  if (!UUID.test(uuid)) throw new Error(`--uuid must be a UUID, got "${uuid}".`);
338
- const data = (0, import_node_fs2.readFileSync)(mappingFile);
339
- return send(connection, [{ kind: "proguard", debugId: uuid.toLowerCase(), name: (0, import_node_path2.basename)(mappingFile), release: options.release, data, gzip: true }], options);
471
+ const data = (0, import_node_fs4.readFileSync)(mappingFile);
472
+ return send(connection, [{ kind: "proguard", debugId: uuid.toLowerCase(), name: (0, import_node_path3.basename)(mappingFile), release: options.release, data, gzip: true }], options);
340
473
  }
341
474
  var DART_ARCH = { x86_64: "x64", x86: "ia32" };
342
475
  function findDartSymbols(path, logger = consoleLogger()) {
343
- const files = (0, import_node_fs2.statSync)(path).isDirectory() ? walk((0, import_node_path2.resolve)(path)) : [(0, import_node_path2.resolve)(path)];
476
+ const files = (0, import_node_fs4.statSync)(path).isDirectory() ? walk((0, import_node_path3.resolve)(path)) : [(0, import_node_path3.resolve)(path)];
344
477
  const out = [];
345
478
  for (const file of files) {
346
479
  const named = /\.symbols$/.test(file);
347
- const data = (0, import_node_fs2.readFileSync)(file);
480
+ const data = (0, import_node_fs4.readFileSync)(file);
348
481
  if (!isElf(data)) {
349
- if (named) logger.warn(`Skipped ${(0, import_node_path2.basename)(file)}: not an ELF file.`);
482
+ if (named) logger.warn(`Skipped ${(0, import_node_path3.basename)(file)}: not an ELF file.`);
350
483
  continue;
351
484
  }
352
485
  const elf = readElf(data);
353
486
  if (!elf.buildId) {
354
- logger.warn(`Skipped ${(0, import_node_path2.basename)(file)}: it has no GNU build ID.`);
487
+ logger.warn(`Skipped ${(0, import_node_path3.basename)(file)}: it has no GNU build ID.`);
355
488
  continue;
356
489
  }
357
- const match = /\.([a-z]+)-([a-z0-9_]+)\.symbols$/.exec((0, import_node_path2.basename)(file));
490
+ const match = /\.([a-z]+)-([a-z0-9_]+)\.symbols$/.exec((0, import_node_path3.basename)(file));
358
491
  out.push({ path: file, buildId: elf.buildId, os: match?.[1], arch: match?.[2] ?? (elf.arch && (DART_ARCH[elf.arch] ?? elf.arch)) });
359
492
  }
360
493
  return out;
361
494
  }
362
495
  function findObfuscationMap(symbolsPath) {
363
- const dir = (0, import_node_fs2.statSync)(symbolsPath).isDirectory() ? (0, import_node_path2.resolve)(symbolsPath) : (0, import_node_path2.dirname)((0, import_node_path2.resolve)(symbolsPath));
364
- for (const where of [dir, (0, import_node_path2.dirname)(dir)]) {
496
+ const dir = (0, import_node_fs4.statSync)(symbolsPath).isDirectory() ? (0, import_node_path3.resolve)(symbolsPath) : (0, import_node_path3.dirname)((0, import_node_path3.resolve)(symbolsPath));
497
+ for (const where of [dir, (0, import_node_path3.dirname)(dir)]) {
365
498
  let names;
366
499
  try {
367
- names = (0, import_node_fs2.readdirSync)(where).sort();
500
+ names = (0, import_node_fs4.readdirSync)(where).sort();
368
501
  } catch {
369
502
  continue;
370
503
  }
371
504
  const found = names.find((n) => n === "obfuscation.json") ?? names.find((n) => n.endsWith(".obfuscation.json"));
372
- if (found && (0, import_node_fs2.statSync)((0, import_node_path2.join)(where, found)).isFile()) return (0, import_node_path2.join)(where, found);
505
+ if (found && (0, import_node_fs4.statSync)((0, import_node_path3.join)(where, found)).isFile()) return (0, import_node_path3.join)(where, found);
373
506
  }
374
507
  return void 0;
375
508
  }
376
509
  function readObfuscationMap(file) {
377
- const data = (0, import_node_fs2.readFileSync)(file);
510
+ const data = (0, import_node_fs4.readFileSync)(file);
378
511
  let parsed;
379
512
  try {
380
513
  parsed = JSON.parse(data.toString("utf8"));
@@ -392,32 +525,33 @@ async function uploadDartSymbols(path, connection, options = {}) {
392
525
  const artifacts = files.map((f) => ({
393
526
  kind: "dart-symbols",
394
527
  debugId: f.buildId,
395
- name: (0, import_node_path2.basename)(f.path),
528
+ name: (0, import_node_path3.basename)(f.path),
396
529
  arch: f.arch,
397
530
  release: options.release,
398
- data: (0, import_node_fs2.readFileSync)(f.path),
531
+ data: (0, import_node_fs4.readFileSync)(f.path),
399
532
  gzip: true
400
533
  }));
401
- if (options.obfuscationMap && !(0, import_node_fs2.existsSync)(options.obfuscationMap)) throw new Error(`${options.obfuscationMap} does not exist.`);
534
+ if (options.obfuscationMap && !(0, import_node_fs4.existsSync)(options.obfuscationMap)) throw new Error(`${options.obfuscationMap} does not exist.`);
402
535
  const mapFile = options.obfuscationMap ?? findObfuscationMap(path);
403
536
  if (mapFile) {
404
537
  const data = readObfuscationMap(mapFile);
405
538
  const buildIds = [...new Set(files.map((f) => f.buildId))];
406
- logger.info(`With obfuscation map ${(0, import_node_path2.basename)(mapFile)} for ${buildIds.length} build ID(s)`);
539
+ logger.info(`With obfuscation map ${(0, import_node_path3.basename)(mapFile)} for ${buildIds.length} build ID(s)`);
407
540
  for (const debugId of buildIds) {
408
- artifacts.push({ kind: "dart-obfuscation-map", debugId, name: (0, import_node_path2.basename)(mapFile), release: options.release, data, gzip: true });
541
+ artifacts.push({ kind: "dart-obfuscation-map", debugId, name: (0, import_node_path3.basename)(mapFile), release: options.release, data, gzip: true });
409
542
  }
410
543
  } else {
411
544
  logger.info("No obfuscation map found (build with --extra-gen-snapshot-options=--save-obfuscation-map=build/obfuscation.json, or pass --obfuscation-map): obfuscated names in error messages stay as they are.");
412
545
  }
546
+ artifacts.push(...withSources("flutter", [...new Set(files.map((f) => f.buildId))], options, logger));
413
547
  return send(connection, artifacts, options);
414
548
  }
415
549
  function findDsymImages(path) {
416
- const root = (0, import_node_path2.resolve)(path);
417
- const candidates = (0, import_node_fs2.statSync)(root).isDirectory() ? walk(root).filter((f) => /[\\/]Contents[\\/]Resources[\\/]DWARF[\\/][^\\/]+$/.test(f)) : [root];
550
+ const root = (0, import_node_path3.resolve)(path);
551
+ const candidates = (0, import_node_fs4.statSync)(root).isDirectory() ? walk(root).filter((f) => /[\\/]Contents[\\/]Resources[\\/]DWARF[\\/][^\\/]+$/.test(f)) : [root];
418
552
  const out = [];
419
553
  for (const file of candidates) {
420
- const data = (0, import_node_fs2.readFileSync)(file);
554
+ const data = (0, import_node_fs4.readFileSync)(file);
421
555
  if (!isMachO(data)) continue;
422
556
  for (const image of readMachO(data)) out.push({ path: file, ...image });
423
557
  }
@@ -431,11 +565,11 @@ async function uploadDsyms(path, connection, options = {}) {
431
565
  const cache = /* @__PURE__ */ new Map();
432
566
  const artifacts = images.map((image) => {
433
567
  let data = cache.get(image.path);
434
- if (!data) cache.set(image.path, data = (0, import_node_fs2.readFileSync)(image.path));
568
+ if (!data) cache.set(image.path, data = (0, import_node_fs4.readFileSync)(image.path));
435
569
  return {
436
570
  kind: "dsym",
437
571
  debugId: image.uuid,
438
- name: (0, import_node_path2.basename)(image.path),
572
+ name: (0, import_node_path3.basename)(image.path),
439
573
  arch: image.arch,
440
574
  release: options.release,
441
575
  // One architecture's slice of a universal file is a complete Mach-O file on its own.
@@ -443,17 +577,69 @@ async function uploadDsyms(path, connection, options = {}) {
443
577
  gzip: true
444
578
  };
445
579
  });
580
+ const names = swiftNames(images.map((image) => image.path), options.xcodeTool === void 0 ? void 0 : options.xcodeTool);
581
+ if (names && Object.keys(names).length) {
582
+ const data = Buffer.from(JSON.stringify({ names }), "utf8");
583
+ logger.info(`With readable names for ${Object.keys(names).length} Swift symbol(s)`);
584
+ for (const uuid of new Set(images.map((image) => image.uuid))) {
585
+ artifacts.push({ kind: "symbol-names", debugId: uuid, name: "swift-names.json", release: options.release, data, gzip: true });
586
+ }
587
+ } else if (names === null) {
588
+ logger.info("Swift names stay mangled: run the upload on a Mac with Xcode (xcrun swift-demangle) to send readable ones.");
589
+ }
590
+ artifacts.push(...withSources("apple", [...new Set(images.map((image) => image.uuid))], options, logger));
446
591
  return send(connection, artifacts, options);
447
592
  }
448
593
 
449
- // src/sourcemaps.ts
450
- var import_node_fs4 = require("fs");
594
+ // src/react-native.ts
595
+ var import_node_fs5 = require("fs");
451
596
  var import_node_path4 = require("path");
597
+ var MARKER = /zharp-debug-id:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/;
598
+ function bundleDebugId(bundle) {
599
+ return MARKER.exec(bundle.toString("latin1"))?.[1] ?? null;
600
+ }
601
+ async function uploadReactNative(bundlePath, mapPath, connection, options = {}) {
602
+ const logger = options.logger ?? consoleLogger();
603
+ const id = bundleDebugId((0, import_node_fs5.readFileSync)(bundlePath));
604
+ if (!id) {
605
+ throw new Error(`${bundlePath} has no Zharp debug ID \u2014 add withZharpConfig from @zharp/react-native/metro to metro.config.js, then build again.`);
606
+ }
607
+ const map = JSON.parse((0, import_node_fs5.readFileSync)(mapPath, "utf8"));
608
+ map.debugId = id;
609
+ const withSources2 = Array.isArray(map.sourcesContent) ? map.sourcesContent.filter(Boolean).length : 0;
610
+ const data = Buffer.from(JSON.stringify(map), "utf8");
611
+ const artifact = { kind: "sourcemap", debugId: id, name: (0, import_node_path4.basename)(bundlePath), release: options.release, data, gzip: true };
612
+ if (!options.dryRun) {
613
+ if (!connection) throw new Error("No connection to upload to.");
614
+ await uploadArtifact(connection, artifact, { fetch: options.fetch });
615
+ }
616
+ logger.info(`${options.dryRun ? "Would upload" : "Uploaded"} the source map of ${(0, import_node_path4.basename)(bundlePath)} (${formatBytes(data.length)}, ${withSources2} source file(s) inside) ${id}`);
617
+ return artifact;
618
+ }
619
+ async function uploadReactNativeDir(dir, connection, options = {}) {
620
+ const logger = options.logger ?? consoleLogger();
621
+ const bundles = walk(dir).filter((file) => /\.(hbc|js|bundle|jsbundle)$/.test(file) && (0, import_node_fs5.existsSync)(`${file}.map`));
622
+ if (!bundles.length) throw new Error(`No bundles with source maps in ${dir} \u2014 export with \`npx expo export --source-maps\`.`);
623
+ const out = [];
624
+ for (const bundle of bundles) {
625
+ if (!bundleDebugId((0, import_node_fs5.readFileSync)(bundle))) {
626
+ logger.info(` ${(0, import_node_path4.basename)(bundle)}: no Zharp debug ID (metro.config.js without withZharpConfig?), skipped`);
627
+ continue;
628
+ }
629
+ const artifact = await uploadReactNative(bundle, `${bundle}.map`, connection, options);
630
+ if (artifact) out.push(artifact);
631
+ }
632
+ return out;
633
+ }
634
+
635
+ // src/sourcemaps.ts
636
+ var import_node_fs7 = require("fs");
637
+ var import_node_path6 = require("path");
452
638
 
453
639
  // src/debug-id.ts
454
640
  var import_node_crypto = require("crypto");
455
- var import_node_fs3 = require("fs");
456
- var import_node_path3 = require("path");
641
+ var import_node_fs6 = require("fs");
642
+ var import_node_path5 = require("path");
457
643
  var import_node_url = require("url");
458
644
  var DEBUG_ID_COMMENT = "//# debugId=";
459
645
  var DEBUG_ID_PATTERN = /^\/\/# debugId=([0-9a-fA-F-]{36})\s*$/m;
@@ -535,7 +721,7 @@ function injectMap(mapText, debugId, mapPath) {
535
721
  }
536
722
  var MAX_SOURCE_BYTES = 1e6;
537
723
  function sourcePathCandidates(source, mapPath, sourceRoot = "") {
538
- const mapDir = (0, import_node_path3.dirname)(mapPath);
724
+ const mapDir = (0, import_node_path5.dirname)(mapPath);
539
725
  let stripped = source;
540
726
  let projectRelative = false;
541
727
  if (/^turbopack:\/\/\/\[project\]\//.test(source)) {
@@ -553,15 +739,15 @@ function sourcePathCandidates(source, mapPath, sourceRoot = "") {
553
739
  } else if (/^[a-z][\w+.-]*:\/\//i.test(source)) {
554
740
  return [];
555
741
  }
556
- if ((0, import_node_path3.isAbsolute)(stripped)) return [stripped];
557
- const out = [(0, import_node_path3.resolve)(mapDir, sourceRoot, stripped)];
742
+ if ((0, import_node_path5.isAbsolute)(stripped)) return [stripped];
743
+ const out = [(0, import_node_path5.resolve)(mapDir, sourceRoot, stripped)];
558
744
  if (projectRelative) {
559
745
  for (let dir = mapDir, i = 0; i < 12; i++) {
560
- if ((0, import_node_fs3.existsSync)((0, import_node_path3.join)(dir, "package.json"))) {
561
- out.unshift((0, import_node_path3.join)(dir, stripped));
746
+ if ((0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, "package.json"))) {
747
+ out.unshift((0, import_node_path5.join)(dir, stripped));
562
748
  break;
563
749
  }
564
- const up = (0, import_node_path3.dirname)(dir);
750
+ const up = (0, import_node_path5.dirname)(dir);
565
751
  if (up === dir) break;
566
752
  dir = up;
567
753
  }
@@ -578,9 +764,9 @@ function fillSourcesContent(map, mapPath) {
578
764
  for (const path of sourcePathCandidates(source, mapPath, typeof map.sourceRoot === "string" ? map.sourceRoot : "")) {
579
765
  if (/[\\/]node_modules[\\/]/.test(path)) continue;
580
766
  try {
581
- const stat = (0, import_node_fs3.statSync)(path);
767
+ const stat = (0, import_node_fs6.statSync)(path);
582
768
  if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) continue;
583
- contents[i] = (0, import_node_fs3.readFileSync)(path, "utf8");
769
+ contents[i] = (0, import_node_fs6.readFileSync)(path, "utf8");
584
770
  filled++;
585
771
  break;
586
772
  } catch {
@@ -598,8 +784,8 @@ function fillSourcesContent(map, mapPath) {
598
784
  var JS_FILE = /\.(?:js|mjs|cjs)$/;
599
785
  function mapFor(file, code) {
600
786
  const sibling = `${file}.map`;
601
- if ((0, import_node_fs4.existsSync)(sibling)) return sibling;
602
- const url = sourceMappingUrl(code ?? (0, import_node_fs4.readFileSync)(file, "utf8"));
787
+ if ((0, import_node_fs7.existsSync)(sibling)) return sibling;
788
+ const url = sourceMappingUrl(code ?? (0, import_node_fs7.readFileSync)(file, "utf8"));
603
789
  if (!url || /^[a-z][a-z0-9+.-]*:/i.test(url)) return void 0;
604
790
  let path;
605
791
  try {
@@ -607,16 +793,16 @@ function mapFor(file, code) {
607
793
  } catch {
608
794
  return void 0;
609
795
  }
610
- const full = (0, import_node_path4.isAbsolute)(path) ? path : (0, import_node_path4.resolve)((0, import_node_path4.dirname)(file), path);
611
- return (0, import_node_fs4.existsSync)(full) ? full : void 0;
796
+ const full = (0, import_node_path6.isAbsolute)(path) ? path : (0, import_node_path6.resolve)((0, import_node_path6.dirname)(file), path);
797
+ return (0, import_node_fs7.existsSync)(full) ? full : void 0;
612
798
  }
613
799
  function findSourceFiles(dir, options = {}) {
614
- const root = (0, import_node_path4.resolve)(dir);
800
+ const root = (0, import_node_path6.resolve)(dir);
615
801
  const keep = pathFilter(options.include, options.exclude);
616
- const candidates = options.files ? options.files.map((f) => (0, import_node_path4.resolve)(f)) : walk(root);
802
+ const candidates = options.files ? options.files.map((f) => (0, import_node_path6.resolve)(f)) : walk(root);
617
803
  const out = [];
618
804
  for (const file of candidates) {
619
- if (!JS_FILE.test(file) || !(0, import_node_fs4.existsSync)(file)) continue;
805
+ if (!JS_FILE.test(file) || !(0, import_node_fs7.existsSync)(file)) continue;
620
806
  const name = relativePath(root, file);
621
807
  if (!keep(name)) continue;
622
808
  const map = mapFor(file);
@@ -630,18 +816,18 @@ function injectDirectory(dir, options = {}) {
630
816
  const out = [];
631
817
  const noSourcesContent = [];
632
818
  for (const source of files) {
633
- const code = (0, import_node_fs4.readFileSync)(source.file, "utf8");
819
+ const code = (0, import_node_fs7.readFileSync)(source.file, "utf8");
634
820
  const injected = injectCode(code, { stripSourceMappingUrl: options.stripSourceMappingUrl });
635
821
  let map;
636
822
  try {
637
- map = injectMap((0, import_node_fs4.readFileSync)(source.map, "utf8"), injected.debugId, source.map);
823
+ map = injectMap((0, import_node_fs7.readFileSync)(source.map, "utf8"), injected.debugId, source.map);
638
824
  } catch (error) {
639
825
  logger.warn(`Skipped ${source.name}: ${source.mapName} is not a readable source map (${error.message}).`);
640
826
  continue;
641
827
  }
642
828
  if (!options.dryRun) {
643
- if (injected.changed) (0, import_node_fs4.writeFileSync)(source.file, injected.code);
644
- if (map.changed) (0, import_node_fs4.writeFileSync)(source.map, map.text);
829
+ if (injected.changed) (0, import_node_fs7.writeFileSync)(source.file, injected.code);
830
+ if (map.changed) (0, import_node_fs7.writeFileSync)(source.map, map.text);
645
831
  }
646
832
  if (!map.hasSourcesContent) noSourcesContent.push(source.mapName);
647
833
  const changed = injected.changed || map.changed;
@@ -662,13 +848,13 @@ async function uploadSourcemaps(dir, connection, options = {}) {
662
848
  const result = { files: 0, artifacts: 0, bytes: 0, deleted: [], skipped: [] };
663
849
  const work = [];
664
850
  for (const source of files) {
665
- const code = (0, import_node_fs4.readFileSync)(source.file);
851
+ const code = (0, import_node_fs7.readFileSync)(source.file);
666
852
  const debugId = existingDebugId(code.toString("utf8"));
667
853
  if (!debugId) {
668
854
  result.skipped.push(source.name);
669
855
  continue;
670
856
  }
671
- work.push({ source, debugId, code, map: (0, import_node_fs4.readFileSync)(source.map) });
857
+ work.push({ source, debugId, code, map: (0, import_node_fs7.readFileSync)(source.map) });
672
858
  }
673
859
  if (result.skipped.length) {
674
860
  logger.warn(`${result.skipped.length} file(s) have a source map but no debug ID \u2014 run \`zharp sourcemaps inject\` first: ${result.skipped.slice(0, 3).join(", ")}${result.skipped.length > 3 ? ", \u2026" : ""}`);
@@ -705,13 +891,13 @@ async function uploadSourcemaps(dir, connection, options = {}) {
705
891
  function deleteSourcemaps(files, options = {}) {
706
892
  const deleted = [];
707
893
  for (const source of files) {
708
- if (options.stripSourceMappingUrl && (0, import_node_fs4.existsSync)(source.file)) {
709
- const code = (0, import_node_fs4.readFileSync)(source.file, "utf8");
894
+ if (options.stripSourceMappingUrl && (0, import_node_fs7.existsSync)(source.file)) {
895
+ const code = (0, import_node_fs7.readFileSync)(source.file, "utf8");
710
896
  const stripped = withoutSourceMappingUrl(code);
711
- if (stripped !== code) (0, import_node_fs4.writeFileSync)(source.file, stripped);
897
+ if (stripped !== code) (0, import_node_fs7.writeFileSync)(source.file, stripped);
712
898
  }
713
- if ((0, import_node_fs4.existsSync)(source.map)) {
714
- (0, import_node_fs4.unlinkSync)(source.map);
899
+ if ((0, import_node_fs7.existsSync)(source.map)) {
900
+ (0, import_node_fs7.unlinkSync)(source.map);
715
901
  deleted.push(source.mapName);
716
902
  }
717
903
  }
@@ -719,16 +905,16 @@ function deleteSourcemaps(files, options = {}) {
719
905
  }
720
906
 
721
907
  // src/version.ts
722
- var VERSION = "0.2.0";
908
+ var VERSION = "0.3.0";
723
909
 
724
910
  // src/init/index.ts
725
- var import_node_child_process2 = require("child_process");
726
- var import_node_fs7 = require("fs");
911
+ var import_node_child_process3 = require("child_process");
912
+ var import_node_fs12 = require("fs");
727
913
  var import_promises = require("readline/promises");
728
- var import_node_path7 = require("path");
914
+ var import_node_path11 = require("path");
729
915
 
730
916
  // src/init/connect.ts
731
- var import_node_child_process = require("child_process");
917
+ var import_node_child_process2 = require("child_process");
732
918
  var import_node_os = require("os");
733
919
  var OS_NAMES = { win32: "Windows", darwin: "macOS", linux: "Linux" };
734
920
  function openBrowser(url) {
@@ -736,7 +922,7 @@ function openBrowser(url) {
736
922
  try {
737
923
  const command = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
738
924
  const args = process.platform === "win32" ? ["/c", "start", '""', url.replace(/&/g, "^&")] : [url];
739
- (0, import_node_child_process.spawn)(command, args, { stdio: "ignore", detached: true }).on("error", () => {
925
+ (0, import_node_child_process2.spawn)(command, args, { stdio: "ignore", detached: true }).on("error", () => {
740
926
  }).unref();
741
927
  } catch {
742
928
  }
@@ -777,11 +963,11 @@ async function connect(api, project, hooks) {
777
963
  }
778
964
 
779
965
  // src/init/detect.ts
780
- var import_node_fs5 = require("fs");
781
- var import_node_path5 = require("path");
966
+ var import_node_fs8 = require("fs");
967
+ var import_node_path7 = require("path");
782
968
  var read = (path) => {
783
969
  try {
784
- return (0, import_node_fs5.readFileSync)(path, "utf8");
970
+ return (0, import_node_fs8.readFileSync)(path, "utf8");
785
971
  } catch {
786
972
  return null;
787
973
  }
@@ -791,13 +977,13 @@ function majorOf(range) {
791
977
  return m ? ` ${m[1]}` : "";
792
978
  }
793
979
  function packageManagerOf(dir) {
794
- if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "pnpm-lock.yaml"))) return "pnpm";
795
- if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "yarn.lock"))) return "yarn";
796
- if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "bun.lockb")) || (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "bun.lock"))) return "bun";
980
+ if ((0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "pnpm-lock.yaml"))) return "pnpm";
981
+ if ((0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "yarn.lock"))) return "yarn";
982
+ if ((0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "bun.lockb")) || (0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "bun.lock"))) return "bun";
797
983
  return "npm";
798
984
  }
799
985
  function detect(dir) {
800
- const pkgText = read((0, import_node_path5.join)(dir, "package.json"));
986
+ const pkgText = read((0, import_node_path7.join)(dir, "package.json"));
801
987
  const pkg = pkgText ? (() => {
802
988
  try {
803
989
  return JSON.parse(pkgText);
@@ -806,41 +992,556 @@ function detect(dir) {
806
992
  }
807
993
  })() : null;
808
994
  const deps = { ...pkg?.dependencies ?? {}, ...pkg?.devDependencies ?? {} };
809
- const name = typeof pkg?.name === "string" && pkg.name.replace(/^@[^/]+\//, "") || (0, import_node_path5.basename)(dir);
810
- const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "tsconfig.json")), packageJson: pkg ?? void 0 };
995
+ const name = typeof pkg?.name === "string" && pkg.name.replace(/^@[^/]+\//, "") || (0, import_node_path7.basename)(dir);
996
+ const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || (0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "tsconfig.json")), packageJson: pkg ?? void 0 };
997
+ if (deps.expo) return { ...base, framework: "expo", label: `Expo${majorOf(deps.expo).replace(/^ (\d+)$/, " SDK $1")}`, platform: "react-native" };
998
+ if (deps["react-native"]) return { ...base, framework: "react-native", label: `React Native${/(\d+\.\d+)/.exec(deps["react-native"])?.[1] ? ` ${/(\d+\.\d+)/.exec(deps["react-native"])[1]}` : ""}`, platform: "react-native" };
811
999
  if (deps.next) {
812
- const appDir = (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "src", "app")) ? "src/app" : (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "app")) ? "app" : void 0;
1000
+ const appDir = (0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "src", "app")) ? "src/app" : (0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "app")) ? "app" : void 0;
813
1001
  return { ...base, framework: "nextjs", label: `Next.js${majorOf(deps.next)}`, platform: "browser", appDir };
814
1002
  }
815
1003
  if (deps["@nestjs/core"]) return { ...base, framework: "nestjs", label: `NestJS${majorOf(deps["@nestjs/core"])}`, platform: "node" };
816
1004
  if (deps.vite && deps.react) return { ...base, framework: "vite-react", label: "React (Vite)", platform: "browser" };
817
1005
  if (deps.express) return { ...base, framework: "express", label: `Express${majorOf(deps.express)}`, platform: "node" };
818
- const py = [read((0, import_node_path5.join)(dir, "requirements.txt")), read((0, import_node_path5.join)(dir, "pyproject.toml")), read((0, import_node_path5.join)(dir, "Pipfile"))].filter(Boolean).join("\n").toLowerCase();
1006
+ const py = [read((0, import_node_path7.join)(dir, "requirements.txt")), read((0, import_node_path7.join)(dir, "pyproject.toml")), read((0, import_node_path7.join)(dir, "Pipfile"))].filter(Boolean).join("\n").toLowerCase();
819
1007
  if (py) {
820
- const pyName = (0, import_node_path5.basename)(dir);
1008
+ const pyName = (0, import_node_path7.basename)(dir);
821
1009
  if (/\bdjango\b/.test(py)) return { ...base, name: pyName, framework: "django", label: "Django", platform: "python" };
822
1010
  if (/\bfastapi\b/.test(py)) return { ...base, name: pyName, framework: "fastapi", label: "FastAPI", platform: "python" };
823
1011
  if (/\bflask\b/.test(py)) return { ...base, name: pyName, framework: "flask", label: "Flask", platform: "python" };
824
1012
  }
825
- const composer = read((0, import_node_path5.join)(dir, "composer.json"));
826
- if (composer && /laravel\/framework/.test(composer)) return { ...base, name: (0, import_node_path5.basename)(dir), framework: "laravel", label: "Laravel", platform: "php" };
827
- if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "go.mod"))) return { ...base, name: (0, import_node_path5.basename)(dir), framework: "go", label: "Go", platform: "go" };
1013
+ const composer = read((0, import_node_path7.join)(dir, "composer.json"));
1014
+ if (composer && /laravel\/framework/.test(composer)) return { ...base, name: (0, import_node_path7.basename)(dir), framework: "laravel", label: "Laravel", platform: "php" };
1015
+ const goMod = read((0, import_node_path7.join)(dir, "go.mod"));
1016
+ if (goMod !== null) {
1017
+ const router = /github\.com\/gin-gonic\/gin/.test(goMod) ? " (Gin)" : /github\.com\/labstack\/echo/.test(goMod) ? " (Echo)" : "";
1018
+ const moduleName = /^module\s+(\S+)/m.exec(goMod)?.[1]?.split("/").pop();
1019
+ return { ...base, name: moduleName || (0, import_node_path7.basename)(dir), framework: "go", label: `Go${router}`, platform: "go" };
1020
+ }
828
1021
  if (pkg) return { ...base, framework: "node", label: "Node.js", platform: "node" };
829
1022
  return { ...base, framework: "unknown", label: "an unknown project", platform: "otel" };
830
1023
  }
831
1024
 
832
1025
  // src/init/recipes.ts
833
- var import_node_fs6 = require("fs");
834
- var import_node_path6 = require("path");
835
- var DEFAULT_API = "https://api.zharp.io";
1026
+ var import_node_fs11 = require("fs");
1027
+ var import_node_path10 = require("path");
1028
+
1029
+ // src/init/recipes-more.ts
1030
+ var import_node_fs9 = require("fs");
1031
+ var import_node_path8 = require("path");
836
1032
  var read2 = (dir, path) => {
837
1033
  try {
838
- return (0, import_node_fs6.readFileSync)((0, import_node_path6.join)(dir, path), "utf8");
1034
+ return (0, import_node_fs9.readFileSync)((0, import_node_path8.join)(dir, path), "utf8").replace(/\r\n/g, "\n");
1035
+ } catch {
1036
+ return null;
1037
+ }
1038
+ };
1039
+ var first = (dir, paths) => paths.find((p) => (0, import_node_fs9.existsSync)((0, import_node_path8.join)(dir, p))) ?? null;
1040
+ function emptyPlan(envFile) {
1041
+ return { install: [], devInstall: [], changes: [], manual: [], notes: [], env: { file: envFile ?? "", vars: {} }, commands: [] };
1042
+ }
1043
+ var DEFAULT_API = "https://api.zharp.io";
1044
+ var otlpOf = (api) => {
1045
+ const clean = api.replace(/\/+$/, "");
1046
+ return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;
1047
+ };
1048
+ function findFiles(dir, suffix, depth = 3) {
1049
+ const skip = /^(node_modules|vendor|\.git|\.venv|venv|env|__pycache__|dist|build|target|\.next|site-packages)$/;
1050
+ const out = [];
1051
+ const walk2 = (at, level) => {
1052
+ let entries;
1053
+ try {
1054
+ entries = (0, import_node_fs9.readdirSync)(at, { withFileTypes: true });
1055
+ } catch {
1056
+ return;
1057
+ }
1058
+ for (const e of entries) {
1059
+ if (e.isDirectory()) {
1060
+ if (level < depth && !skip.test(e.name) && !e.name.startsWith(".")) walk2((0, import_node_path8.join)(at, e.name), level + 1);
1061
+ } else if (e.name.endsWith(suffix)) {
1062
+ out.push((0, import_node_path8.relative)(dir, (0, import_node_path8.join)(at, e.name)).replace(/\\/g, "/"));
1063
+ }
1064
+ }
1065
+ };
1066
+ walk2(dir, 0);
1067
+ return out.sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b));
1068
+ }
1069
+ function nodeEntry(project) {
1070
+ const scripts = project.packageJson?.scripts ?? {};
1071
+ for (const name of ["start", "dev", "serve"]) {
1072
+ const m = /(?:^|\s)(?:node|nodemon|tsx|ts-node)(?:\s+--?[\w-]+(?:[= ][^\s]+)?)*\s+([\w./-]+\.(?:c|m)?[jt]s)\b/.exec(scripts[name] ?? "");
1073
+ if (m && (0, import_node_fs9.existsSync)((0, import_node_path8.join)(project.dir, m[1]))) return m[1].replace(/^\.\//, "");
1074
+ }
1075
+ const main2 = project.packageJson?.main;
1076
+ if (typeof main2 === "string" && (0, import_node_fs9.existsSync)((0, import_node_path8.join)(project.dir, main2))) return main2.replace(/^\.\//, "");
1077
+ return first(project.dir, ["server.js", "app.js", "index.js", "src/server.js", "src/app.js", "src/index.js", "src/server.ts", "src/app.ts", "src/index.ts", "server.ts", "index.ts"]);
1078
+ }
1079
+ function express(project, c, api) {
1080
+ const plan = emptyPlan(".env");
1081
+ plan.install = ["@zharp/node"];
1082
+ const entry = nodeEntry(project);
1083
+ const endpoint = otlpOf(api);
1084
+ plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ...endpoint ? { ZHARP_ENDPOINT: endpoint } : {} };
1085
+ plan.notes.push("Set ZHARP_KEY where the app runs in production.");
1086
+ if (!entry) {
1087
+ plan.manual.push({ path: "your entry file", why: "start Zharp before anything else loads", snippet: "require('./instrument'); // or: node --import ./instrument.mjs server.js" });
1088
+ return plan;
1089
+ }
1090
+ const main2 = read2(project.dir, entry) ?? "";
1091
+ const ts = entry.endsWith(".ts");
1092
+ const esm = project.packageJson?.type === "module" || /\.mjs$/.test(entry) || !ts && /^\s*import\s/m.test(main2);
1093
+ const dirOf = entry.includes("/") ? entry.slice(0, entry.lastIndexOf("/") + 1) : "";
1094
+ const instrumentName = ts ? "instrument.ts" : esm ? entry.endsWith(".mjs") ? "instrument.mjs" : "instrument.js" : entry.endsWith(".cjs") ? "instrument.cjs" : "instrument.js";
1095
+ const instrumentPath = `${dirOf}${instrumentName}`;
1096
+ const body = [
1097
+ "// Before anything else: http, express and the database drivers are instrumented as they load.",
1098
+ "try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the key */ }",
1099
+ `Zharp.init({ service: '${c.application.serviceName}' });`,
1100
+ ""
1101
+ ];
1102
+ const content = esm || ts ? ["import { Zharp } from '@zharp/node';", "", ...body].join("\n") : ["const { Zharp } = require('@zharp/node');", "", ...body].join("\n");
1103
+ if (!(0, import_node_fs9.existsSync)((0, import_node_path8.join)(project.dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: "create", content, note: "starts Zharp before the app loads" });
1104
+ if (main2.includes("instrument")) return plan;
1105
+ if (esm && !ts) {
1106
+ const pkgText = read2(project.dir, "package.json");
1107
+ let text = pkgText ?? "";
1108
+ const preload = `--import ./${instrumentPath}`;
1109
+ let changed = false;
1110
+ for (const [name, command] of Object.entries(project.packageJson?.scripts ?? {})) {
1111
+ if (command.includes(preload)) continue;
1112
+ const m = /^(node|nodemon)\s+/.exec(command);
1113
+ if (!m || !command.includes(entry.replace(/^\.\//, ""))) continue;
1114
+ const next = command.replace(/^(node|nodemon)\s+/, `$1 ${preload} `);
1115
+ text = text.replace(`"${name}": ${JSON.stringify(command)}`, `"${name}": ${JSON.stringify(next)}`);
1116
+ changed = true;
1117
+ }
1118
+ if (changed) plan.changes.push({ path: "package.json", kind: "edit", content: text, note: "start scripts preload Zharp (--import)" });
1119
+ plan.manual.push({ path: "your start command", why: "ES modules: wherever the app starts outside these scripts, preload Zharp", snippet: `node ${preload} ${entry}` });
1120
+ return plan;
1121
+ }
1122
+ const line = ts ? "import './instrument';" : "require('./instrument');";
1123
+ plan.changes.push({ path: entry, kind: "edit", content: `${line}
1124
+ ${main2}`, note: "loads it first" });
1125
+ return plan;
1126
+ }
1127
+ function pythonInit(c, api) {
1128
+ const endpoint = otlpOf(api);
1129
+ return [
1130
+ "import zharp",
1131
+ "",
1132
+ "# The app's key can only send data to this app, so it is safe in code.",
1133
+ `zharp.init(key="${c.application.ingestKey}", service="${c.application.serviceName}"${endpoint ? `, endpoint="${api.replace(/\/+$/, "")}/api/v1/otlp"` : ""})`
1134
+ ].join("\n");
1135
+ }
1136
+ function afterPythonImports(text, block) {
1137
+ if (/^\s*import zharp\b/m.test(text)) return null;
1138
+ const lines = text.split("\n");
1139
+ let i = 0;
1140
+ while (i < lines.length && /^\s*(#.*)?$/.test(lines[i])) i++;
1141
+ if (i < lines.length && /^\s*[rubRUB]*("""|''')/.test(lines[i])) {
1142
+ const quote = /("""|''')/.exec(lines[i])[1];
1143
+ const rest = lines[i].slice(lines[i].indexOf(quote) + 3);
1144
+ if (!rest.includes(quote)) {
1145
+ i++;
1146
+ while (i < lines.length && !lines[i].includes(quote)) i++;
1147
+ }
1148
+ i++;
1149
+ }
1150
+ let last = -1;
1151
+ for (let j = i; j < lines.length; j++) {
1152
+ if (/^(import |from \S+ import )/.test(lines[j])) {
1153
+ last = j;
1154
+ if (/\($/.test(lines[j].trim())) while (j < lines.length && !lines[j].includes(")")) last = ++j;
1155
+ } else if (!/^\s*(#.*)?$/.test(lines[j])) break;
1156
+ }
1157
+ const at = last >= 0 ? last + 1 : i;
1158
+ return [...lines.slice(0, at), "", block, "", ...lines.slice(at)].join("\n").replace(/\n{4,}/g, "\n\n\n");
1159
+ }
1160
+ function pythonInstall(project) {
1161
+ const dir = project.dir;
1162
+ const changes = [];
1163
+ const commands = [];
1164
+ const manual = [];
1165
+ const requirements = read2(dir, "requirements.txt");
1166
+ const pyproject = read2(dir, "pyproject.toml") ?? "";
1167
+ if (requirements !== null) {
1168
+ if (!/^zharp\b/im.test(requirements)) changes.push({ path: "requirements.txt", kind: "edit", content: `${requirements.replace(/\s*$/, "\n")}zharp
1169
+ `, note: "adds zharp" });
1170
+ }
1171
+ const venvPython = first(dir, [".venv/Scripts/python.exe", ".venv/bin/python", "venv/Scripts/python.exe", "venv/bin/python"]);
1172
+ if ((0, import_node_fs9.existsSync)((0, import_node_path8.join)(dir, "uv.lock"))) commands.push({ label: "uv add zharp", argv: ["uv", "add", "zharp"] });
1173
+ else if (/\[tool\.poetry\]/.test(pyproject)) commands.push({ label: "poetry add zharp", argv: ["poetry", "add", "zharp"] });
1174
+ else if (venvPython) commands.push({ label: `install zharp into ${venvPython.split("/")[0]}`, argv: [(0, import_node_path8.join)(dir, venvPython), "-m", "pip", "install", "zharp"] });
1175
+ else manual.push({ path: "your Python environment", why: "install the package where the app runs", snippet: "pip install zharp" });
1176
+ return { changes, commands, manual };
1177
+ }
1178
+ function python(project, c, api) {
1179
+ const plan = emptyPlan(null);
1180
+ const installed2 = pythonInstall(project);
1181
+ plan.changes.push(...installed2.changes);
1182
+ plan.commands = installed2.commands;
1183
+ plan.manual.push(...installed2.manual);
1184
+ const block = pythonInit(c, api);
1185
+ let targets = [];
1186
+ if (project.framework === "django") {
1187
+ targets = [first(project.dir, ["manage.py"]), ...findFiles(project.dir, "wsgi.py"), ...findFiles(project.dir, "asgi.py")].filter((p) => !!p);
1188
+ } else {
1189
+ const marker = project.framework === "fastapi" ? /\bFastAPI\(/ : /\bFlask\(\s*__name__/;
1190
+ const files = findFiles(project.dir, ".py").filter((f) => marker.test(read2(project.dir, f) ?? ""));
1191
+ const preferred = files.find((f) => /(^|\/)(main|app|server|wsgi|__init__)\.py$/.test(f)) ?? files[0];
1192
+ if (preferred) targets = [preferred];
1193
+ }
1194
+ for (const path of targets) {
1195
+ const text = read2(project.dir, path);
1196
+ const edited = text !== null ? afterPythonImports(text, block) : null;
1197
+ if (edited) plan.changes.push({ path, kind: "edit", content: edited, note: "starts Zharp" });
1198
+ }
1199
+ if (!targets.length) {
1200
+ const where = project.framework === "django" ? "manage.py, wsgi.py and asgi.py" : project.framework === "fastapi" ? "the file that creates FastAPI()" : "the file that creates Flask(__name__)";
1201
+ plan.manual.push({ path: where, why: "start Zharp at the top, after the imports", snippet: block });
1202
+ }
1203
+ return plan;
1204
+ }
1205
+ function laravel(project, c, api) {
1206
+ const plan = emptyPlan(".env");
1207
+ plan.commands = [{ label: "composer require zharp/zharp", argv: ["composer", "require", "zharp/zharp"] }];
1208
+ const endpoint = otlpOf(api);
1209
+ plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ZHARP_SERVICE: c.application.serviceName, ...endpoint ? { ZHARP_ENDPOINT: endpoint } : {} };
1210
+ plan.notes.push("Laravel finds Zharp by itself (package discovery). Set ZHARP_KEY in production too.");
1211
+ void project;
1212
+ return plan;
1213
+ }
1214
+ var GO_MODULE = "github.com/zharp-io/zharp-go-lib";
1215
+ function editGoMain(text, c, api, routers) {
1216
+ if (text.includes(GO_MODULE)) return null;
1217
+ const block = /^import \(\n([\s\S]*?)^\)/m.exec(text);
1218
+ const mainFn = /^func main\(\) \{\n/m.exec(text);
1219
+ if (!block || !mainFn) return null;
1220
+ const imports = block[1];
1221
+ const stdlib = [];
1222
+ if (!/^\s*"context"$/m.test(imports)) stdlib.push(' "context"');
1223
+ const add = [` zharp "${GO_MODULE}"`];
1224
+ let routerLine = "";
1225
+ let next = text;
1226
+ const gin = routers.gin ? /^(\s*)(\w+) := gin\.(?:Default|New)\(\)\n/m.exec(next) : null;
1227
+ const echo = routers.echo ? /^(\s*)(\w+) := echo\.New\(\)\n/m.exec(next) : null;
1228
+ if (gin) {
1229
+ add.push(` "${GO_MODULE}/zharpgin"`);
1230
+ routerLine = `${gin[1]}${gin[2]}.Use(zharpgin.Middleware())
1231
+ `;
1232
+ next = next.replace(gin[0], gin[0] + routerLine);
1233
+ } else if (echo) {
1234
+ add.push(` "${GO_MODULE}/zharpecho"`);
1235
+ routerLine = `${echo[1]}${echo[2]}.Use(zharpecho.Middleware())
1236
+ `;
1237
+ next = next.replace(echo[0], echo[0] + routerLine);
1238
+ } else {
1239
+ next = next.replace(/http\.ListenAndServe\(([^,]+),\s*(nil|[\w.]+)\)/, (_, addr, handler) => `http.ListenAndServe(${addr}, zharp.Handler(${handler === "nil" ? "http.DefaultServeMux" : handler}))`);
1240
+ }
1241
+ const endpoint = otlpOf(api);
1242
+ const start = [
1243
+ " // The app's key can only send data to this app, so it is safe in code.",
1244
+ ` shutdown := zharp.Init(zharp.Config{Key: "${c.application.ingestKey}", Service: "${c.application.serviceName}"${endpoint ? `, Endpoint: "${api.replace(/\/+$/, "")}/api/v1/otlp"` : ""}})`,
1245
+ " defer shutdown(context.Background())",
1246
+ ""
1247
+ ].join("\n");
1248
+ next = next.replace(block[0], `import (
1249
+ ${groupedImports(imports, stdlib, add)})`);
1250
+ next = next.replace(/^func main\(\) \{\n/m, `func main() {
1251
+ ${start}`);
1252
+ return next;
1253
+ }
1254
+ function groupedImports(body, stdlib, modules) {
1255
+ const groups = body.replace(/\n+$/, "").split(/\n[ \t]*\n/).map((g) => g.split("\n"));
1256
+ const isModule = (line) => /"[^"/]*\.[^"/]*\//.test(line) || /"[^"/]*\.[^"/]*"/.test(line);
1257
+ const std = groups.find((g) => g.some((l) => /"/.test(l)) && !g.some(isModule));
1258
+ const mods = groups.find((g) => g.some(isModule));
1259
+ if (stdlib.length) std ? std.push(...stdlib) : groups.unshift(stdlib);
1260
+ mods ? mods.push(...modules) : groups.push(modules);
1261
+ return `${groups.map((g) => g.join("\n")).join("\n\n")}
1262
+ `;
1263
+ }
1264
+ function go(project, c, api) {
1265
+ const plan = emptyPlan(null);
1266
+ const goMod = read2(project.dir, "go.mod") ?? "";
1267
+ const routers = { gin: /github\.com\/gin-gonic\/gin/.test(goMod), echo: /github\.com\/labstack\/echo/.test(goMod) };
1268
+ plan.commands = [{ label: `go get ${GO_MODULE}`, argv: ["go", "get", `${GO_MODULE}@latest`] }];
1269
+ if (routers.gin) plan.commands.push({ label: "go get \u2026/zharpgin", argv: ["go", "get", `${GO_MODULE}/zharpgin@latest`] });
1270
+ else if (routers.echo) plan.commands.push({ label: "go get \u2026/zharpecho", argv: ["go", "get", `${GO_MODULE}/zharpecho@latest`] });
1271
+ const mainPath = first(project.dir, ["main.go", "cmd/server/main.go", "cmd/api/main.go", "cmd/main.go"]) ?? findFiles(project.dir, "main.go").find((f) => /func main\(\)/.test(read2(project.dir, f) ?? "")) ?? null;
1272
+ const text = mainPath ? read2(project.dir, mainPath) : null;
1273
+ const edited = text ? editGoMain(text, c, api, routers) : null;
1274
+ if (mainPath && edited) {
1275
+ plan.changes.push({ path: mainPath, kind: "edit", content: edited, note: `starts Zharp${routers.gin ? "; traces Gin" : routers.echo ? "; traces Echo" : ""}` });
1276
+ plan.commands.push({ label: "go mod tidy", argv: ["go", "mod", "tidy"] });
1277
+ plan.commands.push({ label: `gofmt -w ${mainPath}`, argv: ["gofmt", "-w", mainPath] });
1278
+ } else if (!text?.includes(GO_MODULE)) {
1279
+ plan.manual.push({ path: mainPath ?? "main.go", why: "start Zharp first in main()", snippet: `shutdown := zharp.Init(zharp.Config{Key: "${c.application.ingestKey}"})
1280
+ defer shutdown(context.Background())` });
1281
+ }
1282
+ return plan;
1283
+ }
1284
+ function morePlanFor(project, c, api) {
1285
+ switch (project.framework) {
1286
+ case "express":
1287
+ return express(project, c, api);
1288
+ case "django":
1289
+ case "fastapi":
1290
+ case "flask":
1291
+ return python(project, c, api);
1292
+ case "laravel":
1293
+ return laravel(project, c, api);
1294
+ case "go":
1295
+ return go(project, c, api);
1296
+ default:
1297
+ return null;
1298
+ }
1299
+ }
1300
+
1301
+ // src/init/recipes-rn.ts
1302
+ var import_node_fs10 = require("fs");
1303
+ var import_node_path9 = require("path");
1304
+ var read3 = (dir, path) => {
1305
+ try {
1306
+ return (0, import_node_fs10.readFileSync)((0, import_node_path9.join)(dir, path), "utf8").replace(/\r\n/g, "\n");
839
1307
  } catch {
840
1308
  return null;
841
1309
  }
842
1310
  };
843
- var first = (dir, paths) => paths.find((p) => (0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, p))) ?? null;
1311
+ var first2 = (dir, paths) => paths.find((p) => (0, import_node_fs10.existsSync)((0, import_node_path9.join)(dir, p))) ?? null;
1312
+ function emptyPlan2() {
1313
+ return { install: [], devInstall: [], changes: [], manual: [], notes: [], env: { file: "", vars: {} }, commands: [] };
1314
+ }
1315
+ function endpointOf(api) {
1316
+ const clean = api.replace(/\/+$/, "");
1317
+ return /^https:\/\/api\.zharp\.io$/.test(clean) ? null : `${clean}/api/v1/otlp`;
1318
+ }
1319
+ var GRADLE_LINE = `apply from: new File(["node", "--print", "require.resolve('@zharp/react-native/package.json')"].execute(null, rootDir).text.trim(), "../zharp.gradle")`;
1320
+ function addGradleLine(text) {
1321
+ if (text.includes("zharp.gradle")) return text;
1322
+ const anchor = /^apply plugin: ["']com\.facebook\.react["'][^\n]*$/m;
1323
+ if (anchor.test(text)) return text.replace(anchor, (line) => `${line}
1324
+ ${GRADLE_LINE}`);
1325
+ return `${text.replace(/\s*$/, "")}
1326
+
1327
+ ${GRADLE_LINE}
1328
+ `;
1329
+ }
1330
+ function wireBundlePhase(script) {
1331
+ if (script.includes("zharp-upload.sh")) return script;
1332
+ const sourceMap = 'export SOURCEMAP_FILE="${SOURCEMAP_FILE:-$DERIVED_FILE_DIR/main.jsbundle.map}"';
1333
+ const lines = script.split("\n");
1334
+ lines.splice(lines[0].trim() === "set -e" ? 1 : 0, 0, sourceMap);
1335
+ const upload = '/bin/bash "$PODS_ROOT/../../node_modules/@zharp/react-native/ios/zharp-upload.sh"';
1336
+ return `${lines.join("\n").replace(/\s*$/, "")}
1337
+ ${upload}
1338
+ `;
1339
+ }
1340
+ function wireXcodeProject(pbxproj) {
1341
+ const phase = /(name = "Bundle React Native code and images";[\s\S]*?shellScript = )("(?:[^"\\]|\\.)*")(;)/.exec(pbxproj);
1342
+ if (!phase) return null;
1343
+ let script;
1344
+ try {
1345
+ script = JSON.parse(phase[2]);
1346
+ } catch {
1347
+ return null;
1348
+ }
1349
+ const wired = wireBundlePhase(script);
1350
+ if (wired === script) return null;
1351
+ return pbxproj.replace(phase[0], `${phase[1]}${JSON.stringify(wired)}${phase[3]}`);
1352
+ }
1353
+ function wrapMetroConfig(text) {
1354
+ if (text.includes("withZharpConfig")) return null;
1355
+ const exportLine = /^module\.exports\s*=\s*([\s\S]+?);?\s*$/m;
1356
+ const m = exportLine.exec(text);
1357
+ if (!m) return null;
1358
+ const require2 = "const { withZharpConfig } = require('@zharp/react-native/metro');";
1359
+ const lines = text.split("\n");
1360
+ let lastRequire = -1;
1361
+ lines.forEach((line, i) => {
1362
+ if (/^\s*const .*=\s*require\(/.test(line)) lastRequire = i;
1363
+ });
1364
+ lines.splice(lastRequire + 1, 0, require2);
1365
+ return lines.join("\n").replace(exportLine, (_, value) => `module.exports = withZharpConfig(${value.trim().replace(/;$/, "")});`);
1366
+ }
1367
+ function initBlock(c, api, typescript) {
1368
+ void typescript;
1369
+ const endpoint = endpointOf(api);
1370
+ return [
1371
+ "// The app's key can only send data to this app, so it is safe in the app.",
1372
+ "Zharp.init({",
1373
+ ` key: '${c.application.ingestKey}',`,
1374
+ ` service: '${c.application.serviceName}',`,
1375
+ ...endpoint ? [` endpoint: '${endpoint}',`] : [],
1376
+ "});"
1377
+ ].join("\n");
1378
+ }
1379
+ function afterImports(text, imports, block) {
1380
+ const lines = text.split("\n");
1381
+ let last = -1;
1382
+ for (let i = 0; i < lines.length; i++) {
1383
+ const line = lines[i].trim();
1384
+ if (/^import\b/.test(line)) {
1385
+ last = i;
1386
+ while (last < lines.length - 1 && !/from\s+['"][^'"]+['"];?\s*$|^import\s+['"][^'"]+['"];?\s*$/.test(lines[last].trim())) last++;
1387
+ i = last;
1388
+ } else if (line && !line.startsWith("//") && !line.startsWith("/*") && !line.startsWith("*") && !line.startsWith("'use") && !line.startsWith('"use')) break;
1389
+ }
1390
+ const missing = imports.filter((i) => !text.includes(i));
1391
+ lines.splice(last + 1, 0, ...missing, ...block ? ["", block] : []);
1392
+ return lines.join("\n");
1393
+ }
1394
+ function editRootLayout(text, c, api, typescript) {
1395
+ if (text.includes("@zharp/react-native")) return null;
1396
+ const fn = /export default function (\w+)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{\n/.exec(text);
1397
+ if (!fn) return null;
1398
+ let out = afterImports(text, ["import { Zharp, useZharpNavigation } from '@zharp/react-native';"], initBlock(c, api, typescript));
1399
+ if (!/import\s*\{[^}]*\buseNavigationContainerRef\b[^}]*\}\s*from\s*['"]expo-router['"]/.test(out)) {
1400
+ const existing = /import\s*\{([^}]*)\}\s*from\s*(['"])expo-router\2;?/.exec(out);
1401
+ out = existing ? out.replace(existing[0], existing[0].replace(`{${existing[1]}}`, `{${existing[1].replace(/\s*$/, "")}, useNavigationContainerRef }`)) : afterImports(out, ["import { useNavigationContainerRef } from 'expo-router';"], "");
1402
+ }
1403
+ const again = /export default function (\w+)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{\n/.exec(out);
1404
+ return out.replace(again[0], `${again[0]} // Each screen the app shows, with the requests it made.
1405
+ useZharpNavigation(useNavigationContainerRef());
1406
+ `);
1407
+ }
1408
+ function gitIgnores(dir, file) {
1409
+ const ignore = read3(dir, ".gitignore") ?? "";
1410
+ const lines = ignore.split("\n").map((l) => l.trim());
1411
+ const name = file.split("/").pop();
1412
+ return lines.some((l) => l === file || l === `/${file}` || l === name || l === `*.${name.split(".").pop()}` || l === ".env*.local" && /^\.env.*\.local$/.test(name) || l === ".xcode.env.local" && name === ".xcode.env.local");
1413
+ }
1414
+ function metroChange(project, plan, expo2) {
1415
+ const dir = project.dir;
1416
+ const path = first2(dir, ["metro.config.js", "metro.config.cjs"]);
1417
+ if (!path) {
1418
+ if (expo2) {
1419
+ plan.changes.push({
1420
+ path: "metro.config.js",
1421
+ kind: "create",
1422
+ note: "Expo\u2019s config, with release bundles stamped for readable errors",
1423
+ content: [
1424
+ "const { getDefaultConfig } = require('expo/metro-config');",
1425
+ "const { withZharpConfig } = require('@zharp/react-native/metro');",
1426
+ "",
1427
+ "module.exports = withZharpConfig(getDefaultConfig(__dirname));",
1428
+ ""
1429
+ ].join("\n")
1430
+ });
1431
+ } else {
1432
+ plan.manual.push({ path: "metro.config.js", why: "wrap its config so release errors are readable", snippet: "const { withZharpConfig } = require('@zharp/react-native/metro');\nmodule.exports = withZharpConfig(config);" });
1433
+ }
1434
+ return;
1435
+ }
1436
+ const text = read3(dir, path);
1437
+ const wrapped = wrapMetroConfig(text);
1438
+ if (wrapped) plan.changes.push({ path, kind: "edit", content: wrapped, note: "release bundles stamped for readable errors" });
1439
+ else if (!text.includes("withZharpConfig")) plan.manual.push({ path, why: "wrap what it exports so release errors are readable", snippet: "const { withZharpConfig } = require('@zharp/react-native/metro');\nmodule.exports = withZharpConfig(/* your config */);" });
1440
+ }
1441
+ function expo(project, c, api) {
1442
+ const plan = emptyPlan2();
1443
+ const dir = project.dir;
1444
+ plan.install = ["@zharp/react-native"];
1445
+ metroChange(project, plan, true);
1446
+ const appJson = read3(dir, "app.json");
1447
+ if (appJson && !first2(dir, ["app.config.js", "app.config.ts"])) {
1448
+ try {
1449
+ const config = JSON.parse(appJson);
1450
+ const root = config.expo ?? config;
1451
+ const plugins = Array.isArray(root.plugins) ? root.plugins : [];
1452
+ if (!plugins.some((p) => (Array.isArray(p) ? p[0] : p) === "@zharp/react-native")) {
1453
+ root.plugins = [...plugins, "@zharp/react-native"];
1454
+ plan.changes.push({ path: "app.json", kind: "edit", content: `${JSON.stringify(config, null, 2)}
1455
+ `, note: "the config plugin: builds upload their source maps" });
1456
+ }
1457
+ } catch {
1458
+ plan.manual.push({ path: "app.json", why: "add the config plugin", snippet: '"plugins": ["@zharp/react-native"]' });
1459
+ }
1460
+ } else {
1461
+ plan.manual.push({ path: "app.config", why: "add the config plugin", snippet: "plugins: ['@zharp/react-native']" });
1462
+ }
1463
+ const layout = first2(dir, ["app/_layout.tsx", "app/_layout.jsx", "app/_layout.js", "src/app/_layout.tsx", "src/app/_layout.jsx"]);
1464
+ const entry = (() => {
1465
+ const main2 = project.packageJson?.main;
1466
+ if (typeof main2 === "string" && !main2.includes("expo-router") && (0, import_node_fs10.existsSync)((0, import_node_path9.join)(dir, main2))) return main2;
1467
+ return first2(dir, ["index.ts", "index.tsx", "index.js", "App.tsx", "App.js"]);
1468
+ })();
1469
+ if (layout) {
1470
+ const edited = editRootLayout(read3(dir, layout), c, api, project.typescript);
1471
+ if (edited) plan.changes.push({ path: layout, kind: "edit", content: edited, note: "starts Zharp; screens from Expo Router" });
1472
+ } else if (entry) {
1473
+ const text = read3(dir, entry);
1474
+ if (!text.includes("@zharp/react-native")) {
1475
+ plan.changes.push({ path: entry, kind: "edit", content: afterImports(text, ["import { Zharp } from '@zharp/react-native';"], initBlock(c, api, project.typescript)), note: "starts Zharp" });
1476
+ }
1477
+ } else {
1478
+ plan.manual.push({ path: "your entry file", why: "start Zharp before the app renders", snippet: `import { Zharp } from '@zharp/react-native';
1479
+
1480
+ ${initBlock(c, api, project.typescript)}` });
1481
+ }
1482
+ plan.env = { file: ".env.local", vars: { ZHARP_AUTH_TOKEN: c.uploadKey, ZHARP_APP: String(c.application.id), ...endpointOf(api) ? { ZHARP_URL: api.replace(/\/+$/, "") } : {} } };
1483
+ plan.notes.push(`EAS Build: add the upload key as secrets \u2014 eas env:create --name ZHARP_AUTH_TOKEN --value <the key in .env.local> --visibility secret, and ZHARP_APP=${c.application.id}.`);
1484
+ plan.notes.push("EAS Update: after eas update (or npx expo export --source-maps), upload with npx zharp react-native upload --dir dist.");
1485
+ return plan;
1486
+ }
1487
+ function reactNative(project, c, api) {
1488
+ const plan = emptyPlan2();
1489
+ const dir = project.dir;
1490
+ plan.install = ["@zharp/react-native"];
1491
+ metroChange(project, plan, false);
1492
+ const entry = first2(dir, ["index.js", "index.ts", "index.tsx"]);
1493
+ if (entry) {
1494
+ const text = read3(dir, entry);
1495
+ if (!text.includes("@zharp/react-native")) {
1496
+ plan.changes.push({ path: entry, kind: "edit", content: afterImports(text, ["import { Zharp } from '@zharp/react-native';"], initBlock(c, api, project.typescript)), note: "starts Zharp, before the app registers" });
1497
+ }
1498
+ }
1499
+ plan.notes.push("Screens: useZharpNavigation(navigationRef) next to your NavigationContainer (React Navigation).");
1500
+ const gradle = read3(dir, "android/app/build.gradle");
1501
+ if (gradle !== null) {
1502
+ const edited = addGradleLine(gradle);
1503
+ if (edited !== gradle) plan.changes.push({ path: "android/app/build.gradle", kind: "edit", content: edited, note: "release builds upload their source map" });
1504
+ const local = read3(dir, "android/local.properties") ?? "";
1505
+ if (!/^zharp\.authToken=/m.test(local)) {
1506
+ const lines = [`zharp.authToken=${c.uploadKey}`, `zharp.appId=${c.application.id}`];
1507
+ plan.changes.push({ path: "android/local.properties", kind: local ? "edit" : "create", content: `${local.replace(/\s*$/, local ? "\n" : "")}${lines.join("\n")}
1508
+ `, note: "the upload key (git ignores this file)" });
1509
+ if (!gitIgnores(dir, "android/local.properties") && !gitIgnores((0, import_node_path9.join)(dir, "android"), "local.properties")) plan.notes.push("android/local.properties holds the upload key: make sure git ignores it.");
1510
+ }
1511
+ }
1512
+ const ios = (0, import_node_fs10.existsSync)((0, import_node_path9.join)(dir, "ios")) ? (0, import_node_fs10.readdirSync)((0, import_node_path9.join)(dir, "ios")).find((name) => name.endsWith(".xcodeproj")) : void 0;
1513
+ if (ios) {
1514
+ const path = `ios/${ios}/project.pbxproj`;
1515
+ const text = read3(dir, path);
1516
+ const wired = text ? wireXcodeProject(text) : null;
1517
+ if (wired) plan.changes.push({ path, kind: "edit", content: wired, note: "the bundle phase writes and uploads its source map" });
1518
+ const envLocal = read3(dir, "ios/.xcode.env.local") ?? "";
1519
+ if (!/ZHARP_AUTH_TOKEN=/.test(envLocal)) {
1520
+ const lines = [`export ZHARP_AUTH_TOKEN=${c.uploadKey}`, `export ZHARP_APP=${c.application.id}`, ...endpointOf(api) ? [`export ZHARP_URL=${api.replace(/\/+$/, "")}`] : []];
1521
+ plan.changes.push({ path: "ios/.xcode.env.local", kind: envLocal ? "edit" : "create", content: `${envLocal.replace(/\s*$/, envLocal ? "\n" : "")}${lines.join("\n")}
1522
+ `, note: "the upload key (git ignores this file)" });
1523
+ }
1524
+ }
1525
+ if (endpointOf(api) && gradle !== null) plan.notes.push(`Android builds upload to ${api}: set ZHARP_URL=${api.replace(/\/+$/, "")} when building.`);
1526
+ plan.notes.push("CI: set ZHARP_AUTH_TOKEN (the upload key) and ZHARP_APP for release builds.");
1527
+ return plan;
1528
+ }
1529
+ function reactNativePlanFor(project, c, api) {
1530
+ if (project.framework === "expo") return expo(project, c, api);
1531
+ if (project.framework === "react-native") return reactNative(project, c, api);
1532
+ return null;
1533
+ }
1534
+
1535
+ // src/init/recipes.ts
1536
+ var DEFAULT_API2 = "https://api.zharp.io";
1537
+ var read4 = (dir, path) => {
1538
+ try {
1539
+ return (0, import_node_fs11.readFileSync)((0, import_node_path10.join)(dir, path), "utf8").replace(/\r\n/g, "\n");
1540
+ } catch {
1541
+ return null;
1542
+ }
1543
+ };
1544
+ var first3 = (dir, paths) => paths.find((p) => (0, import_node_fs11.existsSync)((0, import_node_path10.join)(dir, p))) ?? null;
844
1545
  var mentionsZharp = (text) => !!text && /@zharp\//.test(text);
845
1546
  function styled(text, line) {
846
1547
  const imports = [...text.matchAll(/^import .*$/gm)].map((m) => m[0].trimEnd());
@@ -849,9 +1550,9 @@ function styled(text, line) {
849
1550
  const quoted = double ? line.replace(/'([^'"]*)'/g, '"$1"') : line;
850
1551
  return bare ? quoted.replace(/;$/, "") : quoted;
851
1552
  }
852
- function endpointOf(api) {
1553
+ function endpointOf2(api) {
853
1554
  const clean = api.replace(/\/+$/, "");
854
- return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;
1555
+ return clean === DEFAULT_API2 ? null : `${clean}/api/v1/otlp`;
855
1556
  }
856
1557
  function wrapNextConfig(text, appId, esm) {
857
1558
  if (/withZharp/.test(text)) return null;
@@ -898,7 +1599,7 @@ function nextjs(project, c, api) {
898
1599
  const dir = project.dir;
899
1600
  const ts = project.typescript;
900
1601
  const plan = { install: ["@zharp/browser", "@zharp/node"], devInstall: ["@zharp/nextjs"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
901
- const endpoint = endpointOf(api);
1602
+ const endpoint = endpointOf2(api);
902
1603
  const instrumentationPath = `${project.appDir?.startsWith("src/") ? "src/" : ""}instrumentation.${ts ? "ts" : "js"}`;
903
1604
  const instrumentation = [
904
1605
  "export async function register() {",
@@ -917,17 +1618,17 @@ function nextjs(project, c, api) {
917
1618
  "}",
918
1619
  ""
919
1620
  ].join("\n");
920
- const existingInstrumentation = first(dir, ["instrumentation.ts", "instrumentation.js", "src/instrumentation.ts", "src/instrumentation.js"]);
1621
+ const existingInstrumentation = first3(dir, ["instrumentation.ts", "instrumentation.js", "src/instrumentation.ts", "src/instrumentation.js"]);
921
1622
  if (!existingInstrumentation) plan.changes.push({ path: instrumentationPath, kind: "create", content: instrumentation, note: "starts Zharp on the server" });
922
- else if (!mentionsZharp(read2(dir, existingInstrumentation))) plan.manual.push({ path: existingInstrumentation, why: "it already exists \u2014 add Zharp to it", snippet: instrumentation });
923
- const configPath = first(dir, ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"]);
1623
+ else if (!mentionsZharp(read4(dir, existingInstrumentation))) plan.manual.push({ path: existingInstrumentation, why: "it already exists \u2014 add Zharp to it", snippet: instrumentation });
1624
+ const configPath = first3(dir, ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"]);
924
1625
  if (!configPath) {
925
1626
  plan.changes.push({ path: ts ? "next.config.ts" : "next.config.mjs", kind: "create", content: `import { withZharp } from '@zharp/nextjs';
926
1627
 
927
1628
  export default withZharp({}, { app: ${c.application.id} });
928
1629
  `, note: "source maps uploaded on build" });
929
1630
  } else {
930
- const text = read2(dir, configPath) ?? "";
1631
+ const text = read4(dir, configPath) ?? "";
931
1632
  const esm = /\.(ts|mjs)$/.test(configPath) || /^\s*(import|export)\s/m.test(text);
932
1633
  const wrapped = mentionsZharp(text) ? null : wrapNextConfig(text, c.application.id, esm);
933
1634
  if (wrapped) plan.changes.push({ path: configPath, kind: "edit", content: wrapped, note: "wrapped with withZharp" });
@@ -952,9 +1653,9 @@ export default withZharp(nextConfig, { app: ${c.application.id} });` });
952
1653
  "}",
953
1654
  ""
954
1655
  ].join("\n");
955
- if (!(0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, clientPath))) plan.changes.push({ path: clientPath, kind: "create", content: client, note: `starts Zharp in the browser` });
956
- const layoutPath = first(dir, [`${project.appDir}/layout.tsx`, `${project.appDir}/layout.jsx`, `${project.appDir}/layout.js`]);
957
- const layout = layoutPath ? read2(dir, layoutPath) : null;
1656
+ if (!(0, import_node_fs11.existsSync)((0, import_node_path10.join)(dir, clientPath))) plan.changes.push({ path: clientPath, kind: "create", content: client, note: `starts Zharp in the browser` });
1657
+ const layoutPath = first3(dir, [`${project.appDir}/layout.tsx`, `${project.appDir}/layout.jsx`, `${project.appDir}/layout.js`]);
1658
+ const layout = layoutPath ? read4(dir, layoutPath) : null;
958
1659
  const edited = layout ? addToLayout(layout, "./zharp-client") : null;
959
1660
  if (layoutPath && edited) plan.changes.push({ path: layoutPath, kind: "edit", content: edited, note: "renders <ZharpClient />" });
960
1661
  else if (layoutPath && !/ZharpClient/.test(layout ?? "")) plan.manual.push({ path: layoutPath, why: "add the component inside <body>", snippet: "import { ZharpClient } from './zharp-client';\n\u2026\n<body>\n <ZharpClient />" });
@@ -1027,17 +1728,17 @@ ${init}${next.slice(end).replace(/^\n+/, "\n")}`;
1027
1728
  }
1028
1729
  function viteReact(project, c, api) {
1029
1730
  const dir = project.dir;
1030
- const endpoint = endpointOf(api);
1731
+ const endpoint = endpointOf2(api);
1031
1732
  const plan = { install: ["@zharp/browser"], devInstall: ["@zharp/vite-plugin"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
1032
- const configPath = first(dir, ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]);
1033
- const config = configPath ? read2(dir, configPath) : null;
1733
+ const configPath = first3(dir, ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]);
1734
+ const config = configPath ? read4(dir, configPath) : null;
1034
1735
  const editedConfig = config ? addVitePlugin(config, c.application.id) : null;
1035
1736
  if (configPath && editedConfig) plan.changes.push({ path: configPath, kind: "edit", content: editedConfig, note: "source maps uploaded on build" });
1036
1737
  else if (!mentionsZharp(config)) plan.manual.push({ path: configPath ?? "vite.config.ts", why: "add the plugin to plugins", snippet: `import { zharp } from '@zharp/vite-plugin';
1037
1738
  \u2026
1038
1739
  plugins: [react(), zharp({ app: ${c.application.id} })]` });
1039
- const mainPath = first(dir, ["src/main.tsx", "src/main.jsx", "src/main.ts", "src/main.js", "src/index.tsx", "src/index.jsx"]);
1040
- const main2 = mainPath ? read2(dir, mainPath) : null;
1740
+ const mainPath = first3(dir, ["src/main.tsx", "src/main.jsx", "src/main.ts", "src/main.js", "src/index.tsx", "src/index.jsx"]);
1741
+ const main2 = mainPath ? read4(dir, mainPath) : null;
1041
1742
  const editedMain = main2 ? addToViteMain(main2, c.application.serviceName, !!endpoint) : null;
1042
1743
  if (mainPath && editedMain) plan.changes.push({ path: mainPath, kind: "edit", content: editedMain, note: "starts Zharp; React errors with their component stack" });
1043
1744
  else if (!mentionsZharp(main2)) plan.manual.push({ path: mainPath ?? "src/main.tsx", why: "start Zharp before React renders", snippet: "import { Zharp } from '@zharp/browser';\n\nZharp.init({ key: import.meta.env.VITE_ZHARP_KEY });\n\ncreateRoot(el, { onUncaughtError: Zharp.reactErrorHandler(), onCaughtError: Zharp.reactErrorHandler() })" });
@@ -1051,7 +1752,7 @@ plugins: [react(), zharp({ app: ${c.application.id} })]` });
1051
1752
  }
1052
1753
  function nestjs(project, c, api) {
1053
1754
  const dir = project.dir;
1054
- const endpoint = endpointOf(api);
1755
+ const endpoint = endpointOf2(api);
1055
1756
  const plan = { install: ["@zharp/node"], devInstall: [], changes: [], manual: [], notes: [], env: { file: ".env", vars: {} } };
1056
1757
  const ext = project.typescript ? "ts" : "js";
1057
1758
  const instrumentPath = `src/instrument.${ext}`;
@@ -1063,12 +1764,12 @@ function nestjs(project, c, api) {
1063
1764
  `Zharp.init({ service: '${c.application.serviceName}' });`,
1064
1765
  ""
1065
1766
  ].join("\n");
1066
- if (!(0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: "create", content: instrument, note: "starts Zharp before the app loads" });
1067
- const mainPath = first(dir, [`src/main.${ext}`]);
1068
- const main2 = mainPath ? read2(dir, mainPath) : null;
1767
+ if (!(0, import_node_fs11.existsSync)((0, import_node_path10.join)(dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: "create", content: instrument, note: "starts Zharp before the app loads" });
1768
+ const mainPath = first3(dir, [`src/main.${ext}`]);
1769
+ const main2 = mainPath ? read4(dir, mainPath) : null;
1069
1770
  const esm = project.packageJson?.type === "module" || /from '\.{1,2}\/[^']+\.js'/.test(main2 ?? "");
1070
1771
  if (esm) {
1071
- const pkgText = read2(dir, "package.json");
1772
+ const pkgText = read4(dir, "package.json");
1072
1773
  const scripts = { ...project.packageJson?.scripts ?? {} };
1073
1774
  const preload = "--import ./dist/instrument.js";
1074
1775
  let changed = false;
@@ -1104,6 +1805,17 @@ ${main2}`, note: "loads it first" });
1104
1805
  return plan;
1105
1806
  }
1106
1807
  function planFor(project, c, api) {
1808
+ const plan = basePlanFor(project, c, api);
1809
+ for (const ch of plan?.changes ?? []) {
1810
+ if (ch.kind !== "edit") continue;
1811
+ try {
1812
+ if ((0, import_node_fs11.readFileSync)((0, import_node_path10.join)(project.dir, ch.path), "utf8").includes("\r\n")) ch.content = ch.content.replace(/\r?\n/g, "\r\n");
1813
+ } catch {
1814
+ }
1815
+ }
1816
+ return plan;
1817
+ }
1818
+ function basePlanFor(project, c, api) {
1107
1819
  switch (project.framework) {
1108
1820
  case "nextjs":
1109
1821
  return nextjs(project, c, api);
@@ -1112,7 +1824,7 @@ function planFor(project, c, api) {
1112
1824
  case "nestjs":
1113
1825
  return nestjs(project, c, api);
1114
1826
  default:
1115
- return null;
1827
+ return reactNativePlanFor(project, c, api) ?? morePlanFor(project, c, api);
1116
1828
  }
1117
1829
  }
1118
1830
  var GUIDES = {
@@ -1149,7 +1861,7 @@ function mergeEnv(existing, vars) {
1149
1861
  const added = Object.entries(vars).filter(([k]) => !seen.has(k));
1150
1862
  if (added.length) {
1151
1863
  if (out.length) out.push("");
1152
- out.push("# Zharp (npx zharp init)");
1864
+ out.push("# Zharp (npm init zharp@latest)");
1153
1865
  for (const [k, v] of added) out.push(`${k}=${v}`);
1154
1866
  }
1155
1867
  return `${out.join("\n")}
@@ -1159,7 +1871,7 @@ function ignoredByGit(gitignore, file) {
1159
1871
  return gitignore.split(/\r?\n/).map((l) => l.trim()).some((l) => l === file || l === `/${file}` || l === ".env*" || l === ".env*.local" && file.endsWith(".local") || l === "*.local" && file.endsWith(".local") || l === ".env.*" && file !== ".env");
1160
1872
  }
1161
1873
  function installCommand(project, packages, dev, tarballs) {
1162
- const specs = tarballs ? packages.map((p) => (0, import_node_path7.join)(tarballs, `${p.replace("@", "").replace("/", "-")}.tgz`)) : packages;
1874
+ const specs = tarballs ? packages.map((p) => (0, import_node_path11.join)(tarballs, `${p.replace("@", "").replace("/", "-")}.tgz`)) : packages;
1163
1875
  switch (project.packageManager) {
1164
1876
  case "pnpm":
1165
1877
  return ["pnpm", ["add", ...dev ? ["-D"] : [], ...specs]];
@@ -1171,6 +1883,10 @@ function installCommand(project, packages, dev, tarballs) {
1171
1883
  return ["npm", ["install", ...dev ? ["--save-dev"] : [], ...specs]];
1172
1884
  }
1173
1885
  }
1886
+ function installed(command) {
1887
+ const found = process.platform === "win32" ? (0, import_node_child_process3.spawnSync)("where", [command], { stdio: "ignore" }) : (0, import_node_child_process3.spawnSync)("sh", ["-c", 'command -v "$0"', command], { stdio: "ignore" });
1888
+ return found.status === 0;
1889
+ }
1174
1890
  async function ask(question) {
1175
1891
  const rl = (0, import_promises.createInterface)({ input: process.stdin, output: process.stdout });
1176
1892
  try {
@@ -1190,11 +1906,11 @@ async function sendTestError(api, c) {
1190
1906
  timeUnixNano: now,
1191
1907
  severityNumber: 17,
1192
1908
  severityText: "ERROR",
1193
- body: { stringValue: "ZharpSetupTest: Zharp is connected \u2014 this is the test error npx zharp init sent" },
1909
+ body: { stringValue: "ZharpSetupTest: Zharp is connected \u2014 this is the test error npm init zharp@latest sent" },
1194
1910
  attributes: [
1195
1911
  attr("exception.type", "ZharpSetupTest"),
1196
- attr("exception.message", "Zharp is connected \u2014 this is the test error npx zharp init sent"),
1197
- attr("exception.stacktrace", "ZharpSetupTest: Zharp is connected \u2014 this is the test error npx zharp init sent\n at zharp init"),
1912
+ attr("exception.message", "Zharp is connected \u2014 this is the test error npm init zharp@latest sent"),
1913
+ attr("exception.stacktrace", "ZharpSetupTest: Zharp is connected \u2014 this is the test error npm init zharp@latest sent\n at zharp init"),
1198
1914
  attr("zharp.handled", "true")
1199
1915
  ]
1200
1916
  }]
@@ -1216,14 +1932,15 @@ function showPlan(plan, c) {
1216
1932
  say(`${green("\u25C6")} ${bold("These changes will be made:")}`);
1217
1933
  const deps = [...plan.install, ...plan.devInstall];
1218
1934
  if (deps.length) say(`${bar} ${green("+")} install ${deps.join(" ")}`);
1935
+ for (const cmd of plan.commands ?? []) say(`${bar} ${green("+")} ${cmd.label}`);
1219
1936
  for (const ch of plan.changes) say(`${bar} ${ch.kind === "create" ? green("+") : yellow("~")} ${bold(ch.path)} ${dim(ch.kind === "create" ? `(new) ${ch.note}` : ch.note)}`);
1220
- say(`${bar} ${green("+")} ${bold(plan.env.file)} ${dim(Object.keys(plan.env.vars).join(", "))}`);
1937
+ if (plan.env.file) say(`${bar} ${green("+")} ${bold(plan.env.file)} ${dim(Object.keys(plan.env.vars).join(", "))}`);
1221
1938
  for (const m of plan.manual) say(`${bar} ${yellow("!")} ${m.path}: ${dim(`left as it is \u2014 ${m.why}`)}`);
1222
1939
  void c;
1223
1940
  }
1224
1941
  async function runInit(options) {
1225
- const dir = (0, import_node_path7.resolve)(options.dir ?? process.cwd());
1226
- const api = (options.url ?? process.env.ZHARP_URL ?? DEFAULT_API).replace(/\/+$/, "");
1942
+ const dir = (0, import_node_path11.resolve)(options.dir ?? process.cwd());
1943
+ const api = (options.url ?? process.env.ZHARP_URL ?? DEFAULT_API2).replace(/\/+$/, "");
1227
1944
  const project = detect(dir);
1228
1945
  say();
1229
1946
  say(`${green("\u25C6")} ${bold("Zharp setup")}`);
@@ -1280,30 +1997,45 @@ ${bold(`\u2500\u2500 ${ch.path} ${ch.kind === "create" ? "(new)" : "(edited)"}`)
1280
1997
  }
1281
1998
  }
1282
1999
  for (const ch of plan.changes) {
1283
- const path = (0, import_node_path7.join)(dir, ch.path);
1284
- (0, import_node_fs7.mkdirSync)((0, import_node_path7.dirname)(path), { recursive: true });
1285
- (0, import_node_fs7.writeFileSync)(path, ch.content);
1286
- }
1287
- const envPath = (0, import_node_path7.join)(dir, plan.env.file);
1288
- (0, import_node_fs7.writeFileSync)(envPath, mergeEnv((0, import_node_fs7.existsSync)(envPath) ? (0, import_node_fs7.readFileSync)(envPath, "utf8") : "", plan.env.vars));
1289
- const gitignorePath = (0, import_node_path7.join)(dir, ".gitignore");
1290
- if ((0, import_node_fs7.existsSync)((0, import_node_path7.join)(dir, ".git")) || (0, import_node_fs7.existsSync)(gitignorePath)) {
1291
- const gitignore = (0, import_node_fs7.existsSync)(gitignorePath) ? (0, import_node_fs7.readFileSync)(gitignorePath, "utf8") : "";
1292
- if (!ignoredByGit(gitignore, plan.env.file)) (0, import_node_fs7.writeFileSync)(gitignorePath, `${gitignore.replace(/\s*$/, "\n")}${plan.env.file}
2000
+ const path = (0, import_node_path11.join)(dir, ch.path);
2001
+ (0, import_node_fs12.mkdirSync)((0, import_node_path11.dirname)(path), { recursive: true });
2002
+ (0, import_node_fs12.writeFileSync)(path, ch.content);
2003
+ }
2004
+ if (plan.env.file) {
2005
+ const envPath = (0, import_node_path11.join)(dir, plan.env.file);
2006
+ (0, import_node_fs12.writeFileSync)(envPath, mergeEnv((0, import_node_fs12.existsSync)(envPath) ? (0, import_node_fs12.readFileSync)(envPath, "utf8") : "", plan.env.vars));
2007
+ const gitignorePath = (0, import_node_path11.join)(dir, ".gitignore");
2008
+ if ((0, import_node_fs12.existsSync)((0, import_node_path11.join)(dir, ".git")) || (0, import_node_fs12.existsSync)(gitignorePath)) {
2009
+ const gitignore = (0, import_node_fs12.existsSync)(gitignorePath) ? (0, import_node_fs12.readFileSync)(gitignorePath, "utf8") : "";
2010
+ if (!ignoredByGit(gitignore, plan.env.file)) (0, import_node_fs12.writeFileSync)(gitignorePath, `${gitignore.replace(/\s*$/, "\n")}${plan.env.file}
1293
2011
  `);
2012
+ }
1294
2013
  }
1295
2014
  say(`${green("\u25C7")} Files written`);
2015
+ const run = (command, args) => {
2016
+ if (!(0, import_node_path11.isAbsolute)(command) && !installed(command)) return "missing";
2017
+ say(`${bar} ${dim(`${command} ${args.join(" ")}`)}`);
2018
+ const result = process.platform === "win32" ? (0, import_node_child_process3.spawnSync)([command, ...args].map((a) => /[\s"&|<>^]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a).join(" "), { cwd: dir, stdio: "inherit", shell: true }) : (0, import_node_child_process3.spawnSync)(command, args, { cwd: dir, stdio: "inherit" });
2019
+ if (result.error?.code === "ENOENT" || process.platform === "win32" && result.status === 9009 || process.platform !== "win32" && result.status === 127) return "missing";
2020
+ return result.status === 0 ? "ok" : "failed";
2021
+ };
1296
2022
  for (const [packages, dev] of [[plan.install, false], [plan.devInstall, true]]) {
1297
2023
  if (!packages.length) continue;
1298
2024
  const [command, args] = installCommand(project, [...packages], dev, options.tarballs);
1299
- say(`${bar} ${dim(`${command} ${args.join(" ")}`)}`);
1300
- const result = process.platform === "win32" ? (0, import_node_child_process2.spawnSync)([command, ...args].map((a) => /[\s"&|<>^]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a).join(" "), { cwd: dir, stdio: "inherit", shell: true }) : (0, import_node_child_process2.spawnSync)(command, args, { cwd: dir, stdio: "inherit" });
1301
- if (result.status !== 0) {
2025
+ if (run(command, args) !== "ok") {
1302
2026
  say(`${yellow("\u25A0")} The install failed. Run it yourself: ${command} ${args.join(" ")}`);
1303
2027
  return 1;
1304
2028
  }
1305
2029
  }
1306
- say(`${green("\u25C7")} Packages installed`);
2030
+ const leftToDo = [];
2031
+ for (const cmd of plan.commands ?? []) {
2032
+ const [command, ...args] = cmd.argv;
2033
+ const result = run(command, args);
2034
+ if (result === "missing") leftToDo.push(`${cmd.argv.join(" ")} ${dim(`(${command} isn't installed here)`)}`);
2035
+ else if (result === "failed") leftToDo.push(cmd.argv.join(" "));
2036
+ }
2037
+ say(`${green("\u25C7")} ${leftToDo.length ? "Set up \u2014 finish with:" : "Packages installed"}`);
2038
+ for (const line of leftToDo) say(`${bar} ${line}`);
1307
2039
  for (const m of plan.manual) {
1308
2040
  say(bar);
1309
2041
  say(`${yellow("!")} ${bold(m.path)} \u2014 ${m.why}:`);
@@ -1321,6 +2053,7 @@ var HELP = `zharp ${VERSION} \u2014 readable stack traces for Zharp
1321
2053
 
1322
2054
  Usage:
1323
2055
  zharp init Connect this project to Zharp and set it up
2056
+ (also: npm init zharp@latest)
1324
2057
  [--yes] [--dry-run] (signs in through the browser)
1325
2058
  zharp sourcemaps inject <dir> Add debug IDs to JS files and their maps
1326
2059
  zharp sourcemaps upload <dir> --app <id> Upload JS files and their maps
@@ -1329,12 +2062,17 @@ Usage:
1329
2062
  zharp dart-symbols upload <dir> --app <id> Flutter --split-debug-info output
1330
2063
  [--obfuscation-map <file>] (and its obfuscation map)
1331
2064
  zharp dsym upload <path> --app <id> A .dSYM, or a folder of them
2065
+ zharp react-native upload --bundle <file> --map <file> --app <id>
2066
+ A React Native release bundle's source map
2067
+ zharp react-native upload --dir dist --app <id> Every bundle an \`npx expo export\` wrote (EAS Update)
1332
2068
 
1333
2069
  Options:
1334
2070
  --app <id> Application ID (or ZHARP_APP)
1335
2071
  --release <r> Release name to file the upload under (or ZHARP_RELEASE)
1336
2072
  --include <glob> Only these files (repeatable; sourcemaps)
1337
2073
  --exclude <glob> Not these files (repeatable; sourcemaps)
2074
+ --sources <dir> The project whose sources go with the symbols (dart-symbols, dsym; default: found)
2075
+ --no-sources Don't upload the app's sources (errors then show code only from a linked repo)
1338
2076
  --delete-after Delete .map files after uploading them
1339
2077
  --dry-run Show what would happen; change and send nothing
1340
2078
  --url <url> Zharp API (default ZHARP_URL or https://api.zharp.io)
@@ -1358,6 +2096,11 @@ async function main(argv) {
1358
2096
  release: { type: "string" },
1359
2097
  uuid: { type: "string" },
1360
2098
  "obfuscation-map": { type: "string" },
2099
+ sources: { type: "string" },
2100
+ bundle: { type: "string" },
2101
+ dir: { type: "string" },
2102
+ map: { type: "string" },
2103
+ "no-sources": { type: "boolean" },
1361
2104
  include: { type: "string", multiple: true },
1362
2105
  exclude: { type: "string", multiple: true },
1363
2106
  "delete-after": { type: "boolean" },
@@ -1387,7 +2130,7 @@ async function main(argv) {
1387
2130
  const release2 = values.release ?? process.env.ZHARP_RELEASE;
1388
2131
  const needTarget = (what) => {
1389
2132
  if (!target) fail(`${group} ${command} needs ${what}. See \`zharp --help\`.`);
1390
- if (!(0, import_node_fs8.existsSync)(target)) fail(`${target} does not exist.`);
2133
+ if (!(0, import_node_fs13.existsSync)(target)) fail(`${target} does not exist.`);
1391
2134
  return target;
1392
2135
  };
1393
2136
  const connect2 = () => dryRun ? null : resolveConnection({ app: values.app, url: values.url });
@@ -1419,11 +2162,24 @@ async function main(argv) {
1419
2162
  return;
1420
2163
  }
1421
2164
  case "dart-symbols upload": {
1422
- await uploadDartSymbols(needTarget("the --split-debug-info directory"), connect2(), { release: release2, dryRun, logger, obfuscationMap: values["obfuscation-map"] });
2165
+ const sources = values["no-sources"] ? false : values.sources;
2166
+ await uploadDartSymbols(needTarget("the --split-debug-info directory"), connect2(), { release: release2, dryRun, logger, obfuscationMap: values["obfuscation-map"], sources });
2167
+ return;
2168
+ }
2169
+ case "react-native upload": {
2170
+ if (values.dir) {
2171
+ if (!(0, import_node_fs13.existsSync)(values.dir)) fail(`${values.dir} does not exist.`);
2172
+ await uploadReactNativeDir(values.dir, connect2(), { release: release2, dryRun, logger });
2173
+ return;
2174
+ }
2175
+ if (!values.bundle || !values.map) fail("react-native upload needs --bundle <index.android.bundle | main.jsbundle> and --map <its source map>, or --dir <expo export output>.");
2176
+ for (const file of [values.bundle, values.map]) if (!(0, import_node_fs13.existsSync)(file)) fail(`${file} does not exist.`);
2177
+ await uploadReactNative(values.bundle, values.map, connect2(), { release: release2, dryRun, logger });
1423
2178
  return;
1424
2179
  }
1425
2180
  case "dsym upload": {
1426
- await uploadDsyms(needTarget("a .dSYM bundle or a folder of them"), connect2(), { release: release2, dryRun, logger });
2181
+ const sources = values["no-sources"] ? false : values.sources;
2182
+ await uploadDsyms(needTarget("a .dSYM bundle or a folder of them"), connect2(), { release: release2, dryRun, logger, sources });
1427
2183
  return;
1428
2184
  }
1429
2185
  default: