reg-cli 0.18.16 → 0.19.0-rc0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +155 -46
  2. package/dist/cli.cjs +221 -0
  3. package/dist/cli.d.cts +1 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/cli.mjs +221 -0
  6. package/dist/entry.cjs +119 -0
  7. package/dist/entry.d.cts +15 -0
  8. package/dist/entry.d.mts +15 -0
  9. package/dist/entry.mjs +118 -0
  10. package/dist/index.cjs +212 -0
  11. package/dist/index.d.cts +52 -0
  12. package/dist/index.d.mts +52 -0
  13. package/dist/index.mjs +206 -0
  14. package/dist/progress-BB7D-xke.mjs +28 -0
  15. package/dist/progress-UOiKHaTY.cjs +33 -0
  16. package/dist/reg.wasm +0 -0
  17. package/dist/rolldown-runtime-D_mwlA32.cjs +43 -0
  18. package/{report/ui/dist/worker.js → dist/shared/report-worker.js} +859 -247
  19. package/dist/tracing-7HO8hac9.mjs +378 -0
  20. package/dist/tracing-DlLL541f.cjs +445 -0
  21. package/dist/worker.cjs +143 -0
  22. package/dist/worker.d.cts +1 -0
  23. package/dist/worker.d.mts +1 -0
  24. package/dist/worker.mjs +142 -0
  25. package/dist/ximgdiff-DzkRRnkW.mjs +41 -0
  26. package/dist/ximgdiff-wmW1BH1H.cjs +41 -0
  27. package/package.json +61 -112
  28. package/dist/.keep +0 -0
  29. package/dist/cli.js +0 -214
  30. package/dist/diff.js +0 -80
  31. package/dist/icon.js +0 -12
  32. package/dist/image-finder.js +0 -25
  33. package/dist/index.js +0 -200
  34. package/dist/log.js +0 -21
  35. package/dist/process-adaptor.js +0 -40
  36. package/dist/report.js +0 -170
  37. package/dist/tracing.js +0 -169
  38. package/report/assets/favicon_failure.png +0 -0
  39. package/report/assets/favicon_success.png +0 -0
  40. package/report/sample/actual/sample.png +0 -0
  41. package/report/sample/diff/sample.png +0 -0
  42. package/report/sample/expected/sample.png +0 -0
  43. package/report/ui/dist/report.js +0 -123
  44. package/report/ui/dist/style.css +0 -1
  45. package/template/template.html +0 -20
  46. /package/{template → dist/shared}/worker_pre.js +0 -0
@@ -0,0 +1,378 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { readFile } from "node:fs/promises";
5
+ import { dirname, join } from "node:path";
6
+ import { env } from "node:process";
7
+ //#region src/utils.ts
8
+ const isCJS = typeof __dirname !== "undefined";
9
+ const readWasm = () => {
10
+ return readFile(join(isCJS ? __dirname : path.dirname(fileURLToPath(import.meta.url)), "./reg.wasm"));
11
+ };
12
+ const resolveExtention = () => {
13
+ return isCJS ? "cjs" : "mjs";
14
+ };
15
+ /**
16
+ * Host environment variables intentionally forwarded into the Wasm sandbox.
17
+ * Everything else (shell secrets, CI credentials, AWS_*, NPM_TOKEN, ...) is
18
+ * filtered out.
19
+ */
20
+ const FORWARDED_ENV = [
21
+ "OTEL_ENABLED",
22
+ "JAEGER_ENABLED",
23
+ "OTEL_DEBUG",
24
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
25
+ "OTEL_EXPORTER_OTLP_PROTOCOL",
26
+ "OTEL_SERVICE_NAME",
27
+ "OTEL_TRACES_EXPORTER",
28
+ "OTEL_RESOURCE_ATTRIBUTES"
29
+ ];
30
+ /**
31
+ * Longest directory path that every input in `paths` lives under. Treats
32
+ * each path as a sequence of "/"-separated segments; absolute-vs-relative
33
+ * mixes fall back to '.'.
34
+ */
35
+ const commonAncestor = (paths) => {
36
+ const defined = paths.filter(Boolean);
37
+ if (defined.length === 0) return ".";
38
+ if (defined.length === 1) return defined[0];
39
+ const isAbs = (p) => p.startsWith("/");
40
+ const anyAbs = defined.some(isAbs);
41
+ const allAbs = defined.every(isAbs);
42
+ if (anyAbs && !allAbs) return ".";
43
+ const split = defined.map((p) => p.split("/").filter(Boolean));
44
+ const shortest = Math.min(...split.map((s) => s.length));
45
+ const common = [];
46
+ for (let i = 0; i < shortest; i++) {
47
+ const seg = split[0][i];
48
+ if (split.every((s) => s[i] === seg)) common.push(seg);
49
+ else break;
50
+ }
51
+ if (common.length === 0) return allAbs ? "/" : ".";
52
+ return (allAbs ? "/" : "") + common.join("/");
53
+ };
54
+ /**
55
+ * Compute the minimum-capability WASI sandbox for a given reg-cli invocation:
56
+ *
57
+ * - preopen only the smallest ancestor directory that covers every path
58
+ * this run touches (actualDir, expectedDir, diffDir, and the parents
59
+ * of --report / --json)
60
+ * - forward only an allowlisted subset of host env into Wasm
61
+ *
62
+ * Before this, entry.ts / worker.ts did `preopens: { './': './' }` which
63
+ * exposed the entire cwd (and therefore `.npmrc`, `.env`, `node_modules`,
64
+ * etc.) to whatever runs inside Wasm. Narrowing matters because reg-cli
65
+ * deliberately ingests untrusted images from CI and image decoders
66
+ * (libpng, libwebp, libjpeg) have a long history of RCE-class CVEs.
67
+ *
68
+ * Why a single common-ancestor and not one preopen per directory:
69
+ * On the `wasm32-wasip1-threads` target, Rust's libstd only enumerates
70
+ * the first preopen returned by WASI (`fd_prestat_get(3)` is queried but
71
+ * `fd_prestat_get(4)` is never issued). Until that's fixed upstream,
72
+ * registering one preopen per dir effectively hides every dir but the
73
+ * first. Picking the narrowest *single* ancestor that still contains
74
+ * every touched path gives us a real-world win without tripping the bug.
75
+ *
76
+ * Caveats (follow-ups, not in this PR):
77
+ * - Symlinks and FIFOs inside the preopened directory are still resolved
78
+ * by the host, so an attacker who can plant files under `./diff/` could
79
+ * still exfiltrate via an evil symlink pointing outside the sandbox.
80
+ * Addressing this needs host-side WASI changes.
81
+ * - `@tybys/wasm-util`'s WASI still runs on top of Node's `fs` with full
82
+ * privilege (`fs: fs as IFs`); we only constrain *what paths Wasm is
83
+ * allowed to name*, not what the host fs underneath could do.
84
+ * - One-preopen-per-dir limitation above.
85
+ */
86
+ const computeWasiSandbox = (argv) => {
87
+ const args = argv[0] === "--" ? argv.slice(1) : argv;
88
+ const positional = [];
89
+ for (let i = 0; i < args.length && positional.length < 3; i++) {
90
+ if (args[i].startsWith("--")) break;
91
+ positional.push(args[i]);
92
+ }
93
+ const flagValue = (name) => {
94
+ const i = args.indexOf(name);
95
+ return i >= 0 && i + 1 < args.length ? args[i + 1] : void 0;
96
+ };
97
+ const dirs = [];
98
+ for (const p of positional) if (p) dirs.push(p);
99
+ const report = flagValue("--report");
100
+ const json = flagValue("--json");
101
+ const junit = flagValue("--junit");
102
+ const from = flagValue("--from") ?? flagValue("-F");
103
+ if (report) dirs.push(dirname(report) || ".");
104
+ if (json) dirs.push(dirname(json) || ".");
105
+ if (junit) dirs.push(dirname(junit) || ".");
106
+ if (from) dirs.push(dirname(from) || ".");
107
+ const preopenRoot = commonAncestor(dirs) || ".";
108
+ const mapWasm = (p) => p === "." || p === "./" || p.startsWith("/") || p.startsWith("./") ? p : `./${p}`;
109
+ const preopens = { [mapWasm(preopenRoot)]: preopenRoot };
110
+ if (!preopenRoot || preopenRoot === "." || preopenRoot === "./") preopens["./"] = "./";
111
+ const env$1 = {};
112
+ for (const k of FORWARDED_ENV) {
113
+ const v = env[k];
114
+ if (v !== void 0) env$1[k] = v;
115
+ }
116
+ return {
117
+ preopens,
118
+ env: env$1
119
+ };
120
+ };
121
+ //#endregion
122
+ //#region src/tracing.ts
123
+ /**
124
+ * OpenTelemetry tracing utilities for reg-cli
125
+ *
126
+ * This module receives trace data from the Rust/WASM side and converts it
127
+ * to OpenTelemetry spans that can be exported to Jaeger or other backends.
128
+ *
129
+ * The @opentelemetry/* packages are declared as **optional peer
130
+ * dependencies** — they are loaded lazily inside `initTracing()` only when
131
+ * `OTEL_ENABLED=true` (or `JAEGER_ENABLED=true`). Default installs of this
132
+ * package therefore pay zero install or runtime cost for OTel.
133
+ */
134
+ const PKG_VERSION = (() => {
135
+ try {
136
+ return createRequire(import.meta.url)("../package.json").version ?? "unknown";
137
+ } catch {
138
+ return "unknown";
139
+ }
140
+ })();
141
+ let otel = null;
142
+ let provider = null;
143
+ let isInitialized = false;
144
+ let currentRootSpan = null;
145
+ let currentRootContext = null;
146
+ /**
147
+ * Check if tracing is enabled via environment variable
148
+ */
149
+ const isTracingEnabled = () => {
150
+ return process.env.OTEL_ENABLED === "true" || process.env.JAEGER_ENABLED === "true";
151
+ };
152
+ /**
153
+ * Lazily import the @opentelemetry/* packages. Returns null and prints a
154
+ * single warning if any are missing — keeps the CLI working without OTel
155
+ * installed even when the env vars are set.
156
+ */
157
+ const loadOtel = async () => {
158
+ if (otel) return otel;
159
+ try {
160
+ const [api, resources, sdkBase, sdkNode, exporter, semconv] = await Promise.all([
161
+ import("@opentelemetry/api"),
162
+ import("@opentelemetry/resources"),
163
+ import("@opentelemetry/sdk-trace-base"),
164
+ import("@opentelemetry/sdk-trace-node"),
165
+ import("@opentelemetry/exporter-trace-otlp-http"),
166
+ import("@opentelemetry/semantic-conventions")
167
+ ]);
168
+ otel = {
169
+ api,
170
+ resources,
171
+ sdkBase,
172
+ sdkNode,
173
+ exporter,
174
+ semconv
175
+ };
176
+ return otel;
177
+ } catch (err) {
178
+ const pkgs = [
179
+ "@opentelemetry/api",
180
+ "@opentelemetry/exporter-trace-otlp-http",
181
+ "@opentelemetry/resources",
182
+ "@opentelemetry/sdk-trace-base",
183
+ "@opentelemetry/sdk-trace-node",
184
+ "@opentelemetry/semantic-conventions"
185
+ ].join(" ");
186
+ console.warn(`[Tracing] OTEL_ENABLED is set but the @opentelemetry/* peer dependencies are not installed. Continuing without tracing. To enable, install the peers alongside reg-cli, e.g.:
187
+ npm i -g ${pkgs} # if reg-cli is installed globally\n npm i ${pkgs} # if reg-cli is a project dependency`);
188
+ if (process.env.OTEL_DEBUG === "true") console.warn("[Tracing] Import error:", err);
189
+ return null;
190
+ }
191
+ };
192
+ /**
193
+ * Initialize OpenTelemetry SDK
194
+ */
195
+ const initTracing = async () => {
196
+ if (!isTracingEnabled() || isInitialized) return;
197
+ const mods = await loadOtel();
198
+ if (!mods) return;
199
+ const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318/v1/traces";
200
+ const otlpExporter = new mods.exporter.OTLPTraceExporter({ url: otlpEndpoint });
201
+ provider = new mods.sdkNode.NodeTracerProvider({
202
+ resource: mods.resources.resourceFromAttributes({
203
+ [mods.semconv.ATTR_SERVICE_NAME]: "reg-cli",
204
+ [mods.semconv.ATTR_SERVICE_VERSION]: "0.18.10"
205
+ }),
206
+ spanProcessors: [new mods.sdkBase.BatchSpanProcessor(otlpExporter)]
207
+ });
208
+ provider.register();
209
+ isInitialized = true;
210
+ if (process.env.OTEL_DEBUG === "true") {
211
+ console.log("[Tracing] OpenTelemetry initialized");
212
+ console.log(`[Tracing] OTLP endpoint: ${otlpEndpoint}`);
213
+ }
214
+ };
215
+ /**
216
+ * Shutdown OpenTelemetry SDK gracefully
217
+ */
218
+ const shutdownTracing = async () => {
219
+ if (!provider || !isInitialized) return;
220
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] Starting SDK shutdown...");
221
+ try {
222
+ await provider.shutdown();
223
+ } catch (err) {
224
+ console.error("[Tracing] Error during shutdown:", err);
225
+ }
226
+ isInitialized = false;
227
+ provider = null;
228
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] OpenTelemetry SDK shut down");
229
+ };
230
+ /**
231
+ * Get the tracer instance
232
+ */
233
+ const getTracer = () => {
234
+ return otel.api.trace.getTracer("reg-cli", PKG_VERSION);
235
+ };
236
+ /**
237
+ * Start a root span and return context info to pass to Rust
238
+ */
239
+ const startRootSpan = (name) => {
240
+ if (!isTracingEnabled() || !isInitialized || !otel) return null;
241
+ currentRootSpan = getTracer().startSpan(name);
242
+ currentRootContext = otel.api.trace.setSpan(otel.api.ROOT_CONTEXT, currentRootSpan);
243
+ const spanContext = currentRootSpan.spanContext();
244
+ if (process.env.OTEL_DEBUG === "true") {
245
+ console.log(`[Tracing] Started root span: ${name}`);
246
+ console.log(`[Tracing] Trace ID: ${spanContext.traceId}`);
247
+ console.log(`[Tracing] Span ID: ${spanContext.spanId}`);
248
+ }
249
+ return {
250
+ traceId: spanContext.traceId,
251
+ spanId: spanContext.spanId
252
+ };
253
+ };
254
+ /**
255
+ * End the current root span
256
+ */
257
+ const endRootSpan = (success = true) => {
258
+ if (currentRootSpan && otel) {
259
+ if (success) currentRootSpan.setStatus({ code: otel.api.SpanStatusCode.OK });
260
+ else currentRootSpan.setStatus({ code: otel.api.SpanStatusCode.ERROR });
261
+ currentRootSpan.end();
262
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] Ended root span");
263
+ currentRootSpan = null;
264
+ currentRootContext = null;
265
+ }
266
+ };
267
+ /**
268
+ * Topologically sort spans so parents are always processed before children
269
+ */
270
+ const topologicalSortSpans = (spans) => {
271
+ const spanMap = /* @__PURE__ */ new Map();
272
+ const childrenMap = /* @__PURE__ */ new Map();
273
+ const rootSpans = [];
274
+ for (const span of spans) {
275
+ spanMap.set(span.span_id, span);
276
+ if (!span.parent_span_id) rootSpans.push(span.span_id);
277
+ else {
278
+ const children = childrenMap.get(span.parent_span_id) || [];
279
+ children.push(span.span_id);
280
+ childrenMap.set(span.parent_span_id, children);
281
+ }
282
+ }
283
+ if (process.env.OTEL_DEBUG === "true") {
284
+ console.log(`[Tracing] Total spans: ${spans.length}, Unique IDs in spanMap: ${spanMap.size}`);
285
+ console.log(`[Tracing] Root spans: ${rootSpans.join(", ")}`);
286
+ console.log(`[Tracing] All spans:`);
287
+ for (const span of spans) console.log(` ${span.span_id}: ${span.name} (parent: ${span.parent_span_id || "none"})`);
288
+ console.log(`[Tracing] Parent->Children map:`);
289
+ for (const [parent, children] of childrenMap.entries()) console.log(` ${parent} -> ${children.join(", ")}`);
290
+ }
291
+ const result = [];
292
+ const queue = [...rootSpans];
293
+ const visited = /* @__PURE__ */ new Set();
294
+ while (queue.length > 0) {
295
+ const spanId = queue.shift();
296
+ if (visited.has(spanId)) continue;
297
+ visited.add(spanId);
298
+ const span = spanMap.get(spanId);
299
+ if (span) {
300
+ result.push(span);
301
+ const children = childrenMap.get(spanId) || [];
302
+ queue.push(...children);
303
+ }
304
+ }
305
+ for (const span of spans) if (!visited.has(span.span_id)) {
306
+ if (process.env.OTEL_DEBUG === "true") console.log(`[Tracing] Orphan span: ${span.name} (id: ${span.span_id}, parent: ${span.parent_span_id})`);
307
+ result.push(span);
308
+ }
309
+ return result;
310
+ };
311
+ /**
312
+ * Convert Rust trace data to OpenTelemetry spans
313
+ *
314
+ * Since Rust spans have already ended by the time we receive them,
315
+ * we reconstruct them with their recorded timestamps.
316
+ */
317
+ const processRustTraceData = (traceData) => {
318
+ if (!isTracingEnabled() || !isInitialized || !otel) return;
319
+ const tracer = getTracer();
320
+ if (process.env.OTEL_DEBUG === "true") {
321
+ console.log(`[Tracing] Processing ${traceData.spans.length} spans from Rust`);
322
+ console.log(`[Tracing] JS parent context available: ${currentRootContext !== null}`);
323
+ }
324
+ const sortedSpans = topologicalSortSpans(traceData.spans);
325
+ const spanContextMap = /* @__PURE__ */ new Map();
326
+ for (const rustSpan of sortedSpans) {
327
+ const startTimeNs = rustSpan.start_time_ms * 1e6;
328
+ const endTimeNs = rustSpan.end_time_ms * 1e6;
329
+ let parentContext;
330
+ let parentInfo;
331
+ if (rustSpan.parent_span_id && spanContextMap.has(rustSpan.parent_span_id)) {
332
+ parentContext = spanContextMap.get(rustSpan.parent_span_id);
333
+ parentInfo = `rust parent: ${rustSpan.parent_span_id}`;
334
+ } else if (!rustSpan.parent_span_id && currentRootContext) {
335
+ parentContext = currentRootContext;
336
+ parentInfo = `js parent: ${currentRootSpan?.spanContext().spanId}`;
337
+ } else {
338
+ parentContext = currentRootContext || otel.api.ROOT_CONTEXT;
339
+ parentInfo = rustSpan.parent_span_id ? `orphan (parent ${rustSpan.parent_span_id} not found)` : "root (no js context)";
340
+ }
341
+ const span = tracer.startSpan(rustSpan.name, { startTime: [Math.floor(startTimeNs / 1e9), startTimeNs % 1e9] }, parentContext);
342
+ span.setAttribute("rust.target", rustSpan.target);
343
+ span.setAttribute("rust.level", rustSpan.level);
344
+ span.setAttribute("rust.span_id", rustSpan.span_id);
345
+ span.setAttribute("duration_ms", rustSpan.duration_ms);
346
+ for (const [key, value] of Object.entries(rustSpan.attributes)) span.setAttribute(`rust.${key}`, value);
347
+ if (rustSpan.status === "error") span.setStatus({
348
+ code: otel.api.SpanStatusCode.ERROR,
349
+ message: rustSpan.error_message || "Unknown error"
350
+ });
351
+ else span.setStatus({ code: otel.api.SpanStatusCode.OK });
352
+ span.end([Math.floor(endTimeNs / 1e9), endTimeNs % 1e9]);
353
+ const ctx = otel.api.trace.setSpan(parentContext, span);
354
+ spanContextMap.set(rustSpan.span_id, ctx);
355
+ if (process.env.OTEL_DEBUG === "true") console.log(`[Tracing] Created span: ${rustSpan.name} (${rustSpan.duration_ms}ms) [${parentInfo}] start=${rustSpan.start_time_ms}, end=${rustSpan.end_time_ms}`);
356
+ }
357
+ };
358
+ /**
359
+ * Convert worker-side timing events to OpenTelemetry spans attached under the
360
+ * current root span. Used to surface JS-bridge costs (Worker creation, wasm
361
+ * compile / instantiate, message round-trips) that Rust-side tracing cannot see.
362
+ */
363
+ const processWorkerSpans = (spans, workerLabel) => {
364
+ if (!isTracingEnabled() || !isInitialized || !otel || !spans?.length) return;
365
+ const tracer = getTracer();
366
+ const parentCtx = currentRootContext ?? otel.api.ROOT_CONTEXT;
367
+ for (const s of spans) {
368
+ const startNs = s.start_ms * 1e6;
369
+ const endNs = s.end_ms * 1e6;
370
+ const span = tracer.startSpan(s.name, { startTime: [Math.floor(startNs / 1e9), startNs % 1e9] }, parentCtx);
371
+ span.setAttribute("worker", s.worker_label ?? workerLabel);
372
+ span.setAttribute("duration_ms", s.end_ms - s.start_ms);
373
+ if (s.attributes) for (const [k, v] of Object.entries(s.attributes)) span.setAttribute(k, v);
374
+ span.end([Math.floor(endNs / 1e9), endNs % 1e9]);
375
+ }
376
+ };
377
+ //#endregion
378
+ export { processWorkerSpans as a, computeWasiSandbox as c, resolveExtention as d, processRustTraceData as i, isCJS as l, initTracing as n, shutdownTracing as o, isTracingEnabled as r, startRootSpan as s, endRootSpan as t, readWasm as u };