@zharp/cli 0.2.1 → 0.4.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 +958 -134
- package/dist/cli.js.map +1 -1
- package/dist/index.d.mts +13 -2
- package/dist/index.d.ts +13 -2
- package/dist/index.js +191 -44
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +181 -34
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
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
|
|
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((
|
|
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
|
|
121
|
-
var
|
|
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,
|
|
339
|
-
return send(connection, [{ kind: "proguard", debugId: uuid.toLowerCase(), name: (0,
|
|
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,
|
|
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,
|
|
480
|
+
const data = (0, import_node_fs4.readFileSync)(file);
|
|
348
481
|
if (!isElf(data)) {
|
|
349
|
-
if (named) logger.warn(`Skipped ${(0,
|
|
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,
|
|
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,
|
|
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,
|
|
364
|
-
for (const where of [dir, (0,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
528
|
+
name: (0, import_node_path3.basename)(f.path),
|
|
396
529
|
arch: f.arch,
|
|
397
530
|
release: options.release,
|
|
398
|
-
data: (0,
|
|
531
|
+
data: (0, import_node_fs4.readFileSync)(f.path),
|
|
399
532
|
gzip: true
|
|
400
533
|
}));
|
|
401
|
-
if (options.obfuscationMap && !(0,
|
|
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,
|
|
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,
|
|
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,
|
|
417
|
-
const candidates = (0,
|
|
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,
|
|
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,
|
|
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,
|
|
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/
|
|
450
|
-
var
|
|
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
|
|
456
|
-
var
|
|
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,
|
|
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,
|
|
557
|
-
const out = [(0,
|
|
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,
|
|
561
|
-
out.unshift((0,
|
|
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,
|
|
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,
|
|
767
|
+
const stat = (0, import_node_fs6.statSync)(path);
|
|
582
768
|
if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) continue;
|
|
583
|
-
contents[i] = (0,
|
|
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,
|
|
602
|
-
const url = sourceMappingUrl(code ?? (0,
|
|
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,
|
|
611
|
-
return (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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
644
|
-
if (map.changed) (0,
|
|
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,
|
|
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,
|
|
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,
|
|
709
|
-
const code = (0,
|
|
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,
|
|
897
|
+
if (stripped !== code) (0, import_node_fs7.writeFileSync)(source.file, stripped);
|
|
712
898
|
}
|
|
713
|
-
if ((0,
|
|
714
|
-
(0,
|
|
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.
|
|
908
|
+
var VERSION = "0.4.0";
|
|
723
909
|
|
|
724
910
|
// src/init/index.ts
|
|
725
|
-
var
|
|
726
|
-
var
|
|
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
|
|
914
|
+
var import_node_path11 = require("path");
|
|
729
915
|
|
|
730
916
|
// src/init/connect.ts
|
|
731
|
-
var
|
|
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,
|
|
925
|
+
(0, import_node_child_process2.spawn)(command, args, { stdio: "ignore", detached: true }).on("error", () => {
|
|
740
926
|
}).unref();
|
|
741
927
|
} catch {
|
|
742
928
|
}
|
|
@@ -750,7 +936,7 @@ async function connect(api, project, hooks) {
|
|
|
750
936
|
const opened = await http(`${base}/sessions`, {
|
|
751
937
|
method: "POST",
|
|
752
938
|
headers: { "content-type": "application/json", "user-agent": `zharp-cli/${VERSION}` },
|
|
753
|
-
body: JSON.stringify({ name: project.name, framework: project.label, platform: project.platform, os: OS_NAMES[(0, import_node_os.platform)()] ?? `${(0, import_node_os.platform)()} ${(0, import_node_os.release)()}`, cliVersion: VERSION })
|
|
939
|
+
body: JSON.stringify({ name: project.name, framework: project.label, catalog: project.catalog, platform: project.platform, os: OS_NAMES[(0, import_node_os.platform)()] ?? `${(0, import_node_os.platform)()} ${(0, import_node_os.release)()}`, cliVersion: VERSION })
|
|
754
940
|
}).catch((error) => {
|
|
755
941
|
throw new SetupFailed(`Could not reach Zharp at ${api} (${error?.cause?.code ?? error?.message ?? error}).`);
|
|
756
942
|
});
|
|
@@ -777,11 +963,34 @@ async function connect(api, project, hooks) {
|
|
|
777
963
|
}
|
|
778
964
|
|
|
779
965
|
// src/init/detect.ts
|
|
780
|
-
var
|
|
781
|
-
var
|
|
966
|
+
var import_node_fs8 = require("fs");
|
|
967
|
+
var import_node_path7 = require("path");
|
|
968
|
+
var PYTHON_FRAMEWORKS = [
|
|
969
|
+
{ id: "chalice", requirement: /\bchalice\b/, catalog: "Chalice" },
|
|
970
|
+
{ id: "sanic", requirement: /\bsanic\b/, catalog: "Sanic" },
|
|
971
|
+
{ id: "quart", requirement: /\bquart\b/, catalog: "Quart" },
|
|
972
|
+
{ id: "starlette", requirement: /\bstarlette\b/, catalog: "Starlette" },
|
|
973
|
+
{ id: "falcon", requirement: /\bfalcon\b/, catalog: "Falcon" },
|
|
974
|
+
{ id: "tornado", requirement: /\btornado\b/, catalog: "Tornado" },
|
|
975
|
+
{ id: "pyramid", requirement: /\bpyramid\b/, catalog: "Pyramid" },
|
|
976
|
+
{ id: "aiohttp", requirement: /\baiohttp\b/, catalog: "AIOHTTP" },
|
|
977
|
+
{ id: "bottle", requirement: /\bbottle\b/, catalog: "Bottle" },
|
|
978
|
+
{ id: "celery", requirement: /\bcelery\b/, catalog: "Celery" },
|
|
979
|
+
{ id: "rq", requirement: /^\s*rq\b|["']rq\b/m, catalog: "RQ (Redis Queue)" }
|
|
980
|
+
];
|
|
981
|
+
var GO_ROUTERS = [
|
|
982
|
+
{ id: "gin", module: /github\.com\/gin-gonic\/gin\b/, catalog: "Gin" },
|
|
983
|
+
{ id: "echo", module: /github\.com\/labstack\/echo\b/, catalog: "Echo" },
|
|
984
|
+
{ id: "fiber", module: /github\.com\/gofiber\/fiber\/v2\b/, catalog: "Fiber" },
|
|
985
|
+
{ id: "iris", module: /github\.com\/kataras\/iris\/v12\b/, catalog: "Iris" },
|
|
986
|
+
{ id: "fasthttp", module: /github\.com\/valyala\/fasthttp\b/, catalog: "FastHTTP" },
|
|
987
|
+
// Negroni first: a Negroni app often routes with gorilla/mux (both are set up).
|
|
988
|
+
{ id: "negroni", module: /github\.com\/urfave\/negroni\b/, catalog: "Negroni" },
|
|
989
|
+
{ id: "gorilla", module: /github\.com\/gorilla\/mux\b/, catalog: "Go" }
|
|
990
|
+
];
|
|
782
991
|
var read = (path) => {
|
|
783
992
|
try {
|
|
784
|
-
return (0,
|
|
993
|
+
return (0, import_node_fs8.readFileSync)(path, "utf8");
|
|
785
994
|
} catch {
|
|
786
995
|
return null;
|
|
787
996
|
}
|
|
@@ -791,13 +1000,13 @@ function majorOf(range) {
|
|
|
791
1000
|
return m ? ` ${m[1]}` : "";
|
|
792
1001
|
}
|
|
793
1002
|
function packageManagerOf(dir) {
|
|
794
|
-
if ((0,
|
|
795
|
-
if ((0,
|
|
796
|
-
if ((0,
|
|
1003
|
+
if ((0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "pnpm-lock.yaml"))) return "pnpm";
|
|
1004
|
+
if ((0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "yarn.lock"))) return "yarn";
|
|
1005
|
+
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
1006
|
return "npm";
|
|
798
1007
|
}
|
|
799
1008
|
function detect(dir) {
|
|
800
|
-
const pkgText = read((0,
|
|
1009
|
+
const pkgText = read((0, import_node_path7.join)(dir, "package.json"));
|
|
801
1010
|
const pkg = pkgText ? (() => {
|
|
802
1011
|
try {
|
|
803
1012
|
return JSON.parse(pkgText);
|
|
@@ -806,41 +1015,602 @@ function detect(dir) {
|
|
|
806
1015
|
}
|
|
807
1016
|
})() : null;
|
|
808
1017
|
const deps = { ...pkg?.dependencies ?? {}, ...pkg?.devDependencies ?? {} };
|
|
809
|
-
const name = typeof pkg?.name === "string" && pkg.name.replace(/^@[^/]+\//, "") || (0,
|
|
810
|
-
const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || (0,
|
|
1018
|
+
const name = typeof pkg?.name === "string" && pkg.name.replace(/^@[^/]+\//, "") || (0, import_node_path7.basename)(dir);
|
|
1019
|
+
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 };
|
|
1020
|
+
if (deps.expo) return { ...base, framework: "expo", label: `Expo${majorOf(deps.expo).replace(/^ (\d+)$/, " SDK $1")}`, catalog: "React Native", platform: "react-native" };
|
|
1021
|
+
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]}` : ""}`, catalog: "React Native", platform: "react-native" };
|
|
811
1022
|
if (deps.next) {
|
|
812
|
-
const appDir = (0,
|
|
813
|
-
return { ...base, framework: "nextjs", label: `Next.js${majorOf(deps.next)}`, platform: "browser", appDir };
|
|
1023
|
+
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;
|
|
1024
|
+
return { ...base, framework: "nextjs", label: `Next.js${majorOf(deps.next)}`, catalog: "Next.js", platform: "browser", appDir };
|
|
814
1025
|
}
|
|
815
|
-
if (deps["@nestjs/core"]) return { ...base, framework: "nestjs", label: `NestJS${majorOf(deps["@nestjs/core"])}`, platform: "node" };
|
|
816
|
-
if (deps.vite && deps.react) return { ...base, framework: "vite-react", label: "React (Vite)", platform: "browser" };
|
|
817
|
-
if (deps.express) return { ...base, framework: "express", label: `Express${majorOf(deps.express)}`, platform: "node" };
|
|
818
|
-
|
|
1026
|
+
if (deps["@nestjs/core"]) return { ...base, framework: "nestjs", label: `NestJS${majorOf(deps["@nestjs/core"])}`, catalog: "NestJS", platform: "node" };
|
|
1027
|
+
if (deps.vite && deps.react) return { ...base, framework: "vite-react", label: "React (Vite)", catalog: "React", platform: "browser" };
|
|
1028
|
+
if (deps.express) return { ...base, framework: "express", label: `Express${majorOf(deps.express)}`, catalog: "Express", platform: "node" };
|
|
1029
|
+
if (deps.fastify) return { ...base, framework: "fastify", label: `Fastify${majorOf(deps.fastify)}`, catalog: "Fastify", platform: "node" };
|
|
1030
|
+
if (deps.koa) return { ...base, framework: "koa", label: `Koa${majorOf(deps.koa)}`, catalog: "Koa", platform: "node" };
|
|
1031
|
+
if (deps["@hapi/hapi"]) return { ...base, framework: "hapi", label: `Hapi${majorOf(deps["@hapi/hapi"])}`, catalog: "Hapi", platform: "node" };
|
|
1032
|
+
if (deps.connect) return { ...base, framework: "connect", label: "Connect", catalog: "Connect", platform: "node" };
|
|
1033
|
+
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
1034
|
if (py) {
|
|
820
|
-
const pyName = (0,
|
|
821
|
-
if (/\bdjango\b/.test(py)) return { ...base, name: pyName, framework: "django", label: "Django", platform: "python" };
|
|
822
|
-
if (/\bfastapi\b/.test(py)) return { ...base, name: pyName, framework: "fastapi", label: "FastAPI", platform: "python" };
|
|
823
|
-
if (/\bflask\b/.test(py)) return { ...base, name: pyName, framework: "flask", label: "Flask", platform: "python" };
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
if (
|
|
1035
|
+
const pyName = (0, import_node_path7.basename)(dir);
|
|
1036
|
+
if (/\bdjango\b/.test(py)) return { ...base, name: pyName, framework: "django", label: "Django", catalog: "Django", platform: "python" };
|
|
1037
|
+
if (/\bfastapi\b/.test(py)) return { ...base, name: pyName, framework: "fastapi", label: "FastAPI", catalog: "FastAPI", platform: "python" };
|
|
1038
|
+
if (/\bflask\b/.test(py)) return { ...base, name: pyName, framework: "flask", label: "Flask", catalog: "Flask", platform: "python" };
|
|
1039
|
+
const more = PYTHON_FRAMEWORKS.find((f) => f.requirement.test(py));
|
|
1040
|
+
if (more) return { ...base, name: pyName, framework: more.id, label: more.catalog, catalog: more.catalog, platform: "python" };
|
|
1041
|
+
}
|
|
1042
|
+
const composer = read((0, import_node_path7.join)(dir, "composer.json"));
|
|
1043
|
+
if (composer && /laravel\/framework/.test(composer)) return { ...base, name: (0, import_node_path7.basename)(dir), framework: "laravel", label: "Laravel", catalog: "Laravel", platform: "php" };
|
|
1044
|
+
const goMod = read((0, import_node_path7.join)(dir, "go.mod"));
|
|
1045
|
+
if (goMod !== null) {
|
|
1046
|
+
const router = GO_ROUTERS.find((r) => r.module.test(goMod));
|
|
1047
|
+
const moduleName = /^module\s+(\S+)/m.exec(goMod)?.[1]?.split("/").pop();
|
|
1048
|
+
const label = router ? `Go (${router.id === "gorilla" ? "gorilla/mux" : router.catalog})` : "Go";
|
|
1049
|
+
return { ...base, name: moduleName || (0, import_node_path7.basename)(dir), framework: "go", label, catalog: router?.catalog ?? "Go", goRouter: router?.id, platform: "go" };
|
|
1050
|
+
}
|
|
1051
|
+
if (pkg) return { ...base, framework: "node", label: "Node.js", catalog: "Node.js", platform: "node" };
|
|
829
1052
|
return { ...base, framework: "unknown", label: "an unknown project", platform: "otel" };
|
|
830
1053
|
}
|
|
831
1054
|
|
|
832
1055
|
// src/init/recipes.ts
|
|
833
|
-
var
|
|
834
|
-
var
|
|
835
|
-
|
|
1056
|
+
var import_node_fs11 = require("fs");
|
|
1057
|
+
var import_node_path10 = require("path");
|
|
1058
|
+
|
|
1059
|
+
// src/init/recipes-more.ts
|
|
1060
|
+
var import_node_fs9 = require("fs");
|
|
1061
|
+
var import_node_path8 = require("path");
|
|
836
1062
|
var read2 = (dir, path) => {
|
|
837
1063
|
try {
|
|
838
|
-
return (0,
|
|
1064
|
+
return (0, import_node_fs9.readFileSync)((0, import_node_path8.join)(dir, path), "utf8").replace(/\r\n/g, "\n");
|
|
839
1065
|
} catch {
|
|
840
1066
|
return null;
|
|
841
1067
|
}
|
|
842
1068
|
};
|
|
843
|
-
var first = (dir, paths) => paths.find((p) => (0,
|
|
1069
|
+
var first = (dir, paths) => paths.find((p) => (0, import_node_fs9.existsSync)((0, import_node_path8.join)(dir, p))) ?? null;
|
|
1070
|
+
function emptyPlan(envFile) {
|
|
1071
|
+
return { install: [], devInstall: [], changes: [], manual: [], notes: [], env: { file: envFile ?? "", vars: {} }, commands: [] };
|
|
1072
|
+
}
|
|
1073
|
+
var DEFAULT_API = "https://api.zharp.io";
|
|
1074
|
+
var otlpOf = (api) => {
|
|
1075
|
+
const clean = api.replace(/\/+$/, "");
|
|
1076
|
+
return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;
|
|
1077
|
+
};
|
|
1078
|
+
function findFiles(dir, suffix, depth = 3) {
|
|
1079
|
+
const skip = /^(node_modules|vendor|\.git|\.venv|venv|env|__pycache__|dist|build|target|\.next|site-packages)$/;
|
|
1080
|
+
const out = [];
|
|
1081
|
+
const walk2 = (at, level) => {
|
|
1082
|
+
let entries;
|
|
1083
|
+
try {
|
|
1084
|
+
entries = (0, import_node_fs9.readdirSync)(at, { withFileTypes: true });
|
|
1085
|
+
} catch {
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
for (const e of entries) {
|
|
1089
|
+
if (e.isDirectory()) {
|
|
1090
|
+
if (level < depth && !skip.test(e.name) && !e.name.startsWith(".")) walk2((0, import_node_path8.join)(at, e.name), level + 1);
|
|
1091
|
+
} else if (e.name.endsWith(suffix)) {
|
|
1092
|
+
out.push((0, import_node_path8.relative)(dir, (0, import_node_path8.join)(at, e.name)).replace(/\\/g, "/"));
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
walk2(dir, 0);
|
|
1097
|
+
return out.sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b));
|
|
1098
|
+
}
|
|
1099
|
+
function nodeEntry(project) {
|
|
1100
|
+
const scripts = project.packageJson?.scripts ?? {};
|
|
1101
|
+
for (const name of ["start", "dev", "serve"]) {
|
|
1102
|
+
const m = /(?:^|\s)(?:node|nodemon|tsx|ts-node)(?:\s+--?[\w-]+(?:[= ][^\s]+)?)*\s+([\w./-]+\.(?:c|m)?[jt]s)\b/.exec(scripts[name] ?? "");
|
|
1103
|
+
if (m && (0, import_node_fs9.existsSync)((0, import_node_path8.join)(project.dir, m[1]))) return m[1].replace(/^\.\//, "");
|
|
1104
|
+
}
|
|
1105
|
+
const main2 = project.packageJson?.main;
|
|
1106
|
+
if (typeof main2 === "string" && (0, import_node_fs9.existsSync)((0, import_node_path8.join)(project.dir, main2))) return main2.replace(/^\.\//, "");
|
|
1107
|
+
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"]);
|
|
1108
|
+
}
|
|
1109
|
+
function express(project, c, api) {
|
|
1110
|
+
const plan = emptyPlan(".env");
|
|
1111
|
+
plan.install = ["@zharp/node"];
|
|
1112
|
+
const entry = nodeEntry(project);
|
|
1113
|
+
const endpoint = otlpOf(api);
|
|
1114
|
+
plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ...endpoint ? { ZHARP_ENDPOINT: endpoint } : {} };
|
|
1115
|
+
plan.notes.push("Set ZHARP_KEY where the app runs in production.");
|
|
1116
|
+
if (!entry) {
|
|
1117
|
+
plan.manual.push({ path: "your entry file", why: "start Zharp before anything else loads", snippet: "require('./instrument'); // or: node --import ./instrument.mjs server.js" });
|
|
1118
|
+
return plan;
|
|
1119
|
+
}
|
|
1120
|
+
const main2 = read2(project.dir, entry) ?? "";
|
|
1121
|
+
const ts = entry.endsWith(".ts");
|
|
1122
|
+
const esm = project.packageJson?.type === "module" || /\.mjs$/.test(entry) || !ts && /^\s*import\s/m.test(main2);
|
|
1123
|
+
const dirOf = entry.includes("/") ? entry.slice(0, entry.lastIndexOf("/") + 1) : "";
|
|
1124
|
+
const instrumentName = ts ? "instrument.ts" : esm ? entry.endsWith(".mjs") ? "instrument.mjs" : "instrument.js" : entry.endsWith(".cjs") ? "instrument.cjs" : "instrument.js";
|
|
1125
|
+
const instrumentPath = `${dirOf}${instrumentName}`;
|
|
1126
|
+
const body = [
|
|
1127
|
+
"// Before anything else: http, the framework and the database drivers are instrumented as they load.",
|
|
1128
|
+
"try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the key */ }",
|
|
1129
|
+
`Zharp.init({ service: '${c.application.serviceName}' });`,
|
|
1130
|
+
""
|
|
1131
|
+
];
|
|
1132
|
+
const content = esm || ts ? ["import { Zharp } from '@zharp/node';", "", ...body].join("\n") : ["const { Zharp } = require('@zharp/node');", "", ...body].join("\n");
|
|
1133
|
+
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" });
|
|
1134
|
+
if (main2.includes("instrument")) return plan;
|
|
1135
|
+
if (esm && !ts) {
|
|
1136
|
+
const pkgText = read2(project.dir, "package.json");
|
|
1137
|
+
let text = pkgText ?? "";
|
|
1138
|
+
const preload = `--import ./${instrumentPath}`;
|
|
1139
|
+
let changed = false;
|
|
1140
|
+
for (const [name, command] of Object.entries(project.packageJson?.scripts ?? {})) {
|
|
1141
|
+
if (command.includes(preload)) continue;
|
|
1142
|
+
const m = /^(node|nodemon)\s+/.exec(command);
|
|
1143
|
+
if (!m || !command.includes(entry.replace(/^\.\//, ""))) continue;
|
|
1144
|
+
const next = command.replace(/^(node|nodemon)\s+/, `$1 ${preload} `);
|
|
1145
|
+
text = text.replace(`"${name}": ${JSON.stringify(command)}`, `"${name}": ${JSON.stringify(next)}`);
|
|
1146
|
+
changed = true;
|
|
1147
|
+
}
|
|
1148
|
+
if (changed) plan.changes.push({ path: "package.json", kind: "edit", content: text, note: "start scripts preload Zharp (--import)" });
|
|
1149
|
+
plan.manual.push({ path: "your start command", why: "ES modules: wherever the app starts outside these scripts, preload Zharp", snippet: `node ${preload} ${entry}` });
|
|
1150
|
+
return plan;
|
|
1151
|
+
}
|
|
1152
|
+
const line = ts ? "import './instrument';" : "require('./instrument');";
|
|
1153
|
+
plan.changes.push({ path: entry, kind: "edit", content: `${line}
|
|
1154
|
+
${main2}`, note: "loads it first" });
|
|
1155
|
+
return plan;
|
|
1156
|
+
}
|
|
1157
|
+
function pythonInit(c, api, logs = false) {
|
|
1158
|
+
const endpoint = otlpOf(api);
|
|
1159
|
+
return [
|
|
1160
|
+
"import zharp",
|
|
1161
|
+
"",
|
|
1162
|
+
"# The app's key can only send data to this app, so it is safe in code.",
|
|
1163
|
+
`zharp.init(key="${c.application.ingestKey}", service="${c.application.serviceName}"${endpoint ? `, endpoint="${api.replace(/\/+$/, "")}/api/v1/otlp"` : ""}${logs ? ", logs=True" : ""})`
|
|
1164
|
+
].join("\n");
|
|
1165
|
+
}
|
|
1166
|
+
var PYTHON_APP = {
|
|
1167
|
+
fastapi: { marker: /\bFastAPI\(/, where: "the file that creates FastAPI()" },
|
|
1168
|
+
flask: { marker: /\bFlask\(\s*__name__/, where: "the file that creates Flask(__name__)" },
|
|
1169
|
+
chalice: { marker: /\bChalice\(/, where: "app.py, before Chalice(...)" },
|
|
1170
|
+
sanic: { marker: /\bSanic\(/, where: "the file that creates Sanic(...)" },
|
|
1171
|
+
quart: { marker: /\bQuart\(/, where: "the file that creates Quart(__name__)" },
|
|
1172
|
+
starlette: { marker: /\bStarlette\(/, where: "the file that creates Starlette(...)" },
|
|
1173
|
+
falcon: { marker: /\bfalcon\.(?:asgi\.)?(?:App|API)\(/, where: "the file that creates falcon.App()" },
|
|
1174
|
+
tornado: { marker: /\b(?:tornado\.web\.)?Application\(/, where: "the file that creates the tornado Application" },
|
|
1175
|
+
pyramid: { marker: /\bConfigurator\(/, where: "the file that creates the Configurator" },
|
|
1176
|
+
aiohttp: { marker: /\bweb\.Application\(/, where: "the file that creates web.Application()" },
|
|
1177
|
+
bottle: { marker: /\bBottle\(|\bbottle\.run\(|^\s*run\(/m, where: "the file that creates the Bottle app" },
|
|
1178
|
+
celery: { marker: /\bCelery\(/, where: "the module that creates your Celery app" },
|
|
1179
|
+
rq: { marker: /\bWorker\(|\bQueue\(/, where: "the module your RQ worker imports" }
|
|
1180
|
+
};
|
|
1181
|
+
function afterPythonImports(text, block) {
|
|
1182
|
+
if (/^\s*import zharp\b/m.test(text)) return null;
|
|
1183
|
+
const lines = text.split("\n");
|
|
1184
|
+
let i = 0;
|
|
1185
|
+
while (i < lines.length && /^\s*(#.*)?$/.test(lines[i])) i++;
|
|
1186
|
+
if (i < lines.length && /^\s*[rubRUB]*("""|''')/.test(lines[i])) {
|
|
1187
|
+
const quote = /("""|''')/.exec(lines[i])[1];
|
|
1188
|
+
const rest = lines[i].slice(lines[i].indexOf(quote) + 3);
|
|
1189
|
+
if (!rest.includes(quote)) {
|
|
1190
|
+
i++;
|
|
1191
|
+
while (i < lines.length && !lines[i].includes(quote)) i++;
|
|
1192
|
+
}
|
|
1193
|
+
i++;
|
|
1194
|
+
}
|
|
1195
|
+
let last = -1;
|
|
1196
|
+
for (let j = i; j < lines.length; j++) {
|
|
1197
|
+
if (/^(import |from \S+ import )/.test(lines[j])) {
|
|
1198
|
+
last = j;
|
|
1199
|
+
if (/\($/.test(lines[j].trim())) while (j < lines.length && !lines[j].includes(")")) last = ++j;
|
|
1200
|
+
} else if (!/^\s*(#.*)?$/.test(lines[j])) break;
|
|
1201
|
+
}
|
|
1202
|
+
const at = last >= 0 ? last + 1 : i;
|
|
1203
|
+
return [...lines.slice(0, at), "", block, "", ...lines.slice(at)].join("\n").replace(/\n{4,}/g, "\n\n\n");
|
|
1204
|
+
}
|
|
1205
|
+
function pythonInstall(project) {
|
|
1206
|
+
const dir = project.dir;
|
|
1207
|
+
const changes = [];
|
|
1208
|
+
const commands = [];
|
|
1209
|
+
const manual = [];
|
|
1210
|
+
const requirements = read2(dir, "requirements.txt");
|
|
1211
|
+
const pyproject = read2(dir, "pyproject.toml") ?? "";
|
|
1212
|
+
if (requirements !== null) {
|
|
1213
|
+
if (!/^zharp\b/im.test(requirements)) changes.push({ path: "requirements.txt", kind: "edit", content: `${requirements.replace(/\s*$/, "\n")}zharp
|
|
1214
|
+
`, note: "adds zharp" });
|
|
1215
|
+
}
|
|
1216
|
+
const venvPython = first(dir, [".venv/Scripts/python.exe", ".venv/bin/python", "venv/Scripts/python.exe", "venv/bin/python"]);
|
|
1217
|
+
if ((0, import_node_fs9.existsSync)((0, import_node_path8.join)(dir, "uv.lock"))) commands.push({ label: "uv add zharp", argv: ["uv", "add", "zharp"] });
|
|
1218
|
+
else if (/\[tool\.poetry\]/.test(pyproject)) commands.push({ label: "poetry add zharp", argv: ["poetry", "add", "zharp"] });
|
|
1219
|
+
else if (venvPython) commands.push({ label: `install zharp into ${venvPython.split("/")[0]}`, argv: [(0, import_node_path8.join)(dir, venvPython), "-m", "pip", "install", "zharp"] });
|
|
1220
|
+
else manual.push({ path: "your Python environment", why: "install the package where the app runs", snippet: "pip install zharp" });
|
|
1221
|
+
return { changes, commands, manual };
|
|
1222
|
+
}
|
|
1223
|
+
function python(project, c, api) {
|
|
1224
|
+
const plan = emptyPlan(null);
|
|
1225
|
+
const installed2 = pythonInstall(project);
|
|
1226
|
+
plan.changes.push(...installed2.changes);
|
|
1227
|
+
plan.commands = installed2.commands;
|
|
1228
|
+
plan.manual.push(...installed2.manual);
|
|
1229
|
+
const block = pythonInit(c, api, project.framework === "chalice");
|
|
1230
|
+
let targets = [];
|
|
1231
|
+
if (project.framework === "django") {
|
|
1232
|
+
targets = [first(project.dir, ["manage.py"]), ...findFiles(project.dir, "wsgi.py"), ...findFiles(project.dir, "asgi.py")].filter((p) => !!p);
|
|
1233
|
+
} else {
|
|
1234
|
+
const { marker } = PYTHON_APP[project.framework];
|
|
1235
|
+
const files = findFiles(project.dir, ".py").filter((f) => marker.test(read2(project.dir, f) ?? ""));
|
|
1236
|
+
const preferred = files.find((f) => /(^|\/)(main|app|server|wsgi|__init__)\.py$/.test(f)) ?? files[0];
|
|
1237
|
+
if (preferred) targets = [preferred];
|
|
1238
|
+
}
|
|
1239
|
+
for (const path of targets) {
|
|
1240
|
+
const text = read2(project.dir, path);
|
|
1241
|
+
const edited = text !== null ? afterPythonImports(text, block) : null;
|
|
1242
|
+
if (edited) plan.changes.push({ path, kind: "edit", content: edited, note: "starts Zharp" });
|
|
1243
|
+
}
|
|
1244
|
+
if (!targets.length) {
|
|
1245
|
+
const where = project.framework === "django" ? "manage.py, wsgi.py and asgi.py" : PYTHON_APP[project.framework].where;
|
|
1246
|
+
plan.manual.push({ path: where, why: "start Zharp at the top, after the imports", snippet: block });
|
|
1247
|
+
}
|
|
1248
|
+
return plan;
|
|
1249
|
+
}
|
|
1250
|
+
function laravel(project, c, api) {
|
|
1251
|
+
const plan = emptyPlan(".env");
|
|
1252
|
+
plan.commands = [{ label: "composer require zharp/zharp", argv: ["composer", "require", "zharp/zharp"] }];
|
|
1253
|
+
const endpoint = otlpOf(api);
|
|
1254
|
+
plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ZHARP_SERVICE: c.application.serviceName, ...endpoint ? { ZHARP_ENDPOINT: endpoint } : {} };
|
|
1255
|
+
plan.notes.push("Laravel finds Zharp by itself (package discovery). Set ZHARP_KEY in production too.");
|
|
1256
|
+
void project;
|
|
1257
|
+
return plan;
|
|
1258
|
+
}
|
|
1259
|
+
var GO_MODULE = "github.com/zharp-io/zharp-go-lib";
|
|
1260
|
+
function editGoMain(text, c, api, routers) {
|
|
1261
|
+
if (text.includes(GO_MODULE)) return null;
|
|
1262
|
+
const block = /^import \(\n([\s\S]*?)^\)/m.exec(text);
|
|
1263
|
+
const mainFn = /^func main\(\) \{\n/m.exec(text);
|
|
1264
|
+
if (!block || !mainFn) return null;
|
|
1265
|
+
const imports = block[1];
|
|
1266
|
+
const stdlib = [];
|
|
1267
|
+
if (!/^\s*"context"$/m.test(imports)) stdlib.push(' "context"');
|
|
1268
|
+
const add = [` zharp "${GO_MODULE}"`];
|
|
1269
|
+
let next = text;
|
|
1270
|
+
const addAfter = (after, line) => {
|
|
1271
|
+
next = next.replace(after[0], `${after[0]}${after[1]}${line}
|
|
1272
|
+
`);
|
|
1273
|
+
};
|
|
1274
|
+
const gin = routers.gin ? /^(\s*)(\w+) := gin\.(?:Default|New)\(\)\n/m.exec(next) : null;
|
|
1275
|
+
const echo = routers.echo ? /^(\s*)(\w+) := echo\.New\(\)\n/m.exec(next) : null;
|
|
1276
|
+
const fiber = routers.fiber ? /^(\s*)(\w+) := fiber\.New\([^\n]*\)\n/m.exec(next) : null;
|
|
1277
|
+
const iris = routers.iris ? /^(\s*)(\w+) := iris\.(?:New|Default)\(\)\n/m.exec(next) : null;
|
|
1278
|
+
if (gin) {
|
|
1279
|
+
add.push(` "${GO_MODULE}/zharpgin"`);
|
|
1280
|
+
addAfter(gin, `${gin[2]}.Use(zharpgin.Middleware())`);
|
|
1281
|
+
} else if (echo) {
|
|
1282
|
+
add.push(` "${GO_MODULE}/zharpecho"`);
|
|
1283
|
+
addAfter(echo, `${echo[2]}.Use(zharpecho.Middleware())`);
|
|
1284
|
+
} else if (fiber) {
|
|
1285
|
+
add.push(` "${GO_MODULE}/zharpfiber"`);
|
|
1286
|
+
const recover = new RegExp(String.raw`^([ \t]*)${fiber[2]}\.Use\(recover\.New\([^\n]*\)\)\n`, "m").exec(next);
|
|
1287
|
+
addAfter(recover ?? fiber, `${fiber[2]}.Use(zharpfiber.Middleware())`);
|
|
1288
|
+
} else if (iris) {
|
|
1289
|
+
add.push(` "${GO_MODULE}/zharpiris"`);
|
|
1290
|
+
addAfter(iris, `${iris[2]}.UseRouter(zharpiris.Middleware())`);
|
|
1291
|
+
} else if (routers.fasthttp && /fasthttp\.ListenAndServe\(/.test(next)) {
|
|
1292
|
+
add.push(` "${GO_MODULE}/zharpfasthttp"`);
|
|
1293
|
+
next = next.replace(/fasthttp\.ListenAndServe\(([^,]+),\s*([\w.]+)\)/, (_, addr, handler) => `fasthttp.ListenAndServe(${addr}, zharpfasthttp.Handler(${handler}))`);
|
|
1294
|
+
} else {
|
|
1295
|
+
const gorilla = routers.gorilla ? /^(\s*)(\w+) := mux\.NewRouter\(\)\n/m.exec(next) : null;
|
|
1296
|
+
if (gorilla) {
|
|
1297
|
+
add.push(` "${GO_MODULE}/zharpmux"`);
|
|
1298
|
+
addAfter(gorilla, `${gorilla[2]}.Use(zharpmux.Middleware())`);
|
|
1299
|
+
}
|
|
1300
|
+
next = next.replace(/http\.ListenAndServe\(([^,]+),\s*(nil|[\w.]+)\)/, (_, addr, handler) => `http.ListenAndServe(${addr}, zharp.Handler(${handler === "nil" ? "http.DefaultServeMux" : handler}))`);
|
|
1301
|
+
}
|
|
1302
|
+
const endpoint = otlpOf(api);
|
|
1303
|
+
const start = [
|
|
1304
|
+
" // The app's key can only send data to this app, so it is safe in code.",
|
|
1305
|
+
` shutdown := zharp.Init(zharp.Config{Key: "${c.application.ingestKey}", Service: "${c.application.serviceName}"${endpoint ? `, Endpoint: "${api.replace(/\/+$/, "")}/api/v1/otlp"` : ""}})`,
|
|
1306
|
+
" defer shutdown(context.Background())",
|
|
1307
|
+
""
|
|
1308
|
+
].join("\n");
|
|
1309
|
+
next = next.replace(block[0], `import (
|
|
1310
|
+
${groupedImports(imports, stdlib, add)})`);
|
|
1311
|
+
next = next.replace(/^func main\(\) \{\n/m, `func main() {
|
|
1312
|
+
${start}`);
|
|
1313
|
+
return next;
|
|
1314
|
+
}
|
|
1315
|
+
function groupedImports(body, stdlib, modules) {
|
|
1316
|
+
const groups = body.replace(/\n+$/, "").split(/\n[ \t]*\n/).map((g) => g.split("\n"));
|
|
1317
|
+
const isModule = (line) => /"[^"/]*\.[^"/]*\//.test(line) || /"[^"/]*\.[^"/]*"/.test(line);
|
|
1318
|
+
const std = groups.find((g) => g.some((l) => /"/.test(l)) && !g.some(isModule));
|
|
1319
|
+
const mods = groups.find((g) => g.some(isModule));
|
|
1320
|
+
if (stdlib.length) std ? std.push(...stdlib) : groups.unshift(stdlib);
|
|
1321
|
+
mods ? mods.push(...modules) : groups.push(modules);
|
|
1322
|
+
return `${groups.map((g) => g.join("\n")).join("\n\n")}
|
|
1323
|
+
`;
|
|
1324
|
+
}
|
|
1325
|
+
function go(project, c, api) {
|
|
1326
|
+
const plan = emptyPlan(null);
|
|
1327
|
+
const goMod = read2(project.dir, "go.mod") ?? "";
|
|
1328
|
+
const routers = Object.fromEntries(GO_ROUTERS.map((r) => [r.id, r.module.test(goMod)]));
|
|
1329
|
+
plan.commands = [{ label: `go get ${GO_MODULE}`, argv: ["go", "get", `${GO_MODULE}@latest`] }];
|
|
1330
|
+
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;
|
|
1331
|
+
const text = mainPath ? read2(project.dir, mainPath) : null;
|
|
1332
|
+
const edited = text ? editGoMain(text, c, api, routers) : null;
|
|
1333
|
+
if (mainPath && edited) {
|
|
1334
|
+
const module2 = /"github\.com\/zharp-io\/zharp-go-lib\/(zharp\w+)"/.exec(edited)?.[1];
|
|
1335
|
+
if (module2) plan.commands.push({ label: `go get \u2026/${module2}`, argv: ["go", "get", `${GO_MODULE}/${module2}@latest`] });
|
|
1336
|
+
const traced = { zharpgin: "Gin", zharpecho: "Echo", zharpfiber: "Fiber", zharpiris: "Iris", zharpfasthttp: "fasthttp", zharpmux: "gorilla/mux" }[module2 ?? ""];
|
|
1337
|
+
plan.changes.push({ path: mainPath, kind: "edit", content: edited, note: `starts Zharp${traced ? `; traces ${traced}` : edited.includes("zharp.Handler(") ? "; traces requests" : ""}` });
|
|
1338
|
+
plan.commands.push({ label: "go mod tidy", argv: ["go", "mod", "tidy"] });
|
|
1339
|
+
plan.commands.push({ label: `gofmt -w ${mainPath}`, argv: ["gofmt", "-w", mainPath] });
|
|
1340
|
+
if (!/zharp\.Handler\(|zharp\w+\.(Middleware|Handler)\(/.test(edited)) {
|
|
1341
|
+
plan.manual.push({ path: mainPath, why: "trace incoming requests: wrap the handler your server runs", snippet: routers.negroni ? 'http.ListenAndServe(":3000", zharp.Handler(n)) // instead of n.Run(":3000")' : 'http.ListenAndServe(":8080", zharp.Handler(mux))' });
|
|
1342
|
+
}
|
|
1343
|
+
} else if (!text?.includes(GO_MODULE)) {
|
|
1344
|
+
plan.manual.push({ path: mainPath ?? "main.go", why: "start Zharp first in main()", snippet: `shutdown := zharp.Init(zharp.Config{Key: "${c.application.ingestKey}"})
|
|
1345
|
+
defer shutdown(context.Background())` });
|
|
1346
|
+
}
|
|
1347
|
+
return plan;
|
|
1348
|
+
}
|
|
1349
|
+
function morePlanFor(project, c, api) {
|
|
1350
|
+
switch (project.framework) {
|
|
1351
|
+
case "express":
|
|
1352
|
+
case "koa":
|
|
1353
|
+
case "hapi":
|
|
1354
|
+
case "fastify":
|
|
1355
|
+
case "connect":
|
|
1356
|
+
return express(project, c, api);
|
|
1357
|
+
case "django":
|
|
1358
|
+
case "fastapi":
|
|
1359
|
+
case "flask":
|
|
1360
|
+
return python(project, c, api);
|
|
1361
|
+
case "laravel":
|
|
1362
|
+
return laravel(project, c, api);
|
|
1363
|
+
case "go":
|
|
1364
|
+
return go(project, c, api);
|
|
1365
|
+
default:
|
|
1366
|
+
return PYTHON_FRAMEWORKS.some((f) => f.id === project.framework) ? python(project, c, api) : null;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// src/init/recipes-rn.ts
|
|
1371
|
+
var import_node_fs10 = require("fs");
|
|
1372
|
+
var import_node_path9 = require("path");
|
|
1373
|
+
var read3 = (dir, path) => {
|
|
1374
|
+
try {
|
|
1375
|
+
return (0, import_node_fs10.readFileSync)((0, import_node_path9.join)(dir, path), "utf8").replace(/\r\n/g, "\n");
|
|
1376
|
+
} catch {
|
|
1377
|
+
return null;
|
|
1378
|
+
}
|
|
1379
|
+
};
|
|
1380
|
+
var first2 = (dir, paths) => paths.find((p) => (0, import_node_fs10.existsSync)((0, import_node_path9.join)(dir, p))) ?? null;
|
|
1381
|
+
function emptyPlan2() {
|
|
1382
|
+
return { install: [], devInstall: [], changes: [], manual: [], notes: [], env: { file: "", vars: {} }, commands: [] };
|
|
1383
|
+
}
|
|
1384
|
+
function endpointOf(api) {
|
|
1385
|
+
const clean = api.replace(/\/+$/, "");
|
|
1386
|
+
return /^https:\/\/api\.zharp\.io$/.test(clean) ? null : `${clean}/api/v1/otlp`;
|
|
1387
|
+
}
|
|
1388
|
+
var GRADLE_LINE = `apply from: new File(["node", "--print", "require.resolve('@zharp/react-native/package.json')"].execute(null, rootDir).text.trim(), "../zharp.gradle")`;
|
|
1389
|
+
function addGradleLine(text) {
|
|
1390
|
+
if (text.includes("zharp.gradle")) return text;
|
|
1391
|
+
const anchor = /^apply plugin: ["']com\.facebook\.react["'][^\n]*$/m;
|
|
1392
|
+
if (anchor.test(text)) return text.replace(anchor, (line) => `${line}
|
|
1393
|
+
${GRADLE_LINE}`);
|
|
1394
|
+
return `${text.replace(/\s*$/, "")}
|
|
1395
|
+
|
|
1396
|
+
${GRADLE_LINE}
|
|
1397
|
+
`;
|
|
1398
|
+
}
|
|
1399
|
+
function wireBundlePhase(script) {
|
|
1400
|
+
if (script.includes("zharp-upload.sh")) return script;
|
|
1401
|
+
const sourceMap = 'export SOURCEMAP_FILE="${SOURCEMAP_FILE:-$DERIVED_FILE_DIR/main.jsbundle.map}"';
|
|
1402
|
+
const lines = script.split("\n");
|
|
1403
|
+
lines.splice(lines[0].trim() === "set -e" ? 1 : 0, 0, sourceMap);
|
|
1404
|
+
const upload = '/bin/bash "$PODS_ROOT/../../node_modules/@zharp/react-native/ios/zharp-upload.sh"';
|
|
1405
|
+
return `${lines.join("\n").replace(/\s*$/, "")}
|
|
1406
|
+
${upload}
|
|
1407
|
+
`;
|
|
1408
|
+
}
|
|
1409
|
+
function wireXcodeProject(pbxproj) {
|
|
1410
|
+
const phase = /(name = "Bundle React Native code and images";[\s\S]*?shellScript = )("(?:[^"\\]|\\.)*")(;)/.exec(pbxproj);
|
|
1411
|
+
if (!phase) return null;
|
|
1412
|
+
let script;
|
|
1413
|
+
try {
|
|
1414
|
+
script = JSON.parse(phase[2]);
|
|
1415
|
+
} catch {
|
|
1416
|
+
return null;
|
|
1417
|
+
}
|
|
1418
|
+
const wired = wireBundlePhase(script);
|
|
1419
|
+
if (wired === script) return null;
|
|
1420
|
+
return pbxproj.replace(phase[0], `${phase[1]}${JSON.stringify(wired)}${phase[3]}`);
|
|
1421
|
+
}
|
|
1422
|
+
function wrapMetroConfig(text) {
|
|
1423
|
+
if (text.includes("withZharpConfig")) return null;
|
|
1424
|
+
const exportLine = /^module\.exports\s*=\s*([\s\S]+?);?\s*$/m;
|
|
1425
|
+
const m = exportLine.exec(text);
|
|
1426
|
+
if (!m) return null;
|
|
1427
|
+
const require2 = "const { withZharpConfig } = require('@zharp/react-native/metro');";
|
|
1428
|
+
const lines = text.split("\n");
|
|
1429
|
+
let lastRequire = -1;
|
|
1430
|
+
lines.forEach((line, i) => {
|
|
1431
|
+
if (/^\s*const .*=\s*require\(/.test(line)) lastRequire = i;
|
|
1432
|
+
});
|
|
1433
|
+
lines.splice(lastRequire + 1, 0, require2);
|
|
1434
|
+
return lines.join("\n").replace(exportLine, (_, value) => `module.exports = withZharpConfig(${value.trim().replace(/;$/, "")});`);
|
|
1435
|
+
}
|
|
1436
|
+
function initBlock(c, api, typescript) {
|
|
1437
|
+
void typescript;
|
|
1438
|
+
const endpoint = endpointOf(api);
|
|
1439
|
+
return [
|
|
1440
|
+
"// The app's key can only send data to this app, so it is safe in the app.",
|
|
1441
|
+
"Zharp.init({",
|
|
1442
|
+
` key: '${c.application.ingestKey}',`,
|
|
1443
|
+
` service: '${c.application.serviceName}',`,
|
|
1444
|
+
...endpoint ? [` endpoint: '${endpoint}',`] : [],
|
|
1445
|
+
"});"
|
|
1446
|
+
].join("\n");
|
|
1447
|
+
}
|
|
1448
|
+
function afterImports(text, imports, block) {
|
|
1449
|
+
const lines = text.split("\n");
|
|
1450
|
+
let last = -1;
|
|
1451
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1452
|
+
const line = lines[i].trim();
|
|
1453
|
+
if (/^import\b/.test(line)) {
|
|
1454
|
+
last = i;
|
|
1455
|
+
while (last < lines.length - 1 && !/from\s+['"][^'"]+['"];?\s*$|^import\s+['"][^'"]+['"];?\s*$/.test(lines[last].trim())) last++;
|
|
1456
|
+
i = last;
|
|
1457
|
+
} else if (line && !line.startsWith("//") && !line.startsWith("/*") && !line.startsWith("*") && !line.startsWith("'use") && !line.startsWith('"use')) break;
|
|
1458
|
+
}
|
|
1459
|
+
const missing = imports.filter((i) => !text.includes(i));
|
|
1460
|
+
lines.splice(last + 1, 0, ...missing, ...block ? ["", block] : []);
|
|
1461
|
+
return lines.join("\n");
|
|
1462
|
+
}
|
|
1463
|
+
function editRootLayout(text, c, api, typescript) {
|
|
1464
|
+
if (text.includes("@zharp/react-native")) return null;
|
|
1465
|
+
const fn = /export default function (\w+)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{\n/.exec(text);
|
|
1466
|
+
if (!fn) return null;
|
|
1467
|
+
let out = afterImports(text, ["import { Zharp, useZharpNavigation } from '@zharp/react-native';"], initBlock(c, api, typescript));
|
|
1468
|
+
if (!/import\s*\{[^}]*\buseNavigationContainerRef\b[^}]*\}\s*from\s*['"]expo-router['"]/.test(out)) {
|
|
1469
|
+
const existing = /import\s*\{([^}]*)\}\s*from\s*(['"])expo-router\2;?/.exec(out);
|
|
1470
|
+
out = existing ? out.replace(existing[0], existing[0].replace(`{${existing[1]}}`, `{${existing[1].replace(/\s*$/, "")}, useNavigationContainerRef }`)) : afterImports(out, ["import { useNavigationContainerRef } from 'expo-router';"], "");
|
|
1471
|
+
}
|
|
1472
|
+
const again = /export default function (\w+)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{\n/.exec(out);
|
|
1473
|
+
return out.replace(again[0], `${again[0]} // Each screen the app shows, with the requests it made.
|
|
1474
|
+
useZharpNavigation(useNavigationContainerRef());
|
|
1475
|
+
`);
|
|
1476
|
+
}
|
|
1477
|
+
function gitIgnores(dir, file) {
|
|
1478
|
+
const ignore = read3(dir, ".gitignore") ?? "";
|
|
1479
|
+
const lines = ignore.split("\n").map((l) => l.trim());
|
|
1480
|
+
const name = file.split("/").pop();
|
|
1481
|
+
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");
|
|
1482
|
+
}
|
|
1483
|
+
function metroChange(project, plan, expo2) {
|
|
1484
|
+
const dir = project.dir;
|
|
1485
|
+
const path = first2(dir, ["metro.config.js", "metro.config.cjs"]);
|
|
1486
|
+
if (!path) {
|
|
1487
|
+
if (expo2) {
|
|
1488
|
+
plan.changes.push({
|
|
1489
|
+
path: "metro.config.js",
|
|
1490
|
+
kind: "create",
|
|
1491
|
+
note: "Expo\u2019s config, with release bundles stamped for readable errors",
|
|
1492
|
+
content: [
|
|
1493
|
+
"const { getDefaultConfig } = require('expo/metro-config');",
|
|
1494
|
+
"const { withZharpConfig } = require('@zharp/react-native/metro');",
|
|
1495
|
+
"",
|
|
1496
|
+
"module.exports = withZharpConfig(getDefaultConfig(__dirname));",
|
|
1497
|
+
""
|
|
1498
|
+
].join("\n")
|
|
1499
|
+
});
|
|
1500
|
+
} else {
|
|
1501
|
+
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);" });
|
|
1502
|
+
}
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
const text = read3(dir, path);
|
|
1506
|
+
const wrapped = wrapMetroConfig(text);
|
|
1507
|
+
if (wrapped) plan.changes.push({ path, kind: "edit", content: wrapped, note: "release bundles stamped for readable errors" });
|
|
1508
|
+
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 */);" });
|
|
1509
|
+
}
|
|
1510
|
+
function expo(project, c, api) {
|
|
1511
|
+
const plan = emptyPlan2();
|
|
1512
|
+
const dir = project.dir;
|
|
1513
|
+
plan.install = ["@zharp/react-native"];
|
|
1514
|
+
metroChange(project, plan, true);
|
|
1515
|
+
const appJson = read3(dir, "app.json");
|
|
1516
|
+
if (appJson && !first2(dir, ["app.config.js", "app.config.ts"])) {
|
|
1517
|
+
try {
|
|
1518
|
+
const config = JSON.parse(appJson);
|
|
1519
|
+
const root = config.expo ?? config;
|
|
1520
|
+
const plugins = Array.isArray(root.plugins) ? root.plugins : [];
|
|
1521
|
+
if (!plugins.some((p) => (Array.isArray(p) ? p[0] : p) === "@zharp/react-native")) {
|
|
1522
|
+
root.plugins = [...plugins, "@zharp/react-native"];
|
|
1523
|
+
plan.changes.push({ path: "app.json", kind: "edit", content: `${JSON.stringify(config, null, 2)}
|
|
1524
|
+
`, note: "the config plugin: builds upload their source maps" });
|
|
1525
|
+
}
|
|
1526
|
+
} catch {
|
|
1527
|
+
plan.manual.push({ path: "app.json", why: "add the config plugin", snippet: '"plugins": ["@zharp/react-native"]' });
|
|
1528
|
+
}
|
|
1529
|
+
} else {
|
|
1530
|
+
plan.manual.push({ path: "app.config", why: "add the config plugin", snippet: "plugins: ['@zharp/react-native']" });
|
|
1531
|
+
}
|
|
1532
|
+
const layout = first2(dir, ["app/_layout.tsx", "app/_layout.jsx", "app/_layout.js", "src/app/_layout.tsx", "src/app/_layout.jsx"]);
|
|
1533
|
+
const entry = (() => {
|
|
1534
|
+
const main2 = project.packageJson?.main;
|
|
1535
|
+
if (typeof main2 === "string" && !main2.includes("expo-router") && (0, import_node_fs10.existsSync)((0, import_node_path9.join)(dir, main2))) return main2;
|
|
1536
|
+
return first2(dir, ["index.ts", "index.tsx", "index.js", "App.tsx", "App.js"]);
|
|
1537
|
+
})();
|
|
1538
|
+
if (layout) {
|
|
1539
|
+
const edited = editRootLayout(read3(dir, layout), c, api, project.typescript);
|
|
1540
|
+
if (edited) plan.changes.push({ path: layout, kind: "edit", content: edited, note: "starts Zharp; screens from Expo Router" });
|
|
1541
|
+
} else if (entry) {
|
|
1542
|
+
const text = read3(dir, entry);
|
|
1543
|
+
if (!text.includes("@zharp/react-native")) {
|
|
1544
|
+
plan.changes.push({ path: entry, kind: "edit", content: afterImports(text, ["import { Zharp } from '@zharp/react-native';"], initBlock(c, api, project.typescript)), note: "starts Zharp" });
|
|
1545
|
+
}
|
|
1546
|
+
} else {
|
|
1547
|
+
plan.manual.push({ path: "your entry file", why: "start Zharp before the app renders", snippet: `import { Zharp } from '@zharp/react-native';
|
|
1548
|
+
|
|
1549
|
+
${initBlock(c, api, project.typescript)}` });
|
|
1550
|
+
}
|
|
1551
|
+
plan.env = { file: ".env.local", vars: { ZHARP_AUTH_TOKEN: c.uploadKey, ZHARP_APP: String(c.application.id), ...endpointOf(api) ? { ZHARP_URL: api.replace(/\/+$/, "") } : {} } };
|
|
1552
|
+
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}.`);
|
|
1553
|
+
plan.notes.push("EAS Update: after eas update (or npx expo export --source-maps), upload with npx zharp react-native upload --dir dist.");
|
|
1554
|
+
return plan;
|
|
1555
|
+
}
|
|
1556
|
+
function reactNative(project, c, api) {
|
|
1557
|
+
const plan = emptyPlan2();
|
|
1558
|
+
const dir = project.dir;
|
|
1559
|
+
plan.install = ["@zharp/react-native"];
|
|
1560
|
+
metroChange(project, plan, false);
|
|
1561
|
+
const entry = first2(dir, ["index.js", "index.ts", "index.tsx"]);
|
|
1562
|
+
if (entry) {
|
|
1563
|
+
const text = read3(dir, entry);
|
|
1564
|
+
if (!text.includes("@zharp/react-native")) {
|
|
1565
|
+
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" });
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
plan.notes.push("Screens: useZharpNavigation(navigationRef) next to your NavigationContainer (React Navigation).");
|
|
1569
|
+
const gradle = read3(dir, "android/app/build.gradle");
|
|
1570
|
+
if (gradle !== null) {
|
|
1571
|
+
const edited = addGradleLine(gradle);
|
|
1572
|
+
if (edited !== gradle) plan.changes.push({ path: "android/app/build.gradle", kind: "edit", content: edited, note: "release builds upload their source map" });
|
|
1573
|
+
const local = read3(dir, "android/local.properties") ?? "";
|
|
1574
|
+
if (!/^zharp\.authToken=/m.test(local)) {
|
|
1575
|
+
const lines = [`zharp.authToken=${c.uploadKey}`, `zharp.appId=${c.application.id}`];
|
|
1576
|
+
plan.changes.push({ path: "android/local.properties", kind: local ? "edit" : "create", content: `${local.replace(/\s*$/, local ? "\n" : "")}${lines.join("\n")}
|
|
1577
|
+
`, note: "the upload key (git ignores this file)" });
|
|
1578
|
+
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.");
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
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;
|
|
1582
|
+
if (ios) {
|
|
1583
|
+
const path = `ios/${ios}/project.pbxproj`;
|
|
1584
|
+
const text = read3(dir, path);
|
|
1585
|
+
const wired = text ? wireXcodeProject(text) : null;
|
|
1586
|
+
if (wired) plan.changes.push({ path, kind: "edit", content: wired, note: "the bundle phase writes and uploads its source map" });
|
|
1587
|
+
const envLocal = read3(dir, "ios/.xcode.env.local") ?? "";
|
|
1588
|
+
if (!/ZHARP_AUTH_TOKEN=/.test(envLocal)) {
|
|
1589
|
+
const lines = [`export ZHARP_AUTH_TOKEN=${c.uploadKey}`, `export ZHARP_APP=${c.application.id}`, ...endpointOf(api) ? [`export ZHARP_URL=${api.replace(/\/+$/, "")}`] : []];
|
|
1590
|
+
plan.changes.push({ path: "ios/.xcode.env.local", kind: envLocal ? "edit" : "create", content: `${envLocal.replace(/\s*$/, envLocal ? "\n" : "")}${lines.join("\n")}
|
|
1591
|
+
`, note: "the upload key (git ignores this file)" });
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
if (endpointOf(api) && gradle !== null) plan.notes.push(`Android builds upload to ${api}: set ZHARP_URL=${api.replace(/\/+$/, "")} when building.`);
|
|
1595
|
+
plan.notes.push("CI: set ZHARP_AUTH_TOKEN (the upload key) and ZHARP_APP for release builds.");
|
|
1596
|
+
return plan;
|
|
1597
|
+
}
|
|
1598
|
+
function reactNativePlanFor(project, c, api) {
|
|
1599
|
+
if (project.framework === "expo") return expo(project, c, api);
|
|
1600
|
+
if (project.framework === "react-native") return reactNative(project, c, api);
|
|
1601
|
+
return null;
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
// src/init/recipes.ts
|
|
1605
|
+
var DEFAULT_API2 = "https://api.zharp.io";
|
|
1606
|
+
var read4 = (dir, path) => {
|
|
1607
|
+
try {
|
|
1608
|
+
return (0, import_node_fs11.readFileSync)((0, import_node_path10.join)(dir, path), "utf8").replace(/\r\n/g, "\n");
|
|
1609
|
+
} catch {
|
|
1610
|
+
return null;
|
|
1611
|
+
}
|
|
1612
|
+
};
|
|
1613
|
+
var first3 = (dir, paths) => paths.find((p) => (0, import_node_fs11.existsSync)((0, import_node_path10.join)(dir, p))) ?? null;
|
|
844
1614
|
var mentionsZharp = (text) => !!text && /@zharp\//.test(text);
|
|
845
1615
|
function styled(text, line) {
|
|
846
1616
|
const imports = [...text.matchAll(/^import .*$/gm)].map((m) => m[0].trimEnd());
|
|
@@ -849,9 +1619,9 @@ function styled(text, line) {
|
|
|
849
1619
|
const quoted = double ? line.replace(/'([^'"]*)'/g, '"$1"') : line;
|
|
850
1620
|
return bare ? quoted.replace(/;$/, "") : quoted;
|
|
851
1621
|
}
|
|
852
|
-
function
|
|
1622
|
+
function endpointOf2(api) {
|
|
853
1623
|
const clean = api.replace(/\/+$/, "");
|
|
854
|
-
return clean ===
|
|
1624
|
+
return clean === DEFAULT_API2 ? null : `${clean}/api/v1/otlp`;
|
|
855
1625
|
}
|
|
856
1626
|
function wrapNextConfig(text, appId, esm) {
|
|
857
1627
|
if (/withZharp/.test(text)) return null;
|
|
@@ -898,7 +1668,7 @@ function nextjs(project, c, api) {
|
|
|
898
1668
|
const dir = project.dir;
|
|
899
1669
|
const ts = project.typescript;
|
|
900
1670
|
const plan = { install: ["@zharp/browser", "@zharp/node"], devInstall: ["@zharp/nextjs"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
|
|
901
|
-
const endpoint =
|
|
1671
|
+
const endpoint = endpointOf2(api);
|
|
902
1672
|
const instrumentationPath = `${project.appDir?.startsWith("src/") ? "src/" : ""}instrumentation.${ts ? "ts" : "js"}`;
|
|
903
1673
|
const instrumentation = [
|
|
904
1674
|
"export async function register() {",
|
|
@@ -917,17 +1687,17 @@ function nextjs(project, c, api) {
|
|
|
917
1687
|
"}",
|
|
918
1688
|
""
|
|
919
1689
|
].join("\n");
|
|
920
|
-
const existingInstrumentation =
|
|
1690
|
+
const existingInstrumentation = first3(dir, ["instrumentation.ts", "instrumentation.js", "src/instrumentation.ts", "src/instrumentation.js"]);
|
|
921
1691
|
if (!existingInstrumentation) plan.changes.push({ path: instrumentationPath, kind: "create", content: instrumentation, note: "starts Zharp on the server" });
|
|
922
|
-
else if (!mentionsZharp(
|
|
923
|
-
const configPath =
|
|
1692
|
+
else if (!mentionsZharp(read4(dir, existingInstrumentation))) plan.manual.push({ path: existingInstrumentation, why: "it already exists \u2014 add Zharp to it", snippet: instrumentation });
|
|
1693
|
+
const configPath = first3(dir, ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"]);
|
|
924
1694
|
if (!configPath) {
|
|
925
1695
|
plan.changes.push({ path: ts ? "next.config.ts" : "next.config.mjs", kind: "create", content: `import { withZharp } from '@zharp/nextjs';
|
|
926
1696
|
|
|
927
1697
|
export default withZharp({}, { app: ${c.application.id} });
|
|
928
1698
|
`, note: "source maps uploaded on build" });
|
|
929
1699
|
} else {
|
|
930
|
-
const text =
|
|
1700
|
+
const text = read4(dir, configPath) ?? "";
|
|
931
1701
|
const esm = /\.(ts|mjs)$/.test(configPath) || /^\s*(import|export)\s/m.test(text);
|
|
932
1702
|
const wrapped = mentionsZharp(text) ? null : wrapNextConfig(text, c.application.id, esm);
|
|
933
1703
|
if (wrapped) plan.changes.push({ path: configPath, kind: "edit", content: wrapped, note: "wrapped with withZharp" });
|
|
@@ -952,9 +1722,9 @@ export default withZharp(nextConfig, { app: ${c.application.id} });` });
|
|
|
952
1722
|
"}",
|
|
953
1723
|
""
|
|
954
1724
|
].join("\n");
|
|
955
|
-
if (!(0,
|
|
956
|
-
const layoutPath =
|
|
957
|
-
const layout = layoutPath ?
|
|
1725
|
+
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` });
|
|
1726
|
+
const layoutPath = first3(dir, [`${project.appDir}/layout.tsx`, `${project.appDir}/layout.jsx`, `${project.appDir}/layout.js`]);
|
|
1727
|
+
const layout = layoutPath ? read4(dir, layoutPath) : null;
|
|
958
1728
|
const edited = layout ? addToLayout(layout, "./zharp-client") : null;
|
|
959
1729
|
if (layoutPath && edited) plan.changes.push({ path: layoutPath, kind: "edit", content: edited, note: "renders <ZharpClient />" });
|
|
960
1730
|
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 +1797,17 @@ ${init}${next.slice(end).replace(/^\n+/, "\n")}`;
|
|
|
1027
1797
|
}
|
|
1028
1798
|
function viteReact(project, c, api) {
|
|
1029
1799
|
const dir = project.dir;
|
|
1030
|
-
const endpoint =
|
|
1800
|
+
const endpoint = endpointOf2(api);
|
|
1031
1801
|
const plan = { install: ["@zharp/browser"], devInstall: ["@zharp/vite-plugin"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
|
|
1032
|
-
const configPath =
|
|
1033
|
-
const config = configPath ?
|
|
1802
|
+
const configPath = first3(dir, ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]);
|
|
1803
|
+
const config = configPath ? read4(dir, configPath) : null;
|
|
1034
1804
|
const editedConfig = config ? addVitePlugin(config, c.application.id) : null;
|
|
1035
1805
|
if (configPath && editedConfig) plan.changes.push({ path: configPath, kind: "edit", content: editedConfig, note: "source maps uploaded on build" });
|
|
1036
1806
|
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
1807
|
\u2026
|
|
1038
1808
|
plugins: [react(), zharp({ app: ${c.application.id} })]` });
|
|
1039
|
-
const mainPath =
|
|
1040
|
-
const main2 = mainPath ?
|
|
1809
|
+
const mainPath = first3(dir, ["src/main.tsx", "src/main.jsx", "src/main.ts", "src/main.js", "src/index.tsx", "src/index.jsx"]);
|
|
1810
|
+
const main2 = mainPath ? read4(dir, mainPath) : null;
|
|
1041
1811
|
const editedMain = main2 ? addToViteMain(main2, c.application.serviceName, !!endpoint) : null;
|
|
1042
1812
|
if (mainPath && editedMain) plan.changes.push({ path: mainPath, kind: "edit", content: editedMain, note: "starts Zharp; React errors with their component stack" });
|
|
1043
1813
|
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 +1821,7 @@ plugins: [react(), zharp({ app: ${c.application.id} })]` });
|
|
|
1051
1821
|
}
|
|
1052
1822
|
function nestjs(project, c, api) {
|
|
1053
1823
|
const dir = project.dir;
|
|
1054
|
-
const endpoint =
|
|
1824
|
+
const endpoint = endpointOf2(api);
|
|
1055
1825
|
const plan = { install: ["@zharp/node"], devInstall: [], changes: [], manual: [], notes: [], env: { file: ".env", vars: {} } };
|
|
1056
1826
|
const ext = project.typescript ? "ts" : "js";
|
|
1057
1827
|
const instrumentPath = `src/instrument.${ext}`;
|
|
@@ -1063,12 +1833,12 @@ function nestjs(project, c, api) {
|
|
|
1063
1833
|
`Zharp.init({ service: '${c.application.serviceName}' });`,
|
|
1064
1834
|
""
|
|
1065
1835
|
].join("\n");
|
|
1066
|
-
if (!(0,
|
|
1067
|
-
const mainPath =
|
|
1068
|
-
const main2 = mainPath ?
|
|
1836
|
+
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" });
|
|
1837
|
+
const mainPath = first3(dir, [`src/main.${ext}`]);
|
|
1838
|
+
const main2 = mainPath ? read4(dir, mainPath) : null;
|
|
1069
1839
|
const esm = project.packageJson?.type === "module" || /from '\.{1,2}\/[^']+\.js'/.test(main2 ?? "");
|
|
1070
1840
|
if (esm) {
|
|
1071
|
-
const pkgText =
|
|
1841
|
+
const pkgText = read4(dir, "package.json");
|
|
1072
1842
|
const scripts = { ...project.packageJson?.scripts ?? {} };
|
|
1073
1843
|
const preload = "--import ./dist/instrument.js";
|
|
1074
1844
|
let changed = false;
|
|
@@ -1104,6 +1874,17 @@ ${main2}`, note: "loads it first" });
|
|
|
1104
1874
|
return plan;
|
|
1105
1875
|
}
|
|
1106
1876
|
function planFor(project, c, api) {
|
|
1877
|
+
const plan = basePlanFor(project, c, api);
|
|
1878
|
+
for (const ch of plan?.changes ?? []) {
|
|
1879
|
+
if (ch.kind !== "edit") continue;
|
|
1880
|
+
try {
|
|
1881
|
+
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");
|
|
1882
|
+
} catch {
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
return plan;
|
|
1886
|
+
}
|
|
1887
|
+
function basePlanFor(project, c, api) {
|
|
1107
1888
|
switch (project.framework) {
|
|
1108
1889
|
case "nextjs":
|
|
1109
1890
|
return nextjs(project, c, api);
|
|
@@ -1112,7 +1893,7 @@ function planFor(project, c, api) {
|
|
|
1112
1893
|
case "nestjs":
|
|
1113
1894
|
return nestjs(project, c, api);
|
|
1114
1895
|
default:
|
|
1115
|
-
return
|
|
1896
|
+
return reactNativePlanFor(project, c, api) ?? morePlanFor(project, c, api);
|
|
1116
1897
|
}
|
|
1117
1898
|
}
|
|
1118
1899
|
var GUIDES = {
|
|
@@ -1159,7 +1940,7 @@ function ignoredByGit(gitignore, file) {
|
|
|
1159
1940
|
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
1941
|
}
|
|
1161
1942
|
function installCommand(project, packages, dev, tarballs) {
|
|
1162
|
-
const specs = tarballs ? packages.map((p) => (0,
|
|
1943
|
+
const specs = tarballs ? packages.map((p) => (0, import_node_path11.join)(tarballs, `${p.replace("@", "").replace("/", "-")}.tgz`)) : packages;
|
|
1163
1944
|
switch (project.packageManager) {
|
|
1164
1945
|
case "pnpm":
|
|
1165
1946
|
return ["pnpm", ["add", ...dev ? ["-D"] : [], ...specs]];
|
|
@@ -1171,6 +1952,10 @@ function installCommand(project, packages, dev, tarballs) {
|
|
|
1171
1952
|
return ["npm", ["install", ...dev ? ["--save-dev"] : [], ...specs]];
|
|
1172
1953
|
}
|
|
1173
1954
|
}
|
|
1955
|
+
function installed(command) {
|
|
1956
|
+
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" });
|
|
1957
|
+
return found.status === 0;
|
|
1958
|
+
}
|
|
1174
1959
|
async function ask(question) {
|
|
1175
1960
|
const rl = (0, import_promises.createInterface)({ input: process.stdin, output: process.stdout });
|
|
1176
1961
|
try {
|
|
@@ -1216,14 +2001,15 @@ function showPlan(plan, c) {
|
|
|
1216
2001
|
say(`${green("\u25C6")} ${bold("These changes will be made:")}`);
|
|
1217
2002
|
const deps = [...plan.install, ...plan.devInstall];
|
|
1218
2003
|
if (deps.length) say(`${bar} ${green("+")} install ${deps.join(" ")}`);
|
|
2004
|
+
for (const cmd of plan.commands ?? []) say(`${bar} ${green("+")} ${cmd.label}`);
|
|
1219
2005
|
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(", "))}`);
|
|
2006
|
+
if (plan.env.file) say(`${bar} ${green("+")} ${bold(plan.env.file)} ${dim(Object.keys(plan.env.vars).join(", "))}`);
|
|
1221
2007
|
for (const m of plan.manual) say(`${bar} ${yellow("!")} ${m.path}: ${dim(`left as it is \u2014 ${m.why}`)}`);
|
|
1222
2008
|
void c;
|
|
1223
2009
|
}
|
|
1224
2010
|
async function runInit(options) {
|
|
1225
|
-
const dir = (0,
|
|
1226
|
-
const api = (options.url ?? process.env.ZHARP_URL ??
|
|
2011
|
+
const dir = (0, import_node_path11.resolve)(options.dir ?? process.cwd());
|
|
2012
|
+
const api = (options.url ?? process.env.ZHARP_URL ?? DEFAULT_API2).replace(/\/+$/, "");
|
|
1227
2013
|
const project = detect(dir);
|
|
1228
2014
|
say();
|
|
1229
2015
|
say(`${green("\u25C6")} ${bold("Zharp setup")}`);
|
|
@@ -1280,30 +2066,45 @@ ${bold(`\u2500\u2500 ${ch.path} ${ch.kind === "create" ? "(new)" : "(edited)"}`)
|
|
|
1280
2066
|
}
|
|
1281
2067
|
}
|
|
1282
2068
|
for (const ch of plan.changes) {
|
|
1283
|
-
const path = (0,
|
|
1284
|
-
(0,
|
|
1285
|
-
(0,
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
2069
|
+
const path = (0, import_node_path11.join)(dir, ch.path);
|
|
2070
|
+
(0, import_node_fs12.mkdirSync)((0, import_node_path11.dirname)(path), { recursive: true });
|
|
2071
|
+
(0, import_node_fs12.writeFileSync)(path, ch.content);
|
|
2072
|
+
}
|
|
2073
|
+
if (plan.env.file) {
|
|
2074
|
+
const envPath = (0, import_node_path11.join)(dir, plan.env.file);
|
|
2075
|
+
(0, import_node_fs12.writeFileSync)(envPath, mergeEnv((0, import_node_fs12.existsSync)(envPath) ? (0, import_node_fs12.readFileSync)(envPath, "utf8") : "", plan.env.vars));
|
|
2076
|
+
const gitignorePath = (0, import_node_path11.join)(dir, ".gitignore");
|
|
2077
|
+
if ((0, import_node_fs12.existsSync)((0, import_node_path11.join)(dir, ".git")) || (0, import_node_fs12.existsSync)(gitignorePath)) {
|
|
2078
|
+
const gitignore = (0, import_node_fs12.existsSync)(gitignorePath) ? (0, import_node_fs12.readFileSync)(gitignorePath, "utf8") : "";
|
|
2079
|
+
if (!ignoredByGit(gitignore, plan.env.file)) (0, import_node_fs12.writeFileSync)(gitignorePath, `${gitignore.replace(/\s*$/, "\n")}${plan.env.file}
|
|
1293
2080
|
`);
|
|
2081
|
+
}
|
|
1294
2082
|
}
|
|
1295
2083
|
say(`${green("\u25C7")} Files written`);
|
|
2084
|
+
const run = (command, args) => {
|
|
2085
|
+
if (!(0, import_node_path11.isAbsolute)(command) && !installed(command)) return "missing";
|
|
2086
|
+
say(`${bar} ${dim(`${command} ${args.join(" ")}`)}`);
|
|
2087
|
+
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" });
|
|
2088
|
+
if (result.error?.code === "ENOENT" || process.platform === "win32" && result.status === 9009 || process.platform !== "win32" && result.status === 127) return "missing";
|
|
2089
|
+
return result.status === 0 ? "ok" : "failed";
|
|
2090
|
+
};
|
|
1296
2091
|
for (const [packages, dev] of [[plan.install, false], [plan.devInstall, true]]) {
|
|
1297
2092
|
if (!packages.length) continue;
|
|
1298
2093
|
const [command, args] = installCommand(project, [...packages], dev, options.tarballs);
|
|
1299
|
-
|
|
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) {
|
|
2094
|
+
if (run(command, args) !== "ok") {
|
|
1302
2095
|
say(`${yellow("\u25A0")} The install failed. Run it yourself: ${command} ${args.join(" ")}`);
|
|
1303
2096
|
return 1;
|
|
1304
2097
|
}
|
|
1305
2098
|
}
|
|
1306
|
-
|
|
2099
|
+
const leftToDo = [];
|
|
2100
|
+
for (const cmd of plan.commands ?? []) {
|
|
2101
|
+
const [command, ...args] = cmd.argv;
|
|
2102
|
+
const result = run(command, args);
|
|
2103
|
+
if (result === "missing") leftToDo.push(`${cmd.argv.join(" ")} ${dim(`(${command} isn't installed here)`)}`);
|
|
2104
|
+
else if (result === "failed") leftToDo.push(cmd.argv.join(" "));
|
|
2105
|
+
}
|
|
2106
|
+
say(`${green("\u25C7")} ${leftToDo.length ? "Set up \u2014 finish with:" : "Packages installed"}`);
|
|
2107
|
+
for (const line of leftToDo) say(`${bar} ${line}`);
|
|
1307
2108
|
for (const m of plan.manual) {
|
|
1308
2109
|
say(bar);
|
|
1309
2110
|
say(`${yellow("!")} ${bold(m.path)} \u2014 ${m.why}:`);
|
|
@@ -1330,12 +2131,17 @@ Usage:
|
|
|
1330
2131
|
zharp dart-symbols upload <dir> --app <id> Flutter --split-debug-info output
|
|
1331
2132
|
[--obfuscation-map <file>] (and its obfuscation map)
|
|
1332
2133
|
zharp dsym upload <path> --app <id> A .dSYM, or a folder of them
|
|
2134
|
+
zharp react-native upload --bundle <file> --map <file> --app <id>
|
|
2135
|
+
A React Native release bundle's source map
|
|
2136
|
+
zharp react-native upload --dir dist --app <id> Every bundle an \`npx expo export\` wrote (EAS Update)
|
|
1333
2137
|
|
|
1334
2138
|
Options:
|
|
1335
2139
|
--app <id> Application ID (or ZHARP_APP)
|
|
1336
2140
|
--release <r> Release name to file the upload under (or ZHARP_RELEASE)
|
|
1337
2141
|
--include <glob> Only these files (repeatable; sourcemaps)
|
|
1338
2142
|
--exclude <glob> Not these files (repeatable; sourcemaps)
|
|
2143
|
+
--sources <dir> The project whose sources go with the symbols (dart-symbols, dsym; default: found)
|
|
2144
|
+
--no-sources Don't upload the app's sources (errors then show code only from a linked repo)
|
|
1339
2145
|
--delete-after Delete .map files after uploading them
|
|
1340
2146
|
--dry-run Show what would happen; change and send nothing
|
|
1341
2147
|
--url <url> Zharp API (default ZHARP_URL or https://api.zharp.io)
|
|
@@ -1359,6 +2165,11 @@ async function main(argv) {
|
|
|
1359
2165
|
release: { type: "string" },
|
|
1360
2166
|
uuid: { type: "string" },
|
|
1361
2167
|
"obfuscation-map": { type: "string" },
|
|
2168
|
+
sources: { type: "string" },
|
|
2169
|
+
bundle: { type: "string" },
|
|
2170
|
+
dir: { type: "string" },
|
|
2171
|
+
map: { type: "string" },
|
|
2172
|
+
"no-sources": { type: "boolean" },
|
|
1362
2173
|
include: { type: "string", multiple: true },
|
|
1363
2174
|
exclude: { type: "string", multiple: true },
|
|
1364
2175
|
"delete-after": { type: "boolean" },
|
|
@@ -1388,7 +2199,7 @@ async function main(argv) {
|
|
|
1388
2199
|
const release2 = values.release ?? process.env.ZHARP_RELEASE;
|
|
1389
2200
|
const needTarget = (what) => {
|
|
1390
2201
|
if (!target) fail(`${group} ${command} needs ${what}. See \`zharp --help\`.`);
|
|
1391
|
-
if (!(0,
|
|
2202
|
+
if (!(0, import_node_fs13.existsSync)(target)) fail(`${target} does not exist.`);
|
|
1392
2203
|
return target;
|
|
1393
2204
|
};
|
|
1394
2205
|
const connect2 = () => dryRun ? null : resolveConnection({ app: values.app, url: values.url });
|
|
@@ -1420,11 +2231,24 @@ async function main(argv) {
|
|
|
1420
2231
|
return;
|
|
1421
2232
|
}
|
|
1422
2233
|
case "dart-symbols upload": {
|
|
1423
|
-
|
|
2234
|
+
const sources = values["no-sources"] ? false : values.sources;
|
|
2235
|
+
await uploadDartSymbols(needTarget("the --split-debug-info directory"), connect2(), { release: release2, dryRun, logger, obfuscationMap: values["obfuscation-map"], sources });
|
|
2236
|
+
return;
|
|
2237
|
+
}
|
|
2238
|
+
case "react-native upload": {
|
|
2239
|
+
if (values.dir) {
|
|
2240
|
+
if (!(0, import_node_fs13.existsSync)(values.dir)) fail(`${values.dir} does not exist.`);
|
|
2241
|
+
await uploadReactNativeDir(values.dir, connect2(), { release: release2, dryRun, logger });
|
|
2242
|
+
return;
|
|
2243
|
+
}
|
|
2244
|
+
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>.");
|
|
2245
|
+
for (const file of [values.bundle, values.map]) if (!(0, import_node_fs13.existsSync)(file)) fail(`${file} does not exist.`);
|
|
2246
|
+
await uploadReactNative(values.bundle, values.map, connect2(), { release: release2, dryRun, logger });
|
|
1424
2247
|
return;
|
|
1425
2248
|
}
|
|
1426
2249
|
case "dsym upload": {
|
|
1427
|
-
|
|
2250
|
+
const sources = values["no-sources"] ? false : values.sources;
|
|
2251
|
+
await uploadDsyms(needTarget("a .dSYM bundle or a folder of them"), connect2(), { release: release2, dryRun, logger, sources });
|
|
1428
2252
|
return;
|
|
1429
2253
|
}
|
|
1430
2254
|
default:
|