xovris 0.1.0 → 0.2.1

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.
@@ -1,19 +1,42 @@
1
- import "./src-DPO9_Gtz.js";
2
- import { i as gatedWrite } from "./gated-write-DRftDST4.js";
3
- import { join, sep } from "node:path";
1
+ import "./src-F88zycxp.js";
2
+ import { i as gatedWrite } from "./gated-write-C1W3tG1Z.js";
3
+ import { basename, dirname, join, sep } from "node:path";
4
4
  import { readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
5
5
  import { createHash } from "node:crypto";
6
6
 
7
7
  //#region src/sourcemaps.ts
8
8
  const MAX_FILES = 5e3;
9
9
  const MARK = /\/\/# debugId=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/;
10
- const register = (id) => `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&(g._xovrisDebugIds=g._xovrisDebugIds||{},g._xovrisDebugIds[s]="${id}")}catch(e){}}();`;
10
+ const register = (id) => `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&(g._xovrisDebugIds=g._xovrisDebugIds||{},g._xovrisDebugIds[s]="${id}",g._sentryDebugIds=g._sentryDebugIds||{},g._sentryDebugIds[s]="${id}")}catch(e){}}();`;
11
11
  /** A UUID drawn from the SHA-256 of the map's own bytes: building the same code twice marks it the same. */
12
12
  function debugIdFor(map) {
13
13
  const h = createHash("sha256").update(map).digest("hex");
14
14
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${"89ab"[parseInt(h[16], 16) % 4]}${h.slice(17, 20)}-${h.slice(20, 32)}`;
15
15
  }
16
16
  const OUTSIDE = "a link that does not stay inside the build folder: only files inside the folder given are read, marked and sent";
17
+ const HERMES = "compiled Hermes bytecode, which is never written into, and neither its map nor a packager map in the build names a debug ID - so no crash from this build can be matched to it. A Metro step that writes the debug ID into the bundle before Hermes compiles it gives it one (the metro.config.js wrapper of the React Native SDK the app sends with), and the next build is read as its own code";
18
+ const BUILT = /\.(js|mjs|cjs|bundle|jsbundle)$/;
19
+ const HBC = Buffer.from([
20
+ 198,
21
+ 31,
22
+ 188,
23
+ 3,
24
+ 193,
25
+ 3,
26
+ 25,
27
+ 31
28
+ ]);
29
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
30
+ /** The debug ID a bundler already wrote into the map (debugId, or debug_id), when it has one. */
31
+ function ownId(map) {
32
+ try {
33
+ const m = JSON.parse(map);
34
+ const id = String(m.debugId ?? m.debug_id ?? "").toLowerCase();
35
+ return UUID.test(id) ? id : null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
17
40
  /** The real place of a path when it lies inside the build folder; null when a link takes it out or leads nowhere. */
18
41
  function inside(root, p) {
19
42
  try {
@@ -29,7 +52,7 @@ async function writeInside(root, file, text) {
29
52
  await gatedWrite(root, file, text, "the built file");
30
53
  return true;
31
54
  }
32
- function builtFiles(root, dir, out, left, seen) {
55
+ function builtFiles(root, dir, out, left, seen, lone = [], packager = /* @__PURE__ */ new Map()) {
33
56
  for (const name of readdirSync(dir)) {
34
57
  if (out.length >= MAX_FILES || name === "node_modules" || name.startsWith(".git")) continue;
35
58
  const p = join(dir, name);
@@ -40,26 +63,75 @@ function builtFiles(root, dir, out, left, seen) {
40
63
  }
41
64
  if (seen.has(real)) continue;
42
65
  seen.add(real);
43
- if (statSync(real).isDirectory()) builtFiles(root, p, out, left, seen);
44
- else if (/\.(js|mjs|cjs)$/.test(name) && statSync(`${p}.map`, { throwIfNoEntry: false })?.isFile()) (inside(root, `${p}.map`) ? out : left).push(p);
66
+ if (statSync(real).isDirectory()) builtFiles(root, p, out, left, seen, lone, packager);
67
+ else if (name.endsWith(".packager.map")) {
68
+ const key = `${basename(dir)}/${name.slice(0, -13)}`;
69
+ packager.set(key, packager.has(key) ? null : p);
70
+ } else if (BUILT.test(name) && statSync(`${p}.map`, { throwIfNoEntry: false })?.isFile()) (inside(root, `${p}.map`) ? out : left).push(p);
71
+ else if (name.endsWith(".map") && BUILT.test(name.slice(0, -4)) && !statSync(p.slice(0, -4), { throwIfNoEntry: false })?.isFile()) lone.push(p);
45
72
  }
46
73
  }
47
74
  async function mark(dir) {
48
75
  const root = realpathSync(dir);
49
76
  const found = [];
50
- const left = [];
51
- builtFiles(root, dir, found, left, new Set([root]));
77
+ const outside = [];
78
+ const lone = [];
79
+ const packager = /* @__PURE__ */ new Map();
80
+ builtFiles(root, dir, found, outside, new Set([root]), lone, packager);
81
+ const idFor = async (mapFile, map) => {
82
+ const own = ownId(map);
83
+ if (own) return own;
84
+ const from = packager.get(`${basename(dirname(mapFile))}/${basename(mapFile).slice(0, -4)}`);
85
+ const id = from ? ownId(readFileSync(from, "utf8")) : null;
86
+ if (id) try {
87
+ await writeInside(root, mapFile, JSON.stringify({
88
+ ...JSON.parse(map),
89
+ debugId: id,
90
+ debug_id: id
91
+ }));
92
+ } catch {}
93
+ return id;
94
+ };
95
+ const left = outside.map((file) => ({
96
+ file,
97
+ why: OUTSIDE
98
+ }));
52
99
  const files = [];
100
+ for (const mapFile of lone) {
101
+ const id = await idFor(mapFile, readFileSync(mapFile, "utf8"));
102
+ if (id) files.push({
103
+ file: mapFile.slice(0, -4),
104
+ mapFile,
105
+ debugId: id
106
+ });
107
+ }
53
108
  for (const file of found) {
54
109
  const mapFile = `${file}.map`;
55
110
  const map = readFileSync(mapFile, "utf8");
56
- const js = readFileSync(file, "utf8");
111
+ const bytes = readFileSync(file);
112
+ if (bytes.subarray(0, HBC.length).equals(HBC)) {
113
+ const id = await idFor(mapFile, map);
114
+ if (id) files.push({
115
+ file,
116
+ mapFile,
117
+ debugId: id
118
+ });
119
+ else left.push({
120
+ file,
121
+ why: HERMES
122
+ });
123
+ continue;
124
+ }
125
+ const js = bytes.toString("utf8");
57
126
  const had = MARK.exec(js)?.[1];
58
- const debugId = had ?? debugIdFor(map);
127
+ const debugId = had ?? ownId(map) ?? debugIdFor(map);
59
128
  if (!had) {
60
129
  const at = js.lastIndexOf("//# sourceMappingURL=");
61
130
  if (!await writeInside(root, file, `${at >= 0 ? js.slice(0, at) : js.endsWith("\n") ? js : `${js}\n`}${register(debugId)}\n//# debugId=${debugId}\n${at >= 0 ? js.slice(at) : ""}`)) {
62
- left.push(file);
131
+ left.push({
132
+ file,
133
+ why: OUTSIDE
134
+ });
63
135
  continue;
64
136
  }
65
137
  try {
@@ -84,10 +156,7 @@ async function mark(dir) {
84
156
  /** Marks the build, then sends each map. Without the token or the project nothing is sent, and the result says so as a diagnosis. */
85
157
  async function uploadSourceMaps(o) {
86
158
  const { files, left } = await mark(o.dir);
87
- const outside = left.map((file) => ({
88
- file,
89
- why: OUTSIDE
90
- }));
159
+ const outside = left;
91
160
  if (!o.token || !o.project) {
92
161
  const lacks = !o.token ? "the source-map upload token (XOVRIS_BUILD_TOKEN)" : "its project id (XOVRIS_PROJECT)";
93
162
  return {
@@ -0,0 +1,118 @@
1
+ import { i as tokenFor, u as Api } from "./apicmd-BHGPPVbb.js";
2
+
3
+ //#region src/spend.ts
4
+ /** The ask as `xovris spend` takes it, or why it cannot be read: --since <n>d (1 to 31, the bill's own days) and --group-by. */
5
+ function spendOptions(a) {
6
+ const by = a.groupBy ?? "service";
7
+ if (![
8
+ "service",
9
+ "account",
10
+ "day"
11
+ ].includes(by)) return { problem: `Group the bill by service, account or day: xovris spend --group-by day - "${a.groupBy}" is none of them.` };
12
+ const m = a.since === null ? ["30d", "30"] : /^(\d{1,2})d$/.exec(a.since);
13
+ const days = m ? Number(m[1]) : NaN;
14
+ if (!Number.isInteger(days) || days < 1 || days > 31) return { problem: "Say how far back in days, 1 to 31 (the bill is read by day over the last 31): xovris spend --since 30d" };
15
+ return {
16
+ days,
17
+ by
18
+ };
19
+ }
20
+ /** Each day's spend from month-to-date totals at each day's end: the day's total less the day before's, a fall a new month from
21
+ * nothing, the first day read known only on a month's first. */
22
+ function daysOf(daily) {
23
+ return (daily ?? []).flatMap((d, i, all) => {
24
+ const prev = i ? all[i - 1] : null;
25
+ const spend = prev ? d.total >= prev.total ? d.total - prev.total : d.total : d.day.endsWith("-01") ? d.total : null;
26
+ return spend === null ? [] : [{
27
+ day: d.day,
28
+ spend: Math.round(spend * 100) / 100
29
+ }];
30
+ });
31
+ }
32
+ const money = (n, cur) => `${cur === "USD" ? "$" : `${cur} `}${n.toFixed(2)}`;
33
+ /** The bill as lines a person reads, one block per currency. */
34
+ function spendLines(conns, o, now) {
35
+ const bills = conns.flatMap((c) => c.firstRead?.bill ? [{
36
+ c,
37
+ b: c.firstRead.bill
38
+ }] : []);
39
+ if (!bills.length) return ["No cloud bill read yet - connect a cloud account on Cloud and Xovris reads its bill with it."];
40
+ const out = [];
41
+ const since = (/* @__PURE__ */ new Date(now.getTime() - (o.days - 1) * 864e5)).toISOString().slice(0, 10);
42
+ for (const cur of [...new Set(bills.map((x) => x.b.currency))]) {
43
+ const mine = bills.filter((x) => x.b.currency === cur);
44
+ const total = mine.reduce((n, x) => n + x.b.total, 0);
45
+ out.push(`${money(total, cur)} this month so far across ${mine.length} account${mine.length === 1 ? "" : "s"} (${cur})`);
46
+ const rows = [];
47
+ if (o.by === "account") for (const x of mine) rows.push([`${x.c.provider} ${x.c.accountId ?? x.c.id}`, x.b.total]);
48
+ if (o.by === "service") {
49
+ const by = /* @__PURE__ */ new Map();
50
+ const byDay = mine.every((x) => (x.b.byItem ?? []).every((i) => i.daily?.length));
51
+ for (const x of mine) for (const i of x.b.byItem ?? []) {
52
+ const v = byDay ? daysOf(i.daily).filter((d) => d.day >= since).reduce((n, d) => n + d.spend, 0) : i.amount ?? 0;
53
+ if (v > 0) by.set(i.name, (by.get(i.name) ?? 0) + v);
54
+ }
55
+ rows.push(...by);
56
+ out.push(byDay ? `By service over the last ${o.days} day${o.days === 1 ? "" : "s"}:` : "By service, this month so far (the bill is not read by day for every service):");
57
+ }
58
+ if (o.by === "day") {
59
+ const by = /* @__PURE__ */ new Map();
60
+ for (const x of mine) for (const d of daysOf(x.b.daily)) if (d.day >= since) by.set(d.day, (by.get(d.day) ?? 0) + d.spend);
61
+ rows.push(...[...by].sort((a, b) => a[0].localeCompare(b[0])));
62
+ out.push(rows.length ? `By day over the last ${o.days} day${o.days === 1 ? "" : "s"}:` : "Not read by day yet - the next read of the account adds its days.");
63
+ }
64
+ const sum = rows.reduce((n, r) => n + r[1], 0);
65
+ const ranked = o.by === "day" ? rows : [...rows].sort((a, b) => b[1] - a[1]);
66
+ const w = Math.max(0, ...ranked.map((r) => r[0].length));
67
+ for (const [name, v] of ranked) out.push(` ${name.padEnd(w)} ${money(v, cur).padStart(11)} ${sum > 0 ? `${Math.round(v / sum * 100)}%`.padStart(4) : ""}`);
68
+ if (o.by === "day" && rows.length) out.push(` ${money(sum / rows.length, cur)} on an average day`);
69
+ }
70
+ return out;
71
+ }
72
+ async function spendCommand(a, o, sys, secrets, io, now = /* @__PURE__ */ new Date()) {
73
+ const opts = spendOptions(a);
74
+ if ("problem" in opts) {
75
+ io.err(`${opts.problem}\n`);
76
+ return 2;
77
+ }
78
+ const token = await tokenFor(o.api);
79
+ if (!token) {
80
+ io.err("Not signed in. Run xovris login, or set XOVRIS_TOKEN to a key from Settings, Developers.\n");
81
+ return 1;
82
+ }
83
+ secrets.add(token);
84
+ const api = new Api(o.api, sys);
85
+ api.token = token;
86
+ let res;
87
+ try {
88
+ res = await api.raw("GET", "/cloud/connections", void 0, {});
89
+ } catch {
90
+ io.err(`${o.api} gave this computer no answer - run xovris spend again once its connection is back, or name another address with --api.\n`);
91
+ return 1;
92
+ }
93
+ const text = await res.text();
94
+ let body = null;
95
+ try {
96
+ body = text ? JSON.parse(text) : null;
97
+ } catch {}
98
+ if (res.status < 200 || res.status >= 300) {
99
+ const e = body?.error;
100
+ io.err(`${secrets.redact(e ? `${e.message ?? ""} ${e.nextStep ?? ""}`.trim() : text || `HTTP ${res.status}`)}\n`);
101
+ return 1;
102
+ }
103
+ const conns = body?.items ?? body?.connections ?? [];
104
+ if (a.json) {
105
+ io.out(`${secrets.redact(JSON.stringify(conns.map((c) => ({
106
+ id: c.id,
107
+ provider: c.provider,
108
+ accountId: c.accountId,
109
+ bill: c.firstRead?.bill ?? null
110
+ })), null, 2))}\n`);
111
+ return 0;
112
+ }
113
+ io.out(`${spendLines(conns, opts, now).join("\n")}\n`);
114
+ return 0;
115
+ }
116
+
117
+ //#endregion
118
+ export { daysOf, spendCommand, spendLines, spendOptions };