@ponbac/token-ledger 0.3.0 → 0.5.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/main.js CHANGED
@@ -35162,6 +35162,7 @@ function planHints() {
35162
35162
 
35163
35163
  // packages/core/src/ledger.ts
35164
35164
  var modifiedSlack = 36 * 60 * 60 * 1000;
35165
+ var historyFloor = Date.UTC(2020, 0, 1);
35165
35166
 
35166
35167
  class InvalidRequest extends exports_Schema.TaggedError()("InvalidRequest", {
35167
35168
  message: exports_Schema.String
@@ -35335,18 +35336,28 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35335
35336
  coverage
35336
35337
  });
35337
35338
  });
35338
- const syncPayload = exports_Effect.fn("Ledger.syncPayload")(function* (input, clientInput) {
35339
+ const payloadFrom = exports_Effect.fn("Ledger.payloadFrom")(function* (input, clientInput, history) {
35339
35340
  const request3 = yield* decode5(input);
35340
35341
  const client = yield* exports_Schema.decodeUnknownEffect(SyncClient)(clientInput).pipe(exports_Effect.mapError(() => new InvalidRequest({
35341
35342
  message: "Expected a machine UUID and label and a client version."
35342
35343
  })));
35343
- const window = hourRange(dayWindow(request3.since, request3.until, request3.timeZone));
35344
+ const requested = hourRange(dayWindow(request3.since, request3.until, request3.timeZone));
35345
+ const from = history ? Math.min(historyFloor, requested.start) : requested.start;
35344
35346
  const buckets = sessionBuckets(request3.pricing);
35345
35347
  const hints = planHints();
35346
- const coverage = yield* scan2(request3, window.start, (timestamp2) => timestamp2 >= window.start && timestamp2 < window.end ? timestamp2 : undefined, (record3, attribution) => buckets.add(record3, attribution.shareable ? attribution.project : unattributed), (plan) => hints.add(plan));
35348
+ let earliest = requested.start;
35349
+ const coverage = yield* scan2(request3, from, (timestamp2) => timestamp2 >= from && timestamp2 < requested.end ? timestamp2 : undefined, (record3, attribution, timestamp2) => {
35350
+ earliest = Math.min(earliest, timestamp2);
35351
+ buckets.add(record3, attribution.shareable ? attribution.project : unattributed);
35352
+ }, (plan) => {
35353
+ earliest = Math.min(earliest, plan.timestamp);
35354
+ hints.add(plan);
35355
+ });
35356
+ const since = earliest < requested.start ? exports_DateTime.formatIsoDate(exports_DateTime.setZone(exports_DateTime.makeUnsafe(earliest), request3.timeZone)) : request3.since;
35357
+ const window = since === request3.since ? requested : hourRange(dayWindow(since, request3.until, request3.timeZone));
35347
35358
  const summary = providerCoverage(coverage);
35348
35359
  const replaced = replacedProviders(summary);
35349
- return yield* SyncPayload.makeEffect({
35360
+ const payload = yield* SyncPayload.makeEffect({
35350
35361
  version: 1,
35351
35362
  machine: client.machine,
35352
35363
  clientVersion: client.version,
@@ -35368,8 +35379,13 @@ class Ledger extends exports_Context.Service()("token-ledger/Ledger") {
35368
35379
  }).pipe(exports_Effect.mapError(() => new InvalidRequest({
35369
35380
  message: "Report data must satisfy the sync payload contract."
35370
35381
  })));
35382
+ return { payload, since };
35383
+ });
35384
+ return Ledger.of({
35385
+ report,
35386
+ syncPayload: (request3, client) => exports_Effect.map(payloadFrom(request3, client, false), ({ payload }) => payload),
35387
+ historyPayload: (request3, client) => payloadFrom(request3, client, true)
35371
35388
  });
35372
- return Ledger.of({ report, syncPayload });
35373
35389
  }));
35374
35390
  }
35375
35391
  function acceptsFile(source, file2) {
@@ -42683,7 +42699,7 @@ var runWith2 = (command, config) => {
42683
42699
  // packages/cli/package.json
42684
42700
  var package_default = {
42685
42701
  name: "@ponbac/token-ledger",
42686
- version: "0.3.0",
42702
+ version: "0.5.0",
42687
42703
  private: true,
42688
42704
  type: "module",
42689
42705
  bin: {
@@ -42694,6 +42710,7 @@ var package_default = {
42694
42710
  "@token-ledger/core": "workspace:*",
42695
42711
  "cli-table3": "^0.6.5",
42696
42712
  effect: "4.0.0",
42713
+ "jsonc-parser": "^3.3.1",
42697
42714
  "wrap-ansi": "^10.0.2"
42698
42715
  },
42699
42716
  description: "Local AI token usage and API-equivalent cost reports by project",
@@ -42711,1363 +42728,2866 @@ var package_default = {
42711
42728
  url: "https://github.com/ponbac/token-ledger/issues"
42712
42729
  }
42713
42730
  };
42714
-
42715
- // packages/cli/src/format.ts
42716
- import { styleText } from "node:util";
42717
- var import_cli_table3 = __toESM(require_table(), 1);
42718
-
42719
- // node_modules/.bun/ansi-regex@6.3.0/node_modules/ansi-regex/index.js
42720
- function ansiRegex({ onlyFirst = false } = {}) {
42721
- const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
42722
- const osc = `(?:\\u001B\\][^\\u0007\\u001B\\u009C]*${ST})`;
42723
- const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
42724
- const pattern = `${osc}|${csi}`;
42725
- return new RegExp(pattern, onlyFirst ? undefined : "g");
42726
- }
42727
-
42728
- // node_modules/.bun/strip-ansi@7.2.0/node_modules/strip-ansi/index.js
42729
- var regex = ansiRegex();
42730
- function stripAnsi2(string4) {
42731
- if (typeof string4 !== "string") {
42732
- throw new TypeError(`Expected a \`string\`, got \`${typeof string4}\``);
42731
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
42732
+ function createScanner(text2, ignoreTrivia = false) {
42733
+ const len = text2.length;
42734
+ let pos = 0, value5 = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
42735
+ function scanHexDigits(count2, exact) {
42736
+ let digits = 0;
42737
+ let value6 = 0;
42738
+ while (digits < count2 || !exact) {
42739
+ let ch = text2.charCodeAt(pos);
42740
+ if (ch >= 48 && ch <= 57) {
42741
+ value6 = value6 * 16 + ch - 48;
42742
+ } else if (ch >= 65 && ch <= 70) {
42743
+ value6 = value6 * 16 + ch - 65 + 10;
42744
+ } else if (ch >= 97 && ch <= 102) {
42745
+ value6 = value6 * 16 + ch - 97 + 10;
42746
+ } else {
42747
+ break;
42748
+ }
42749
+ pos++;
42750
+ digits++;
42751
+ }
42752
+ if (digits < count2) {
42753
+ value6 = -1;
42754
+ }
42755
+ return value6;
42733
42756
  }
42734
- if (!string4.includes("\x1B") && !string4.includes("›")) {
42735
- return string4;
42757
+ function setPosition(newPosition) {
42758
+ pos = newPosition;
42759
+ value5 = "";
42760
+ tokenOffset = 0;
42761
+ token = 16;
42762
+ scanError = 0;
42736
42763
  }
42737
- return string4.replace(regex, "");
42738
- }
42739
-
42740
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup-data.js
42741
- var ambiguousMinimalCodePoint = 161;
42742
- var ambiguousMaximumCodePoint = 1114109;
42743
- var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
42744
- var fullwidthMinimalCodePoint = 12288;
42745
- var fullwidthMaximumCodePoint = 65510;
42746
- var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
42747
- var wideMinimalCodePoint = 4352;
42748
- var wideMaximumCodePoint = 262141;
42749
- var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101594, 101631, 101664, 101760, 101874, 101888, 102801, 102816, 102866, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110888, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110952, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127406, 127406, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128729, 128732, 128735, 128747, 128748, 128756, 128764, 128986, 128986, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129734, 129736, 129736, 129740, 129757, 129759, 129771, 129775, 129786, 131072, 196605, 196608, 262141];
42750
-
42751
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/utilities.js
42752
- var isInRange = (ranges, codePoint) => {
42753
- let low = 0;
42754
- let high = Math.floor(ranges.length / 2) - 1;
42755
- while (low <= high) {
42756
- const mid = Math.floor((low + high) / 2);
42757
- const i = mid * 2;
42758
- if (codePoint < ranges[i]) {
42759
- high = mid - 1;
42760
- } else if (codePoint > ranges[i + 1]) {
42761
- low = mid + 1;
42764
+ function scanNumber() {
42765
+ let start = pos;
42766
+ if (text2.charCodeAt(pos) === 48) {
42767
+ pos++;
42762
42768
  } else {
42763
- return true;
42769
+ pos++;
42770
+ while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42771
+ pos++;
42772
+ }
42764
42773
  }
42765
- }
42766
- return false;
42767
- };
42768
-
42769
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup.js
42770
- var commonCjkCodePoint = 19968;
42771
- var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
42772
- function findWideFastPathRange(ranges) {
42773
- let fastPathStart = ranges[0];
42774
- let fastPathEnd = ranges[1];
42775
- for (let index2 = 0;index2 < ranges.length; index2 += 2) {
42776
- const start = ranges[index2];
42777
- const end3 = ranges[index2 + 1];
42778
- if (commonCjkCodePoint >= start && commonCjkCodePoint <= end3) {
42779
- return [start, end3];
42774
+ if (pos < text2.length && text2.charCodeAt(pos) === 46) {
42775
+ pos++;
42776
+ if (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42777
+ pos++;
42778
+ while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42779
+ pos++;
42780
+ }
42781
+ } else {
42782
+ scanError = 3;
42783
+ return text2.substring(start, pos);
42784
+ }
42780
42785
  }
42781
- if (end3 - start > fastPathEnd - fastPathStart) {
42782
- fastPathStart = start;
42783
- fastPathEnd = end3;
42786
+ let end3 = pos;
42787
+ if (pos < text2.length && (text2.charCodeAt(pos) === 69 || text2.charCodeAt(pos) === 101)) {
42788
+ pos++;
42789
+ if (pos < text2.length && text2.charCodeAt(pos) === 43 || text2.charCodeAt(pos) === 45) {
42790
+ pos++;
42791
+ }
42792
+ if (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42793
+ pos++;
42794
+ while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42795
+ pos++;
42796
+ }
42797
+ end3 = pos;
42798
+ } else {
42799
+ scanError = 3;
42800
+ }
42784
42801
  }
42802
+ return text2.substring(start, end3);
42785
42803
  }
42786
- return [fastPathStart, fastPathEnd];
42787
- }
42788
- var isAmbiguous = (codePoint) => {
42789
- if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) {
42790
- return false;
42804
+ function scanString() {
42805
+ let result6 = "", start = pos;
42806
+ while (true) {
42807
+ if (pos >= len) {
42808
+ result6 += text2.substring(start, pos);
42809
+ scanError = 2;
42810
+ break;
42811
+ }
42812
+ const ch = text2.charCodeAt(pos);
42813
+ if (ch === 34) {
42814
+ result6 += text2.substring(start, pos);
42815
+ pos++;
42816
+ break;
42817
+ }
42818
+ if (ch === 92) {
42819
+ result6 += text2.substring(start, pos);
42820
+ pos++;
42821
+ if (pos >= len) {
42822
+ scanError = 2;
42823
+ break;
42824
+ }
42825
+ const ch2 = text2.charCodeAt(pos++);
42826
+ switch (ch2) {
42827
+ case 34:
42828
+ result6 += '"';
42829
+ break;
42830
+ case 92:
42831
+ result6 += "\\";
42832
+ break;
42833
+ case 47:
42834
+ result6 += "/";
42835
+ break;
42836
+ case 98:
42837
+ result6 += "\b";
42838
+ break;
42839
+ case 102:
42840
+ result6 += "\f";
42841
+ break;
42842
+ case 110:
42843
+ result6 += `
42844
+ `;
42845
+ break;
42846
+ case 114:
42847
+ result6 += "\r";
42848
+ break;
42849
+ case 116:
42850
+ result6 += "\t";
42851
+ break;
42852
+ case 117:
42853
+ const ch3 = scanHexDigits(4, true);
42854
+ if (ch3 >= 0) {
42855
+ result6 += String.fromCharCode(ch3);
42856
+ } else {
42857
+ scanError = 4;
42858
+ }
42859
+ break;
42860
+ default:
42861
+ scanError = 5;
42862
+ }
42863
+ start = pos;
42864
+ continue;
42865
+ }
42866
+ if (ch >= 0 && ch <= 31) {
42867
+ if (isLineBreak3(ch)) {
42868
+ result6 += text2.substring(start, pos);
42869
+ scanError = 2;
42870
+ break;
42871
+ } else {
42872
+ scanError = 6;
42873
+ }
42874
+ }
42875
+ pos++;
42876
+ }
42877
+ return result6;
42791
42878
  }
42792
- return isInRange(ambiguousRanges, codePoint);
42793
- };
42794
- var isFullwidth = (codePoint) => {
42795
- if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) {
42796
- return false;
42879
+ function scanNext() {
42880
+ value5 = "";
42881
+ scanError = 0;
42882
+ tokenOffset = pos;
42883
+ lineStartOffset = lineNumber;
42884
+ prevTokenLineStartOffset = tokenLineStartOffset;
42885
+ if (pos >= len) {
42886
+ tokenOffset = len;
42887
+ return token = 17;
42888
+ }
42889
+ let code = text2.charCodeAt(pos);
42890
+ if (isWhiteSpace(code)) {
42891
+ do {
42892
+ pos++;
42893
+ value5 += String.fromCharCode(code);
42894
+ code = text2.charCodeAt(pos);
42895
+ } while (isWhiteSpace(code));
42896
+ return token = 15;
42897
+ }
42898
+ if (isLineBreak3(code)) {
42899
+ pos++;
42900
+ value5 += String.fromCharCode(code);
42901
+ if (code === 13 && text2.charCodeAt(pos) === 10) {
42902
+ pos++;
42903
+ value5 += `
42904
+ `;
42905
+ }
42906
+ lineNumber++;
42907
+ tokenLineStartOffset = pos;
42908
+ return token = 14;
42909
+ }
42910
+ switch (code) {
42911
+ case 123:
42912
+ pos++;
42913
+ return token = 1;
42914
+ case 125:
42915
+ pos++;
42916
+ return token = 2;
42917
+ case 91:
42918
+ pos++;
42919
+ return token = 3;
42920
+ case 93:
42921
+ pos++;
42922
+ return token = 4;
42923
+ case 58:
42924
+ pos++;
42925
+ return token = 6;
42926
+ case 44:
42927
+ pos++;
42928
+ return token = 5;
42929
+ case 34:
42930
+ pos++;
42931
+ value5 = scanString();
42932
+ return token = 10;
42933
+ case 47:
42934
+ const start = pos - 1;
42935
+ if (text2.charCodeAt(pos + 1) === 47) {
42936
+ pos += 2;
42937
+ while (pos < len) {
42938
+ if (isLineBreak3(text2.charCodeAt(pos))) {
42939
+ break;
42940
+ }
42941
+ pos++;
42942
+ }
42943
+ value5 = text2.substring(start, pos);
42944
+ return token = 12;
42945
+ }
42946
+ if (text2.charCodeAt(pos + 1) === 42) {
42947
+ pos += 2;
42948
+ const safeLength = len - 1;
42949
+ let commentClosed = false;
42950
+ while (pos < safeLength) {
42951
+ const ch = text2.charCodeAt(pos);
42952
+ if (ch === 42 && text2.charCodeAt(pos + 1) === 47) {
42953
+ pos += 2;
42954
+ commentClosed = true;
42955
+ break;
42956
+ }
42957
+ pos++;
42958
+ if (isLineBreak3(ch)) {
42959
+ if (ch === 13 && text2.charCodeAt(pos) === 10) {
42960
+ pos++;
42961
+ }
42962
+ lineNumber++;
42963
+ tokenLineStartOffset = pos;
42964
+ }
42965
+ }
42966
+ if (!commentClosed) {
42967
+ pos++;
42968
+ scanError = 1;
42969
+ }
42970
+ value5 = text2.substring(start, pos);
42971
+ return token = 13;
42972
+ }
42973
+ value5 += String.fromCharCode(code);
42974
+ pos++;
42975
+ return token = 16;
42976
+ case 45:
42977
+ value5 += String.fromCharCode(code);
42978
+ pos++;
42979
+ if (pos === len || !isDigit(text2.charCodeAt(pos))) {
42980
+ return token = 16;
42981
+ }
42982
+ case 48:
42983
+ case 49:
42984
+ case 50:
42985
+ case 51:
42986
+ case 52:
42987
+ case 53:
42988
+ case 54:
42989
+ case 55:
42990
+ case 56:
42991
+ case 57:
42992
+ value5 += scanNumber();
42993
+ return token = 11;
42994
+ default:
42995
+ while (pos < len && isUnknownContentCharacter(code)) {
42996
+ pos++;
42997
+ code = text2.charCodeAt(pos);
42998
+ }
42999
+ if (tokenOffset !== pos) {
43000
+ value5 = text2.substring(tokenOffset, pos);
43001
+ switch (value5) {
43002
+ case "true":
43003
+ return token = 8;
43004
+ case "false":
43005
+ return token = 9;
43006
+ case "null":
43007
+ return token = 7;
43008
+ }
43009
+ return token = 16;
43010
+ }
43011
+ value5 += String.fromCharCode(code);
43012
+ pos++;
43013
+ return token = 16;
43014
+ }
42797
43015
  }
42798
- return isInRange(fullwidthRanges, codePoint);
42799
- };
42800
- var isWide = (codePoint) => {
42801
- if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
43016
+ function isUnknownContentCharacter(code) {
43017
+ if (isWhiteSpace(code) || isLineBreak3(code)) {
43018
+ return false;
43019
+ }
43020
+ switch (code) {
43021
+ case 125:
43022
+ case 93:
43023
+ case 123:
43024
+ case 91:
43025
+ case 34:
43026
+ case 58:
43027
+ case 44:
43028
+ case 47:
43029
+ return false;
43030
+ }
42802
43031
  return true;
42803
43032
  }
42804
- if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) {
42805
- return false;
43033
+ function scanNextNonTrivia() {
43034
+ let result6;
43035
+ do {
43036
+ result6 = scanNext();
43037
+ } while (result6 >= 12 && result6 <= 15);
43038
+ return result6;
43039
+ }
43040
+ return {
43041
+ setPosition,
43042
+ getPosition: () => pos,
43043
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
43044
+ getToken: () => token,
43045
+ getTokenValue: () => value5,
43046
+ getTokenOffset: () => tokenOffset,
43047
+ getTokenLength: () => pos - tokenOffset,
43048
+ getTokenStartLine: () => lineStartOffset,
43049
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
43050
+ getTokenError: () => scanError
43051
+ };
43052
+ }
43053
+ function isWhiteSpace(ch) {
43054
+ return ch === 32 || ch === 9;
43055
+ }
43056
+ function isLineBreak3(ch) {
43057
+ return ch === 10 || ch === 13;
43058
+ }
43059
+ function isDigit(ch) {
43060
+ return ch >= 48 && ch <= 57;
43061
+ }
43062
+ var CharacterCodes;
43063
+ (function(CharacterCodes2) {
43064
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
43065
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
43066
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
43067
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
43068
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
43069
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
43070
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
43071
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
43072
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
43073
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
43074
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
43075
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
43076
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
43077
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
43078
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
43079
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
43080
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
43081
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
43082
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
43083
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
43084
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
43085
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
43086
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
43087
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
43088
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
43089
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
43090
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
43091
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
43092
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
43093
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
43094
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
43095
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
43096
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
43097
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
43098
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
43099
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
43100
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
43101
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
43102
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
43103
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
43104
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
43105
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
43106
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
43107
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
43108
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
43109
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
43110
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
43111
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
43112
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
43113
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
43114
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
43115
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
43116
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
43117
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
43118
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
43119
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
43120
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
43121
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
43122
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
43123
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
43124
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
43125
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
43126
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
43127
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
43128
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
43129
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
43130
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
43131
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
43132
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
43133
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
43134
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
43135
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
43136
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
43137
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
43138
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
43139
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
43140
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
43141
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
43142
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
43143
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
43144
+ })(CharacterCodes || (CharacterCodes = {}));
43145
+
43146
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
43147
+ var cachedSpaces = new Array(20).fill(0).map((_, index2) => {
43148
+ return " ".repeat(index2);
43149
+ });
43150
+ var maxCachedValues = 200;
43151
+ var cachedBreakLinesWithSpaces = {
43152
+ " ": {
43153
+ "\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43154
+ return `
43155
+ ` + " ".repeat(index2);
43156
+ }),
43157
+ "\r": new Array(maxCachedValues).fill(0).map((_, index2) => {
43158
+ return "\r" + " ".repeat(index2);
43159
+ }),
43160
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43161
+ return `\r
43162
+ ` + " ".repeat(index2);
43163
+ })
43164
+ },
43165
+ "\t": {
43166
+ "\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43167
+ return `
43168
+ ` + "\t".repeat(index2);
43169
+ }),
43170
+ "\r": new Array(maxCachedValues).fill(0).map((_, index2) => {
43171
+ return "\r" + "\t".repeat(index2);
43172
+ }),
43173
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43174
+ return `\r
43175
+ ` + "\t".repeat(index2);
43176
+ })
42806
43177
  }
42807
- return isInRange(wideRanges, codePoint);
42808
43178
  };
42809
43179
 
42810
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/index.js
42811
- function validate3(codePoint) {
42812
- if (!Number.isSafeInteger(codePoint)) {
42813
- throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
43180
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
43181
+ var ParseOptions;
43182
+ (function(ParseOptions2) {
43183
+ ParseOptions2.DEFAULT = {
43184
+ allowTrailingComma: false
43185
+ };
43186
+ })(ParseOptions || (ParseOptions = {}));
43187
+ function parseTree(text2, errors = [], options3 = ParseOptions.DEFAULT) {
43188
+ let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: undefined };
43189
+ function ensurePropertyComplete(endOffset) {
43190
+ if (currentParent.type === "property") {
43191
+ currentParent.length = endOffset - currentParent.offset;
43192
+ currentParent = currentParent.parent;
43193
+ }
42814
43194
  }
42815
- }
42816
- function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
42817
- validate3(codePoint);
42818
- if (isFullwidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
42819
- return 2;
43195
+ function onValue(valueNode) {
43196
+ currentParent.children.push(valueNode);
43197
+ return valueNode;
42820
43198
  }
42821
- return 1;
43199
+ const visitor = {
43200
+ onObjectBegin: (offset) => {
43201
+ currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
43202
+ },
43203
+ onObjectProperty: (name, offset, length) => {
43204
+ currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
43205
+ currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
43206
+ },
43207
+ onObjectEnd: (offset, length) => {
43208
+ ensurePropertyComplete(offset + length);
43209
+ currentParent.length = offset + length - currentParent.offset;
43210
+ currentParent = currentParent.parent;
43211
+ ensurePropertyComplete(offset + length);
43212
+ },
43213
+ onArrayBegin: (offset, length) => {
43214
+ currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
43215
+ },
43216
+ onArrayEnd: (offset, length) => {
43217
+ currentParent.length = offset + length - currentParent.offset;
43218
+ currentParent = currentParent.parent;
43219
+ ensurePropertyComplete(offset + length);
43220
+ },
43221
+ onLiteralValue: (value5, offset, length) => {
43222
+ onValue({ type: getNodeType(value5), offset, length, parent: currentParent, value: value5 });
43223
+ ensurePropertyComplete(offset + length);
43224
+ },
43225
+ onSeparator: (sep, offset, length) => {
43226
+ if (currentParent.type === "property") {
43227
+ if (sep === ":") {
43228
+ currentParent.colonOffset = offset;
43229
+ } else if (sep === ",") {
43230
+ ensurePropertyComplete(offset);
43231
+ }
43232
+ }
43233
+ },
43234
+ onError: (error2, offset, length) => {
43235
+ errors.push({ error: error2, offset, length });
43236
+ }
43237
+ };
43238
+ visit(text2, visitor, options3);
43239
+ const result6 = currentParent.children[0];
43240
+ if (result6) {
43241
+ delete result6.parent;
43242
+ }
43243
+ return result6;
42822
43244
  }
42823
-
42824
- // node_modules/.bun/string-width@8.2.2/node_modules/string-width/index.js
42825
- var segmenter = new Intl.Segmenter;
42826
- var zeroWidthClusterRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Nonspacing_Mark}|\p{Enclosing_Mark}|\p{Surrogate})+$/v;
42827
- var leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]+/v;
42828
- var spacingMarkRegex = /\p{Spacing_Mark}/v;
42829
- var rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
42830
- var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
42831
- var extendedPictographicRegex = /\p{Extended_Pictographic}/gu;
42832
- function isDoubleWidthNonRgiEmojiSequence(segment) {
42833
- if (segment.length > 50) {
42834
- return false;
43245
+ function getNodeValue(node) {
43246
+ switch (node.type) {
43247
+ case "array":
43248
+ return node.children.map(getNodeValue);
43249
+ case "object":
43250
+ const obj = Object.create(null);
43251
+ for (let prop of node.children) {
43252
+ const valueNode = prop.children[1];
43253
+ if (valueNode) {
43254
+ obj[prop.children[0].value] = getNodeValue(valueNode);
43255
+ }
43256
+ }
43257
+ return obj;
43258
+ case "null":
43259
+ case "string":
43260
+ case "number":
43261
+ case "boolean":
43262
+ return node.value;
43263
+ default:
43264
+ return;
42835
43265
  }
42836
- if (unqualifiedKeycapRegex.test(segment)) {
42837
- return true;
43266
+ }
43267
+ function visit(text2, visitor, options3 = ParseOptions.DEFAULT) {
43268
+ const _scanner = createScanner(text2, false);
43269
+ const _jsonPath = [];
43270
+ let suppressedCallbacks = 0;
43271
+ function toNoArgVisit(visitFunction) {
43272
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
42838
43273
  }
42839
- if (segment.includes("‍")) {
42840
- const pictographics = segment.match(extendedPictographicRegex);
42841
- return pictographics !== null && pictographics.length >= 2;
43274
+ function toOneArgVisit(visitFunction) {
43275
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
42842
43276
  }
42843
- return false;
42844
- }
42845
- function baseVisible(segment) {
42846
- return segment.replace(leadingNonPrintingRegex, "");
42847
- }
42848
- function isZeroWidthCluster(segment) {
42849
- return zeroWidthClusterRegex.test(segment);
42850
- }
42851
- function isHangulLeadingJamo(codePoint) {
42852
- return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
42853
- }
42854
- function isHangulVowelJamo(codePoint) {
42855
- return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
42856
- }
42857
- function isHangulTrailingJamo(codePoint) {
42858
- return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
42859
- }
42860
- function isHangulJamo(codePoint) {
42861
- return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
42862
- }
42863
- function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
42864
- const codePoints = [];
42865
- for (const character of visibleSegment) {
42866
- if (zeroWidthClusterRegex.test(character)) {
42867
- continue;
42868
- }
42869
- codePoints.push(character.codePointAt(0));
43277
+ function toOneArgVisitWithPath(visitFunction) {
43278
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
42870
43279
  }
42871
- if (codePoints.length === 0) {
42872
- return;
43280
+ function toBeginVisit(visitFunction) {
43281
+ return visitFunction ? () => {
43282
+ if (suppressedCallbacks > 0) {
43283
+ suppressedCallbacks++;
43284
+ } else {
43285
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
43286
+ if (cbReturn === false) {
43287
+ suppressedCallbacks = 1;
43288
+ }
43289
+ }
43290
+ } : () => true;
42873
43291
  }
42874
- let width2 = 0;
42875
- for (let index2 = 0;index2 < codePoints.length; index2++) {
42876
- const codePoint = codePoints[index2];
42877
- if (!isHangulJamo(codePoint)) {
42878
- if (width2 === 0) {
42879
- return;
43292
+ function toEndVisit(visitFunction) {
43293
+ return visitFunction ? () => {
43294
+ if (suppressedCallbacks > 0) {
43295
+ suppressedCallbacks--;
42880
43296
  }
42881
- for (let remaining = index2;remaining < codePoints.length; remaining++) {
42882
- width2 += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
43297
+ if (suppressedCallbacks === 0) {
43298
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
42883
43299
  }
42884
- return width2;
42885
- }
42886
- if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index2 + 1])) {
42887
- width2 += 2;
42888
- index2 += isHangulTrailingJamo(codePoints[index2 + 2]) ? 2 : 1;
42889
- continue;
42890
- }
42891
- width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
43300
+ } : () => true;
42892
43301
  }
42893
- return width2;
42894
- }
42895
- function trailingWidth(visibleSegment, eastAsianWidthOptions) {
42896
- let extra = 0;
42897
- let first = true;
42898
- for (const character of visibleSegment) {
42899
- if (first) {
42900
- first = false;
42901
- continue;
43302
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError5 = toOneArgVisit(visitor.onError);
43303
+ const disallowComments = options3 && options3.disallowComments;
43304
+ const allowTrailingComma = options3 && options3.allowTrailingComma;
43305
+ function scanNext() {
43306
+ while (true) {
43307
+ const token = _scanner.scan();
43308
+ switch (_scanner.getTokenError()) {
43309
+ case 4:
43310
+ handleError(14);
43311
+ break;
43312
+ case 5:
43313
+ handleError(15);
43314
+ break;
43315
+ case 3:
43316
+ handleError(13);
43317
+ break;
43318
+ case 1:
43319
+ if (!disallowComments) {
43320
+ handleError(11);
43321
+ }
43322
+ break;
43323
+ case 2:
43324
+ handleError(12);
43325
+ break;
43326
+ case 6:
43327
+ handleError(16);
43328
+ break;
43329
+ }
43330
+ switch (token) {
43331
+ case 12:
43332
+ case 13:
43333
+ if (disallowComments) {
43334
+ handleError(10);
43335
+ } else {
43336
+ onComment();
43337
+ }
43338
+ break;
43339
+ case 16:
43340
+ handleError(1);
43341
+ break;
43342
+ case 15:
43343
+ case 14:
43344
+ break;
43345
+ default:
43346
+ return token;
43347
+ }
42902
43348
  }
42903
- if (spacingMarkRegex.test(character) || character >= "＀" && character <= "￯") {
42904
- extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
43349
+ }
43350
+ function handleError(error2, skipUntilAfter = [], skipUntil = []) {
43351
+ onError5(error2);
43352
+ if (skipUntilAfter.length + skipUntil.length > 0) {
43353
+ let token = _scanner.getToken();
43354
+ while (token !== 17) {
43355
+ if (skipUntilAfter.indexOf(token) !== -1) {
43356
+ scanNext();
43357
+ break;
43358
+ } else if (skipUntil.indexOf(token) !== -1) {
43359
+ break;
43360
+ }
43361
+ token = scanNext();
43362
+ }
42905
43363
  }
42906
43364
  }
42907
- return extra;
42908
- }
42909
- function stringWidth(input, options3 = {}) {
42910
- if (typeof input !== "string" || input.length === 0) {
42911
- return 0;
43365
+ function parseString(isValue) {
43366
+ const value5 = _scanner.getTokenValue();
43367
+ if (isValue) {
43368
+ onLiteralValue(value5);
43369
+ } else {
43370
+ onObjectProperty(value5);
43371
+ _jsonPath.push(value5);
43372
+ }
43373
+ scanNext();
43374
+ return true;
42912
43375
  }
42913
- const {
42914
- ambiguousIsNarrow = true,
42915
- countAnsiEscapeCodes = false
42916
- } = options3;
42917
- let string4 = input;
42918
- if (!countAnsiEscapeCodes && (string4.includes("\x1B") || string4.includes("›"))) {
42919
- string4 = stripAnsi2(string4);
43376
+ function parseLiteral() {
43377
+ switch (_scanner.getToken()) {
43378
+ case 11:
43379
+ const tokenValue = _scanner.getTokenValue();
43380
+ let value5 = Number(tokenValue);
43381
+ if (isNaN(value5)) {
43382
+ handleError(2);
43383
+ value5 = 0;
43384
+ }
43385
+ onLiteralValue(value5);
43386
+ break;
43387
+ case 7:
43388
+ onLiteralValue(null);
43389
+ break;
43390
+ case 8:
43391
+ onLiteralValue(true);
43392
+ break;
43393
+ case 9:
43394
+ onLiteralValue(false);
43395
+ break;
43396
+ default:
43397
+ return false;
43398
+ }
43399
+ scanNext();
43400
+ return true;
42920
43401
  }
42921
- if (string4.length === 0) {
42922
- return 0;
43402
+ function parseProperty() {
43403
+ if (_scanner.getToken() !== 10) {
43404
+ handleError(3, [], [2, 5]);
43405
+ return false;
43406
+ }
43407
+ parseString(false);
43408
+ if (_scanner.getToken() === 6) {
43409
+ onSeparator(":");
43410
+ scanNext();
43411
+ if (!parseValue()) {
43412
+ handleError(4, [], [2, 5]);
43413
+ }
43414
+ } else {
43415
+ handleError(5, [], [2, 5]);
43416
+ }
43417
+ _jsonPath.pop();
43418
+ return true;
42923
43419
  }
42924
- if (/^[\u0020-\u007E]*$/.test(string4)) {
42925
- return string4.length;
43420
+ function parseObject() {
43421
+ onObjectBegin();
43422
+ scanNext();
43423
+ let needsComma = false;
43424
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
43425
+ if (_scanner.getToken() === 5) {
43426
+ if (!needsComma) {
43427
+ handleError(4, [], []);
43428
+ }
43429
+ onSeparator(",");
43430
+ scanNext();
43431
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
43432
+ break;
43433
+ }
43434
+ } else if (needsComma) {
43435
+ handleError(6, [], []);
43436
+ }
43437
+ if (!parseProperty()) {
43438
+ handleError(4, [], [2, 5]);
43439
+ }
43440
+ needsComma = true;
43441
+ }
43442
+ onObjectEnd();
43443
+ if (_scanner.getToken() !== 2) {
43444
+ handleError(7, [2], []);
43445
+ } else {
43446
+ scanNext();
43447
+ }
43448
+ return true;
42926
43449
  }
42927
- let width2 = 0;
42928
- const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
42929
- for (const { segment } of segmenter.segment(string4)) {
42930
- if (isZeroWidthCluster(segment)) {
42931
- continue;
43450
+ function parseArray2() {
43451
+ onArrayBegin();
43452
+ scanNext();
43453
+ let isFirstElement = true;
43454
+ let needsComma = false;
43455
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
43456
+ if (_scanner.getToken() === 5) {
43457
+ if (!needsComma) {
43458
+ handleError(4, [], []);
43459
+ }
43460
+ onSeparator(",");
43461
+ scanNext();
43462
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
43463
+ break;
43464
+ }
43465
+ } else if (needsComma) {
43466
+ handleError(6, [], []);
43467
+ }
43468
+ if (isFirstElement) {
43469
+ _jsonPath.push(0);
43470
+ isFirstElement = false;
43471
+ } else {
43472
+ _jsonPath[_jsonPath.length - 1]++;
43473
+ }
43474
+ if (!parseValue()) {
43475
+ handleError(4, [], [4, 5]);
43476
+ }
43477
+ needsComma = true;
42932
43478
  }
42933
- if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
42934
- width2 += 2;
42935
- continue;
43479
+ onArrayEnd();
43480
+ if (!isFirstElement) {
43481
+ _jsonPath.pop();
42936
43482
  }
42937
- const visibleSegment = baseVisible(segment);
42938
- const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
42939
- if (hangulWidth !== undefined) {
42940
- width2 += hangulWidth;
42941
- continue;
43483
+ if (_scanner.getToken() !== 4) {
43484
+ handleError(8, [4], []);
43485
+ } else {
43486
+ scanNext();
42942
43487
  }
42943
- const codePoint = visibleSegment.codePointAt(0);
42944
- width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
42945
- width2 += trailingWidth(visibleSegment, eastAsianWidthOptions);
43488
+ return true;
42946
43489
  }
42947
- return width2;
42948
- }
42949
-
42950
- // node_modules/.bun/ansi-styles@6.2.3/node_modules/ansi-styles/index.js
42951
- var ANSI_BACKGROUND_OFFSET = 10;
42952
- var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
42953
- var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
42954
- var wrapAnsi16m = (offset = 0) => (red2, green2, blue) => `\x1B[${38 + offset};2;${red2};${green2};${blue}m`;
42955
- var styles = {
42956
- modifier: {
42957
- reset: [0, 0],
42958
- bold: [1, 22],
42959
- dim: [2, 22],
42960
- italic: [3, 23],
42961
- underline: [4, 24],
42962
- overline: [53, 55],
42963
- inverse: [7, 27],
42964
- hidden: [8, 28],
42965
- strikethrough: [9, 29]
42966
- },
42967
- color: {
42968
- black: [30, 39],
42969
- red: [31, 39],
42970
- green: [32, 39],
42971
- yellow: [33, 39],
42972
- blue: [34, 39],
42973
- magenta: [35, 39],
42974
- cyan: [36, 39],
42975
- white: [37, 39],
42976
- blackBright: [90, 39],
42977
- gray: [90, 39],
42978
- grey: [90, 39],
42979
- redBright: [91, 39],
42980
- greenBright: [92, 39],
42981
- yellowBright: [93, 39],
42982
- blueBright: [94, 39],
42983
- magentaBright: [95, 39],
42984
- cyanBright: [96, 39],
42985
- whiteBright: [97, 39]
42986
- },
42987
- bgColor: {
42988
- bgBlack: [40, 49],
42989
- bgRed: [41, 49],
42990
- bgGreen: [42, 49],
42991
- bgYellow: [43, 49],
42992
- bgBlue: [44, 49],
42993
- bgMagenta: [45, 49],
42994
- bgCyan: [46, 49],
42995
- bgWhite: [47, 49],
42996
- bgBlackBright: [100, 49],
42997
- bgGray: [100, 49],
42998
- bgGrey: [100, 49],
42999
- bgRedBright: [101, 49],
43000
- bgGreenBright: [102, 49],
43001
- bgYellowBright: [103, 49],
43002
- bgBlueBright: [104, 49],
43003
- bgMagentaBright: [105, 49],
43004
- bgCyanBright: [106, 49],
43005
- bgWhiteBright: [107, 49]
43490
+ function parseValue() {
43491
+ switch (_scanner.getToken()) {
43492
+ case 3:
43493
+ return parseArray2();
43494
+ case 1:
43495
+ return parseObject();
43496
+ case 10:
43497
+ return parseString(true);
43498
+ default:
43499
+ return parseLiteral();
43500
+ }
43006
43501
  }
43007
- };
43008
- var modifierNames = Object.keys(styles.modifier);
43009
- var foregroundColorNames = Object.keys(styles.color);
43010
- var backgroundColorNames = Object.keys(styles.bgColor);
43011
- var colorNames = [...foregroundColorNames, ...backgroundColorNames];
43012
- function assembleStyles() {
43013
- const codes2 = new Map;
43014
- for (const [groupName, group2] of Object.entries(styles)) {
43015
- for (const [styleName, style] of Object.entries(group2)) {
43016
- styles[styleName] = {
43017
- open: `\x1B[${style[0]}m`,
43018
- close: `\x1B[${style[1]}m`
43019
- };
43020
- group2[styleName] = styles[styleName];
43021
- codes2.set(style[0], style[1]);
43502
+ scanNext();
43503
+ if (_scanner.getToken() === 17) {
43504
+ if (options3.allowEmptyContent) {
43505
+ return true;
43022
43506
  }
43023
- Object.defineProperty(styles, groupName, {
43024
- value: group2,
43025
- enumerable: false
43026
- });
43507
+ handleError(4, [], []);
43508
+ return false;
43027
43509
  }
43028
- Object.defineProperty(styles, "codes", {
43029
- value: codes2,
43030
- enumerable: false
43031
- });
43032
- styles.color.close = "\x1B[39m";
43033
- styles.bgColor.close = "\x1B[49m";
43034
- styles.color.ansi = wrapAnsi16();
43035
- styles.color.ansi256 = wrapAnsi256();
43036
- styles.color.ansi16m = wrapAnsi16m();
43037
- styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
43038
- styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
43039
- styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
43040
- Object.defineProperties(styles, {
43041
- rgbToAnsi256: {
43042
- value(red2, green2, blue) {
43043
- if (red2 === green2 && green2 === blue) {
43044
- if (red2 < 8) {
43045
- return 16;
43046
- }
43047
- if (red2 > 248) {
43048
- return 231;
43049
- }
43050
- return Math.round((red2 - 8) / 247 * 24) + 232;
43051
- }
43052
- return 16 + 36 * Math.round(red2 / 255 * 5) + 6 * Math.round(green2 / 255 * 5) + Math.round(blue / 255 * 5);
43053
- },
43054
- enumerable: false
43055
- },
43056
- hexToRgb: {
43057
- value(hex2) {
43058
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex2.toString(16));
43059
- if (!matches) {
43060
- return [0, 0, 0];
43061
- }
43062
- let [colorString] = matches;
43063
- if (colorString.length === 3) {
43064
- colorString = [...colorString].map((character) => character + character).join("");
43065
- }
43066
- const integer = Number.parseInt(colorString, 16);
43067
- return [
43068
- integer >> 16 & 255,
43069
- integer >> 8 & 255,
43070
- integer & 255
43071
- ];
43072
- },
43073
- enumerable: false
43074
- },
43075
- hexToAnsi256: {
43076
- value: (hex2) => styles.rgbToAnsi256(...styles.hexToRgb(hex2)),
43077
- enumerable: false
43510
+ if (!parseValue()) {
43511
+ handleError(4, [], []);
43512
+ return false;
43513
+ }
43514
+ if (_scanner.getToken() !== 17) {
43515
+ handleError(9, [], []);
43516
+ }
43517
+ return true;
43518
+ }
43519
+ function getNodeType(value5) {
43520
+ switch (typeof value5) {
43521
+ case "boolean":
43522
+ return "boolean";
43523
+ case "number":
43524
+ return "number";
43525
+ case "string":
43526
+ return "string";
43527
+ case "object": {
43528
+ if (!value5) {
43529
+ return "null";
43530
+ } else if (Array.isArray(value5)) {
43531
+ return "array";
43532
+ }
43533
+ return "object";
43534
+ }
43535
+ default:
43536
+ return "null";
43537
+ }
43538
+ }
43539
+
43540
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
43541
+ var ScanError;
43542
+ (function(ScanError2) {
43543
+ ScanError2[ScanError2["None"] = 0] = "None";
43544
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
43545
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
43546
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
43547
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
43548
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
43549
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
43550
+ })(ScanError || (ScanError = {}));
43551
+ var SyntaxKind;
43552
+ (function(SyntaxKind2) {
43553
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
43554
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
43555
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
43556
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
43557
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
43558
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
43559
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
43560
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
43561
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
43562
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
43563
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
43564
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
43565
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
43566
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
43567
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
43568
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
43569
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
43570
+ })(SyntaxKind || (SyntaxKind = {}));
43571
+ var parseTree2 = parseTree;
43572
+ var getNodeValue2 = getNodeValue;
43573
+ var visit2 = visit;
43574
+ var ParseErrorCode;
43575
+ (function(ParseErrorCode2) {
43576
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
43577
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
43578
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
43579
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
43580
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
43581
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
43582
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
43583
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
43584
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
43585
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
43586
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
43587
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
43588
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
43589
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
43590
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
43591
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
43592
+ })(ParseErrorCode || (ParseErrorCode = {}));
43593
+
43594
+ // packages/cli/src/jsonc.ts
43595
+ var parseOptions = { allowTrailingComma: true, allowEmptyContent: true };
43596
+ var defaultIndent = " ";
43597
+ function parse6(text2) {
43598
+ const errors = [];
43599
+ const root = parseTree2(text2, errors, parseOptions);
43600
+ const comments = [];
43601
+ const commas = [];
43602
+ visit2(text2, {
43603
+ onComment: (offset, length) => {
43604
+ comments.push({ offset, length });
43078
43605
  },
43079
- ansi256ToAnsi: {
43080
- value(code) {
43081
- if (code < 8) {
43082
- return 30 + code;
43083
- }
43084
- if (code < 16) {
43085
- return 90 + (code - 8);
43086
- }
43087
- let red2;
43088
- let green2;
43089
- let blue;
43090
- if (code >= 232) {
43091
- red2 = ((code - 232) * 10 + 8) / 255;
43092
- green2 = red2;
43093
- blue = red2;
43094
- } else {
43095
- code -= 16;
43096
- const remainder2 = code % 36;
43097
- red2 = Math.floor(code / 36) / 5;
43098
- green2 = Math.floor(remainder2 / 6) / 5;
43099
- blue = remainder2 % 6 / 5;
43100
- }
43101
- const value5 = Math.max(red2, green2, blue) * 2;
43102
- if (value5 === 0) {
43103
- return 30;
43104
- }
43105
- let result6 = 30 + (Math.round(blue) << 2 | Math.round(green2) << 1 | Math.round(red2));
43106
- if (value5 === 2) {
43107
- result6 += 60;
43108
- }
43109
- return result6;
43110
- },
43111
- enumerable: false
43112
- },
43113
- rgbToAnsi: {
43114
- value: (red2, green2, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red2, green2, blue)),
43115
- enumerable: false
43116
- },
43117
- hexToAnsi: {
43118
- value: (hex2) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex2)),
43119
- enumerable: false
43120
- }
43121
- });
43122
- return styles;
43123
- }
43124
- var ansiStyles = assembleStyles();
43125
- var ansi_styles_default = ansiStyles;
43126
-
43127
- // node_modules/.bun/wrap-ansi@10.0.2/node_modules/wrap-ansi/index.js
43128
- var ANSI_ESCAPE = "\x1B";
43129
- var ANSI_ESCAPE_BELL = "\x07";
43130
- var C1_CSI = "›";
43131
- var ANSI_CSI = "[";
43132
- var ANSI_OSC = "]";
43133
- var ANSI_SGR_TERMINATOR = "m";
43134
- var ANSI_SGR_RESET = 0;
43135
- var ANSI_SGR_RESET_FOREGROUND = 39;
43136
- var ANSI_SGR_RESET_BACKGROUND = 49;
43137
- var ANSI_SGR_RESET_UNDERLINE_COLOR = 59;
43138
- var ANSI_SGR_FOREGROUND_EXTENDED = 38;
43139
- var ANSI_SGR_BACKGROUND_EXTENDED = 48;
43140
- var ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;
43141
- var ANSI_SGR_COLOR_MODE_RGB = 2;
43142
- var ANSI_SGR_COLOR_MODE_256 = 5;
43143
- var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;`;
43144
- var ESCAPES = new Set([
43145
- ANSI_ESCAPE,
43146
- C1_CSI
43147
- ]);
43148
- var ESCAPE_CHARACTERS = [...ESCAPES].join("");
43149
- var CSI_INTRODUCER = `(?:${ANSI_ESCAPE}\\${ANSI_CSI}|${C1_CSI})`;
43150
- var CSI_PARAMETERS = "[0-?]*[ -/]*[@-~]";
43151
- var SGR_PARAMETERS = `(?<sgr>[0-9;:]*)${ANSI_SGR_TERMINATOR}`;
43152
- var OSC_STRING_TERMINATOR = `(?:${ANSI_ESCAPE_BELL}|${ANSI_ESCAPE}\\\\)`;
43153
- var OSC_STRING_PAYLOAD = String.raw`[^\u0000-\u001F\u007F-\u009F]*`;
43154
- var LINK_PARAMETERS = String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${OSC_STRING_PAYLOAD})${OSC_STRING_TERMINATOR}`;
43155
- var OSC_STRING = `${OSC_STRING_PAYLOAD}${OSC_STRING_TERMINATOR}`;
43156
- var ANSI_ESCAPE_REGEX = new RegExp(`${CSI_INTRODUCER}(?:${SGR_PARAMETERS}|${CSI_PARAMETERS})` + `|${ANSI_ESCAPE}\\${ANSI_OSC}(?:${LINK_PARAMETERS}|${OSC_STRING})`, "y");
43157
- var ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansi_styles_default.codes.values());
43158
- ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);
43159
- var segmenter2 = new Intl.Segmenter;
43160
- var getStringWidth = (string4) => stringWidth(string4, { countAnsiEscapeCodes: true });
43161
- var TAB_SIZE = 8;
43162
- var ESCAPE_INTRODUCER_REGEX = new RegExp(`[${ESCAPE_CHARACTERS}]`, "g");
43163
- var ROW_BOUNDARY_REGEX = new RegExp(`[\\n${ESCAPE_CHARACTERS}]`, "g");
43164
- var ASCII_PRINTABLE_REGEX = /^[ -~]*$/;
43165
- var wrapAnsiCode = (code) => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
43166
- var wrapAnsiHyperlink = (url, parameters = "") => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${parameters};${url}${ANSI_ESCAPE_BELL}`;
43167
- var matchAnsiEscape = (string4, index2) => {
43168
- if (!ESCAPES.has(string4[index2])) {
43169
- return;
43170
- }
43171
- ANSI_ESCAPE_REGEX.lastIndex = index2;
43172
- return ANSI_ESCAPE_REGEX.exec(string4) ?? undefined;
43173
- };
43174
- var forEachSegment = (string4, onPlainText, onEscape = () => {}) => {
43175
- let plainStart = 0;
43176
- let index2 = 0;
43177
- while (index2 < string4.length) {
43178
- ESCAPE_INTRODUCER_REGEX.lastIndex = index2;
43179
- const introducer = ESCAPE_INTRODUCER_REGEX.exec(string4);
43180
- if (!introducer) {
43181
- break;
43182
- }
43183
- const escape2 = matchAnsiEscape(string4, introducer.index);
43184
- if (!escape2) {
43185
- index2 = introducer.index + 1;
43186
- continue;
43187
- }
43188
- if (introducer.index > plainStart) {
43189
- onPlainText(string4.slice(plainStart, introducer.index));
43190
- }
43191
- onEscape(escape2[0]);
43192
- index2 = introducer.index + escape2[0].length;
43193
- plainStart = index2;
43606
+ onSeparator: (character, offset) => {
43607
+ if (character === ",")
43608
+ commas.push(offset);
43609
+ }
43610
+ }, parseOptions);
43611
+ return errors.length > 0 ? exports_Option.none() : exports_Option.some({ root: exports_Option.fromUndefinedOr(root), comments, commas });
43612
+ }
43613
+ function members(root) {
43614
+ return (root.children ?? []).flatMap((property) => {
43615
+ const [key, value5] = property.children ?? [];
43616
+ return key === undefined || value5 === undefined ? [] : [{ key, value: value5 }];
43617
+ });
43618
+ }
43619
+ function indentAt(text2, offset) {
43620
+ const prefix3 = text2.slice(text2.lastIndexOf(`
43621
+ `, offset - 1) + 1, offset);
43622
+ return /^[ \t]*$/.test(prefix3) ? exports_Option.some(prefix3) : exports_Option.none();
43623
+ }
43624
+ function lineBreak(text2, parsed, from, to) {
43625
+ let index2 = from;
43626
+ while (index2 < to) {
43627
+ const position = index2;
43628
+ const comment = parsed.comments.find((range3) => position >= range3.offset && position < range3.offset + range3.length);
43629
+ if (comment !== undefined)
43630
+ index2 = comment.offset + comment.length;
43631
+ else if (text2[index2] === `
43632
+ ` || text2[index2] === "\r" && text2[index2 + 1] === `
43633
+ `)
43634
+ return exports_Option.some(index2);
43635
+ else
43636
+ index2++;
43194
43637
  }
43195
- if (plainStart < string4.length) {
43196
- onPlainText(string4.slice(plainStart));
43638
+ return exports_Option.none();
43639
+ }
43640
+ function additions(text2, parsed, root, lines2) {
43641
+ const eol = text2.includes(`\r
43642
+ `) ? `\r
43643
+ ` : `
43644
+ `;
43645
+ const close3 = root.offset + root.length - 1;
43646
+ const last = members(root).at(-1);
43647
+ if (last === undefined) {
43648
+ const outer = exports_Option.getOrElse(indentAt(text2, root.offset), () => "");
43649
+ const body = lines2.map((line) => `${eol}${outer}${defaultIndent}${line}`).join(",");
43650
+ return [
43651
+ exports_Option.match(lineBreak(text2, parsed, root.offset + 1, close3), {
43652
+ onNone: () => ({ offset: root.offset + 1, length: 0, text: `${body}${eol}${outer}` }),
43653
+ onSome: (offset) => ({ offset, length: 0, text: body })
43654
+ })
43655
+ ];
43197
43656
  }
43198
- };
43199
- var getWidth = (string4) => {
43200
- let plainText = "";
43201
- forEachSegment(string4, (part) => {
43202
- plainText += part;
43203
- });
43204
- return getStringWidth(plainText);
43205
- };
43206
- var getTokens = (string4) => {
43207
- const tokens = [];
43208
- forEachSegment(string4, (plainText) => {
43209
- if (ASCII_PRINTABLE_REGEX.test(plainText)) {
43210
- for (const character of plainText) {
43211
- tokens.push({ value: character, width: 1 });
43657
+ const end3 = last.value.offset + last.value.length;
43658
+ const comma = parsed.commas.find((offset) => offset >= end3 && offset < close3);
43659
+ const indent = exports_Option.getOrElse(indentAt(text2, last.key.offset), () => defaultIndent);
43660
+ return exports_Option.match(lineBreak(text2, parsed, comma === undefined ? end3 : comma + 1, close3), {
43661
+ onNone: () => [
43662
+ comma === undefined ? { offset: end3, length: 0, text: lines2.map((line) => `, ${line}`).join("") } : { offset: comma + 1, length: 0, text: lines2.map((line) => ` ${line},`).join("") }
43663
+ ],
43664
+ onSome: (offset) => comma === undefined ? [
43665
+ {
43666
+ offset: end3,
43667
+ length: offset - end3,
43668
+ text: `,${text2.slice(end3, offset)}${lines2.map((line) => `${eol}${indent}${line}`).join(",")}`
43212
43669
  }
43213
- return;
43214
- }
43215
- for (const { segment } of segmenter2.segment(plainText)) {
43216
- tokens.push({ value: segment, width: getStringWidth(segment) });
43217
- }
43218
- }, (escape2) => {
43219
- tokens.push({ value: escape2, width: 0 });
43220
- });
43221
- return tokens;
43222
- };
43223
- var splitWords = (string4) => {
43224
- let currentWord = { value: "", plainText: "" };
43225
- const words = [currentWord];
43226
- forEachSegment(string4, (plainText) => {
43227
- const parts2 = plainText.split(" ");
43228
- currentWord.value += parts2[0];
43229
- currentWord.plainText += parts2[0];
43230
- for (let index2 = 1;index2 < parts2.length; index2++) {
43231
- currentWord = { value: parts2[index2], plainText: parts2[index2] };
43232
- words.push(currentWord);
43233
- }
43234
- }, (escape2) => {
43235
- currentWord.value += escape2;
43670
+ ] : [{ offset, length: 0, text: lines2.map((line) => `${eol}${indent}${line},`).join("") }]
43236
43671
  });
43237
- for (const word of words) {
43238
- word.width = getStringWidth(word.plainText);
43239
- }
43240
- return words;
43241
- };
43242
- var getColonColorToken = (parameter) => {
43243
- const parts2 = parameter.split(":");
43244
- const code = Number.parseInt(parts2[0], 10);
43245
- const mode = Number.parseInt(parts2[1], 10);
43246
- if (![ANSI_SGR_FOREGROUND_EXTENDED, ANSI_SGR_BACKGROUND_EXTENDED, ANSI_SGR_UNDERLINE_COLOR_EXTENDED].includes(code)) {
43247
- return;
43248
- }
43249
- if (mode === ANSI_SGR_COLOR_MODE_256 && parts2.length === 3 && /^\d+$/.test(parts2[2])) {
43250
- return { code, open: parameter, hasArguments: true };
43251
- }
43252
- if (mode !== ANSI_SGR_COLOR_MODE_RGB) {
43253
- return;
43254
- }
43255
- const components = parts2.length === 6 ? parts2.slice(3) : parts2.slice(2);
43256
- const colorSpace = parts2.length === 6 ? parts2[2] : undefined;
43257
- if (components.length === 3 && components.every((component) => /^\d+$/.test(component)) && (colorSpace === undefined || /^\d*$/.test(colorSpace))) {
43258
- return { code, open: parameter, hasArguments: true };
43672
+ }
43673
+ var spliced = (text2, splices) => splices.toSorted((a, b) => b.offset - a.offset).reduce((result6, splice) => `${result6.slice(0, splice.offset)}${splice.text}${result6.slice(splice.offset + splice.length)}`, text2);
43674
+ var others = (root, keys4) => members(root).filter(({ key }) => !keys4.has(String(key.value))).map(({ key, value: value5 }) => `${JSON.stringify(key.value)}=${JSON.stringify(getNodeValue2(value5))}`).join(`
43675
+ `);
43676
+ var holds = (root, properties) => properties.every(([key, value5]) => {
43677
+ const found = members(root).filter((member) => member.key.value === key);
43678
+ return found.length === 1 && found.every((member) => getNodeValue2(member.value) === value5);
43679
+ });
43680
+ function listed(root, key) {
43681
+ const found = members(root).filter((member2) => member2.key.value === key);
43682
+ const [member] = found;
43683
+ return found.length === 1 && member?.value.type === "array" ? exports_Option.some((member.value.children ?? []).map((item) => JSON.stringify(getNodeValue2(item)))) : exports_Option.none();
43684
+ }
43685
+ var includes = (result6, root, memberships) => memberships.every(([key, item]) => {
43686
+ const before = exports_Option.getOrElse(listed(root, key), () => []);
43687
+ const wanted = before.includes(JSON.stringify(item)) ? before : [...before, JSON.stringify(item)];
43688
+ return exports_Option.getOrElse(listed(result6, key), () => []).join(`
43689
+ `) === wanted.join(`
43690
+ `);
43691
+ });
43692
+ function setProperties(source, properties, memberships = []) {
43693
+ const mark = source.startsWith("\uFEFF") ? "\uFEFF" : "";
43694
+ const text2 = source.slice(mark.length);
43695
+ const keys4 = new Set([...properties, ...memberships].map(([key]) => key));
43696
+ const rendered = ([key, value5]) => `${JSON.stringify(key)}: ${JSON.stringify(value5)}`;
43697
+ const holding = ([key, item]) => `${JSON.stringify(key)}: [${JSON.stringify(item)}]`;
43698
+ const parsed = parse6(text2);
43699
+ if (exports_Option.isNone(parsed))
43700
+ return exports_Option.none();
43701
+ if (exports_Option.isNone(parsed.value.root)) {
43702
+ const eol = text2.includes(`\r
43703
+ `) ? `\r
43704
+ ` : `
43705
+ `;
43706
+ const lead = text2 === "" || text2.endsWith(`
43707
+ `) ? text2 : `${text2}${eol}`;
43708
+ const body = [...properties.map(rendered), ...memberships.map(holding)].map((line) => `${defaultIndent}${line}`);
43709
+ return exports_Option.some({
43710
+ text: `${mark}${lead}{${eol}${body.join(`,${eol}`)}${eol}}${eol}`,
43711
+ changes: properties.map(([key, value5]) => ({
43712
+ key,
43713
+ value: JSON.stringify(value5),
43714
+ previous: exports_Option.none()
43715
+ })),
43716
+ included: memberships
43717
+ });
43259
43718
  }
43260
- };
43261
- var getSgrTokens = (sgrParameters) => {
43262
- const parameters = sgrParameters.split(";");
43263
- const sgrTokens = [];
43264
- for (let index2 = 0;index2 < parameters.length; index2++) {
43265
- const parameter = parameters[index2];
43266
- if (parameter.includes(":")) {
43267
- const colonColorToken = getColonColorToken(parameter);
43268
- if (colonColorToken) {
43269
- sgrTokens.push(colonColorToken);
43270
- }
43271
- continue;
43272
- }
43273
- const code = parameter === "" ? ANSI_SGR_RESET : Number.parseInt(parameter, 10);
43274
- if (!Number.isFinite(code)) {
43719
+ const root = parsed.value.root.value;
43720
+ if (root.type !== "object")
43721
+ return exports_Option.none();
43722
+ const changes2 = [];
43723
+ const splices = [];
43724
+ const included = [];
43725
+ const missing2 = [];
43726
+ for (const property of properties) {
43727
+ const [key, value5] = property;
43728
+ const found = members(root).filter((member2) => member2.key.value === key);
43729
+ const [member] = found;
43730
+ if (found.length > 1)
43731
+ return exports_Option.none();
43732
+ if (member !== undefined && getNodeValue2(member.value) === value5)
43275
43733
  continue;
43276
- }
43277
- if (code === ANSI_SGR_FOREGROUND_EXTENDED || code === ANSI_SGR_BACKGROUND_EXTENDED || code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED) {
43278
- if (index2 + 1 >= parameters.length) {
43279
- break;
43280
- }
43281
- const mode = Number.parseInt(parameters[index2 + 1], 10);
43282
- const colorIndex = Number.parseInt(parameters[index2 + 2], 10);
43283
- if (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(colorIndex)) {
43284
- sgrTokens.push({ code, open: [code, mode, colorIndex].join(";"), hasArguments: true });
43285
- index2 += 2;
43286
- continue;
43287
- }
43288
- const red2 = Number.parseInt(parameters[index2 + 2], 10);
43289
- const green2 = Number.parseInt(parameters[index2 + 3], 10);
43290
- const blue = Number.parseInt(parameters[index2 + 4], 10);
43291
- if (mode === ANSI_SGR_COLOR_MODE_RGB && Number.isFinite(red2) && Number.isFinite(green2) && Number.isFinite(blue)) {
43292
- sgrTokens.push({ code, open: [code, mode, red2, green2, blue].join(";"), hasArguments: true });
43293
- index2 += 4;
43294
- continue;
43295
- }
43296
- break;
43297
- }
43298
- sgrTokens.push({ code, open: String(code), hasArguments: false });
43299
- }
43300
- return sgrTokens;
43301
- };
43302
- var removeActiveStyle = (activeStyles, family) => {
43303
- const activeStyleIndex = activeStyles.findIndex((activeStyle) => activeStyle.family === family);
43304
- if (activeStyleIndex !== -1) {
43305
- activeStyles.splice(activeStyleIndex, 1);
43306
- }
43307
- };
43308
- var upsertActiveStyle = (activeStyles, nextActiveStyle) => {
43309
- removeActiveStyle(activeStyles, nextActiveStyle.family);
43310
- activeStyles.push(nextActiveStyle);
43311
- };
43312
- var removeModifierStylesByClose = (activeStyles, closeCode) => {
43313
- for (let index2 = activeStyles.length - 1;index2 >= 0; index2--) {
43314
- const activeStyle = activeStyles[index2];
43315
- if (activeStyle.family.startsWith("modifier-") && activeStyle.close === closeCode) {
43316
- activeStyles.splice(index2, 1);
43317
- }
43318
- }
43319
- };
43320
- var getColorStyle = (sgrToken) => {
43321
- const { code, open: open3, hasArguments } = sgrToken;
43322
- if (code >= 30 && code <= 37 || code >= 90 && code <= 97 || code === ANSI_SGR_FOREGROUND_EXTENDED && hasArguments) {
43323
- return {
43324
- family: "foreground",
43325
- open: open3,
43326
- close: ANSI_SGR_RESET_FOREGROUND
43327
- };
43734
+ changes2.push({
43735
+ key,
43736
+ value: JSON.stringify(value5),
43737
+ previous: exports_Option.map(exports_Option.fromUndefinedOr(member), ({ value: node }) => text2.slice(node.offset, node.offset + node.length))
43738
+ });
43739
+ if (member === undefined)
43740
+ missing2.push(rendered(property));
43741
+ else
43742
+ splices.push({
43743
+ offset: member.value.offset,
43744
+ length: member.value.length,
43745
+ text: JSON.stringify(value5)
43746
+ });
43328
43747
  }
43329
- if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === ANSI_SGR_BACKGROUND_EXTENDED && hasArguments) {
43330
- return {
43331
- family: "background",
43332
- open: open3,
43333
- close: ANSI_SGR_RESET_BACKGROUND
43334
- };
43335
- }
43336
- if (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && hasArguments) {
43337
- return {
43338
- family: "underlineColor",
43339
- open: open3,
43340
- close: ANSI_SGR_RESET_UNDERLINE_COLOR
43341
- };
43342
- }
43343
- };
43344
- var applySgrResetCode = (code, activeStyles) => {
43345
- if (code === ANSI_SGR_RESET) {
43346
- activeStyles.length = 0;
43347
- return true;
43348
- }
43349
- if (code === ANSI_SGR_RESET_FOREGROUND) {
43350
- removeActiveStyle(activeStyles, "foreground");
43351
- return true;
43352
- }
43353
- if (code === ANSI_SGR_RESET_BACKGROUND) {
43354
- removeActiveStyle(activeStyles, "background");
43355
- return true;
43356
- }
43357
- if (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {
43358
- removeActiveStyle(activeStyles, "underlineColor");
43359
- return true;
43360
- }
43361
- if (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {
43362
- removeModifierStylesByClose(activeStyles, code);
43363
- return true;
43364
- }
43365
- return false;
43366
- };
43367
- var applySgrToken = (sgrToken, activeStyles) => {
43368
- const { code } = sgrToken;
43369
- if (applySgrResetCode(code, activeStyles)) {
43370
- return;
43371
- }
43372
- const colorStyle = getColorStyle(sgrToken);
43373
- if (colorStyle) {
43374
- upsertActiveStyle(activeStyles, colorStyle);
43375
- return;
43376
- }
43377
- const close3 = ansi_styles_default.codes.get(code);
43378
- if (close3 !== undefined && close3 !== ANSI_SGR_RESET) {
43379
- upsertActiveStyle(activeStyles, {
43380
- family: `modifier-${code}`,
43381
- open: sgrToken.open,
43382
- close: close3
43383
- });
43384
- }
43385
- };
43386
- var applySgrParameters = (sgrParameters, activeStyles) => {
43387
- for (const sgrToken of getSgrTokens(sgrParameters)) {
43388
- applySgrToken(sgrToken, activeStyles);
43389
- }
43390
- };
43391
- var applySgrResets = (sgrParameters, activeStyles) => {
43392
- for (const { code } of getSgrTokens(sgrParameters)) {
43393
- applySgrResetCode(code, activeStyles);
43394
- }
43395
- };
43396
- var applyLeadingSgrResets = (string4, startIndex, activeStyles) => {
43397
- let index2 = startIndex;
43398
- while (index2 < string4.length) {
43399
- const match10 = matchAnsiEscape(string4, index2);
43400
- if (!match10) {
43401
- break;
43402
- }
43403
- if (match10.groups.sgr !== undefined) {
43404
- applySgrResets(match10.groups.sgr, activeStyles);
43405
- }
43406
- index2 += match10[0].length;
43407
- }
43408
- };
43409
- var getClosingSgrSequence = (activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join("");
43410
- var getOpeningSgrSequence = (activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join("");
43411
- var wrapWord = (rows, word, columns, rowWidth) => {
43412
- const tokens = getTokens(word);
43413
- let visible = rowWidth;
43414
- for (let index2 = 0;index2 < tokens.length; index2++) {
43415
- const token = tokens[index2];
43416
- if (token.width > 0 && visible > 0 && visible + token.width > columns) {
43417
- rows.push("");
43418
- visible = 0;
43419
- }
43420
- rows[rows.length - 1] += token.value;
43421
- visible += token.width;
43422
- if (visible === columns && index2 < tokens.length - 1) {
43423
- rows.push("");
43424
- visible = 0;
43425
- }
43426
- }
43427
- if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
43428
- rows[rows.length - 2] += rows.pop();
43429
- }
43430
- return getWidth(rows.at(-1));
43431
- };
43432
- var stringVisibleTrimSpacesRight = (string4) => {
43433
- if (!string4.includes(" ")) {
43434
- return string4;
43435
- }
43436
- const segments = [];
43437
- forEachSegment(string4, (plainText) => {
43438
- segments.push({ value: plainText, isEscape: false });
43439
- }, (escape2) => {
43440
- segments.push({ value: escape2, isEscape: true });
43441
- });
43442
- for (let index2 = segments.length - 1;index2 >= 0; index2--) {
43443
- const segment = segments[index2];
43444
- if (segment.isEscape) {
43748
+ for (const membership of memberships) {
43749
+ const [key, item] = membership;
43750
+ const found = members(root).filter((member2) => member2.key.value === key);
43751
+ const [member] = found;
43752
+ if (found.length > 1 || member !== undefined && member.value.type !== "array")
43753
+ return exports_Option.none();
43754
+ const items = member?.value.children ?? [];
43755
+ if (items.some((node) => getNodeValue2(node) === item))
43445
43756
  continue;
43446
- }
43447
- let end3 = segment.value.length;
43448
- while (end3 > 0 && segment.value[end3 - 1] === " ") {
43449
- end3--;
43450
- }
43451
- segment.value = segment.value.slice(0, end3);
43452
- if (getStringWidth(segment.value) > 0) {
43453
- break;
43454
- }
43455
- }
43456
- return segments.map((segment) => segment.value).join("");
43457
- };
43458
- var expandTabs = (line) => {
43459
- if (!line.includes("\t")) {
43460
- return line;
43461
- }
43462
- let visible = 0;
43463
- let expandedLine = "";
43464
- let plainTextSinceTab = "";
43465
- const expandPlainText = (plainText) => {
43466
- const segments = plainText.split("\t");
43467
- for (const [index2, segment] of segments.entries()) {
43468
- expandedLine += segment;
43469
- plainTextSinceTab += segment;
43470
- if (index2 < segments.length - 1) {
43471
- visible += getStringWidth(plainTextSinceTab);
43472
- plainTextSinceTab = "";
43473
- const spaces = TAB_SIZE - visible % TAB_SIZE;
43474
- expandedLine += " ".repeat(spaces);
43475
- visible += spaces;
43476
- }
43477
- }
43478
- };
43479
- forEachSegment(line, expandPlainText, (escape2) => {
43480
- expandedLine += escape2;
43757
+ included.push(membership);
43758
+ const last = items.at(-1);
43759
+ if (member === undefined)
43760
+ missing2.push(holding(membership));
43761
+ else
43762
+ splices.push(last === undefined ? { offset: member.value.offset + 1, length: 0, text: JSON.stringify(item) } : { offset: last.offset + last.length, length: 0, text: `, ${JSON.stringify(item)}` });
43763
+ }
43764
+ if (missing2.length > 0)
43765
+ splices.push(...additions(text2, parsed.value, root, missing2));
43766
+ const edited = spliced(text2, splices);
43767
+ return exports_Option.flatMap(parse6(edited), (result6) => exports_Option.match(result6.root, {
43768
+ onNone: () => exports_Option.none(),
43769
+ onSome: (object) => object.type === "object" && holds(object, properties) && includes(object, root, memberships) && others(object, keys4) === others(root, keys4) ? exports_Option.some({ text: `${mark}${edited}`, changes: changes2, included }) : exports_Option.none()
43770
+ }));
43771
+ }
43772
+
43773
+ // packages/cli/src/schedule.ts
43774
+ import { homedir as homedir2, userInfo } from "node:os";
43775
+
43776
+ // packages/cli/src/settings.ts
43777
+ import { randomUUID } from "node:crypto";
43778
+ import { homedir, hostname } from "node:os";
43779
+ class SettingsError extends exports_Schema.TaggedError()("SettingsError", {
43780
+ message: exports_Schema.String
43781
+ }) {
43782
+ }
43783
+ var loopback = new Set(["localhost", "127.0.0.1", "[::1]"]);
43784
+ var ServerUrl = exports_Schema.URLFromString.check(exports_Schema.makeFilter((url) => url.protocol === "https:" || url.protocol === "http:" && loopback.has(url.hostname), { expected: "an https:// URL, or http:// on localhost" }));
43785
+ var SyncSettings = exports_Schema.Struct({
43786
+ server: exports_Schema.optionalKey(ServerUrl),
43787
+ token: exports_Schema.optionalKey(exports_Schema.RedactedFromValue(exports_Schema.NonEmptyString))
43788
+ });
43789
+ var configHome = exports_Effect.gen(function* () {
43790
+ const path = yield* exports_Path.Path;
43791
+ return yield* exports_Config.String("XDG_CONFIG_HOME").pipe(exports_Config.option, exports_Effect.map(exports_Option.filter((directory) => path.isAbsolute(directory))));
43792
+ });
43793
+ var settingsDirectory = exports_Effect.gen(function* () {
43794
+ const path = yield* exports_Path.Path;
43795
+ const home = homedir();
43796
+ const xdg = yield* configHome;
43797
+ const appData = yield* exports_Config.String("APPDATA").pipe(exports_Config.option);
43798
+ const root = exports_Option.getOrElse(xdg, () => exports_Match.value(process.platform).pipe(exports_Match.when("win32", () => exports_Option.getOrElse(appData, () => path.join(home, "AppData", "Roaming"))), exports_Match.when("darwin", () => path.join(home, "Library", "Application Support")), exports_Match.orElse(() => path.join(home, ".config"))));
43799
+ return path.join(root, "token-ledger");
43800
+ });
43801
+ var loadMachine = exports_Effect.fn("Settings.loadMachine")(function* (directory) {
43802
+ const fs = yield* exports_FileSystem.FileSystem;
43803
+ const path = yield* exports_Path.Path;
43804
+ const file2 = path.join(directory, "machine.json");
43805
+ const read2 = fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncMachine))), exports_Effect.mapError(() => new SettingsError({ message: `Cannot read ${file2}; fix or remove it.` })));
43806
+ if (yield* fs.exists(file2).pipe(exports_Effect.orElseSucceed(() => true)))
43807
+ return yield* read2;
43808
+ const machine = yield* SyncMachine.makeEffect({
43809
+ id: randomUUID(),
43810
+ label: hostname().trim() || "machine"
43811
+ }).pipe(exports_Effect.orDie);
43812
+ const created = yield* exports_Effect.gen(function* () {
43813
+ yield* fs.makeDirectory(directory, { recursive: true });
43814
+ const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
43815
+ directory,
43816
+ prefix: ".machine-"
43817
+ });
43818
+ const temporary = path.join(temporaryDirectory, "machine.json");
43819
+ yield* fs.writeFileString(temporary, `${JSON.stringify(machine, null, 2)}
43820
+ `, {
43821
+ flag: "wx",
43822
+ mode: 384
43823
+ });
43824
+ return yield* fs.link(temporary, file2).pipe(exports_Effect.as(true), exports_Effect.catchReason("PlatformError", "AlreadyExists", () => exports_Effect.succeed(false)));
43825
+ }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot create ${file2}.` })));
43826
+ return created ? machine : yield* read2;
43827
+ });
43828
+ var loadSyncSettings = exports_Effect.fn("Settings.loadSync")(function* (directory) {
43829
+ const fs = yield* exports_FileSystem.FileSystem;
43830
+ const path = yield* exports_Path.Path;
43831
+ const file2 = path.join(directory, "sync.json");
43832
+ const failure = new SettingsError({ message: `Cannot read or decode ${file2}.` });
43833
+ if (!(yield* fs.exists(file2).pipe(exports_Effect.mapError(() => failure))))
43834
+ return {};
43835
+ return yield* fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncSettings))), exports_Effect.mapError(() => failure));
43836
+ });
43837
+ var saveSyncSettings = exports_Effect.fn("Settings.saveSync")(function* (directory, server, token) {
43838
+ const fs = yield* exports_FileSystem.FileSystem;
43839
+ const path = yield* exports_Path.Path;
43840
+ const file2 = path.join(directory, "sync.json");
43841
+ yield* exports_Effect.gen(function* () {
43842
+ const settings = yield* exports_Schema.encodeEffect(SyncSettings)({ server, token });
43843
+ yield* fs.makeDirectory(directory, { recursive: true });
43844
+ const temporaryDirectory = yield* fs.makeTempDirectoryScoped({ directory, prefix: ".sync-" });
43845
+ const temporary = path.join(temporaryDirectory, "sync.json");
43846
+ yield* fs.writeFileString(temporary, `${JSON.stringify(settings, null, 2)}
43847
+ `, {
43848
+ flag: "wx",
43849
+ mode: 384
43850
+ });
43851
+ yield* fs.rename(temporary, file2);
43852
+ }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot save ${file2}.` })));
43853
+ return file2;
43854
+ });
43855
+
43856
+ // packages/cli/src/schedule.ts
43857
+ class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
43858
+ message: exports_Schema.String
43859
+ }) {
43860
+ }
43861
+ var TimeOfDay = exports_Schema.String.check(exports_Schema.isPattern(/^(?:[01]\d|2[0-3]):[0-5]\d$/));
43862
+ var Action3 = exports_Data.taggedEnum();
43863
+ var unit = "token-ledger-sync";
43864
+ var label = "com.github.ponbac.token-ledger.sync";
43865
+ var task = "token-ledger sync";
43866
+ var packageSpec = "@ponbac/token-ledger@latest";
43867
+ function run6(outcome, program, args2, hint = "") {
43868
+ return Action3.Run({
43869
+ program,
43870
+ args: args2,
43871
+ shown: [program, ...args2].join(" "),
43872
+ outcome,
43873
+ hint,
43874
+ gone: []
43481
43875
  });
43482
- return expandedLine;
43876
+ }
43877
+ function quotable(job, forbidden2, described) {
43878
+ const offending = [job.nodeDirectory, ...exports_Option.toArray(job.configHome), ...job.flags].find((value5) => forbidden2.test(value5));
43879
+ return offending === undefined ? exports_Effect.succeed(job) : exports_Effect.fail(new ScheduleError({
43880
+ message: `Cannot schedule with ${JSON.stringify(offending)}: it contains ${described}.`
43881
+ }));
43882
+ }
43883
+ var posixWord = (value5) => /^[\w@+=:,./-]+$/.test(value5) ? value5 : `'${value5.replaceAll("'", "'\\''")}'`;
43884
+ var posixScript = (job) => [
43885
+ "cd /",
43886
+ ...exports_Option.toArray(job.configHome).map((directory) => `export XDG_CONFIG_HOME=${posixWord(directory)}`),
43887
+ `export PATH=${posixWord(job.nodeDirectory)}:"$PATH"`,
43888
+ `exec npx --yes ${packageSpec} ${["sync", ...job.flags].map(posixWord).join(" ")}`
43889
+ ].join("; ");
43890
+ var posixJob = (job) => quotable(job, /\p{Cc}/u, "a control character");
43891
+ var systemdQuoted = (value5) => `"${value5.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("%", "%%").replaceAll("$", () => "$$")}"`;
43892
+ function systemdTimer(directory) {
43893
+ const service4 = `${directory}/${unit}.service`;
43894
+ const timer = `${directory}/${unit}.timer`;
43895
+ const systemctl = (outcome, args2, hint = "") => run6(outcome, "systemctl", ["--user", ...args2], hint);
43896
+ return {
43897
+ name: "systemd user timer",
43898
+ install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => [
43899
+ systemctl("required", ["daemon-reload"], "A systemd user session is required; without one, add the cron entry from the README."),
43900
+ Action3.Write({
43901
+ file: service4,
43902
+ contents: `[Unit]
43903
+ Description=Upload AI usage to toki2
43904
+
43905
+ [Service]
43906
+ Type=oneshot
43907
+ ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
43908
+ `
43909
+ }),
43910
+ Action3.Write({
43911
+ file: timer,
43912
+ contents: `[Unit]
43913
+ Description=Daily AI usage sync
43914
+
43915
+ [Timer]
43916
+ OnCalendar=*-*-* ${job2.at}:00
43917
+ Persistent=true
43918
+ RandomizedDelaySec=10m
43919
+
43920
+ [Install]
43921
+ WantedBy=timers.target
43922
+ `
43923
+ }),
43924
+ systemctl("required", ["daemon-reload"]),
43925
+ systemctl("required", ["enable", `${unit}.timer`]),
43926
+ systemctl("required", ["restart", `${unit}.timer`])
43927
+ ])),
43928
+ uninstall: [
43929
+ systemctl("reported", ["disable", "--now", `${unit}.timer`]),
43930
+ systemctl("reported", ["clean", "--what=state", `${unit}.timer`]),
43931
+ Action3.Remove({ file: service4 }),
43932
+ Action3.Remove({ file: timer }),
43933
+ systemctl("reported", ["daemon-reload"]),
43934
+ Action3.Run({
43935
+ ...systemctl("absent", ["is-active", "--quiet", `${unit}.timer`], "Cannot confirm that the timer is gone; systemd's reason is shown above."),
43936
+ gone: [3, 4]
43937
+ })
43938
+ ],
43939
+ status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])]
43940
+ };
43941
+ }
43942
+ var xmlText = (value5) => value5.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
43943
+ function launchAgent(home, uid) {
43944
+ const plist = `${home}/Library/LaunchAgents/${label}.plist`;
43945
+ const log3 = `${home}/Library/Logs/${unit}.log`;
43946
+ const domain = `gui/${uid}`;
43947
+ return {
43948
+ name: "launchd agent",
43949
+ install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => {
43950
+ const [hour2, minute] = job2.at.split(":").map(Number);
43951
+ return [
43952
+ Action3.Write({
43953
+ file: plist,
43954
+ contents: `<?xml version="1.0" encoding="UTF-8"?>
43955
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
43956
+ <plist version="1.0">
43957
+ <dict>
43958
+ <key>Label</key>
43959
+ <string>${label}</string>
43960
+ <key>ProgramArguments</key>
43961
+ <array>
43962
+ <string>/bin/zsh</string>
43963
+ <string>-lc</string>
43964
+ <string>${xmlText(posixScript(job2))}</string>
43965
+ </array>
43966
+ <key>RunAtLoad</key>
43967
+ <true/>
43968
+ <key>StartCalendarInterval</key>
43969
+ <dict>
43970
+ <key>Hour</key>
43971
+ <integer>${hour2}</integer>
43972
+ <key>Minute</key>
43973
+ <integer>${minute}</integer>
43974
+ </dict>
43975
+ <key>StandardOutPath</key>
43976
+ <string>${xmlText(log3)}</string>
43977
+ <key>StandardErrorPath</key>
43978
+ <string>${xmlText(log3)}</string>
43979
+ </dict>
43980
+ </plist>
43981
+ `
43982
+ }),
43983
+ run6("silent", "launchctl", ["bootout", `${domain}/${label}`]),
43984
+ run6("required", "launchctl", ["bootstrap", domain, plist])
43985
+ ];
43986
+ })),
43987
+ uninstall: [
43988
+ run6("reported", "launchctl", ["bootout", `${domain}/${label}`]),
43989
+ Action3.Remove({ file: plist }),
43990
+ run6("absent", "launchctl", ["print", `${domain}/${label}`], "The agent is still loaded; launchd's reason is shown above.")
43991
+ ],
43992
+ status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])]
43993
+ };
43994
+ }
43995
+ var cmdWord = (value5) => /^[\w@+=:,./\\-]+$/.test(value5) ? value5 : `"${value5}"`;
43996
+ var powershellString = (value5) => `'${value5.replaceAll("'", "''")}'`;
43997
+ var powershellOptions = ["-NoProfile", "-NonInteractive", "-EncodedCommand"];
43998
+ var powershellArguments = (script) => [
43999
+ ...powershellOptions,
44000
+ Buffer.from(script, "utf16le").toString("base64")
44001
+ ];
44002
+ var taskScheduler = {
44003
+ name: "Task Scheduler task",
44004
+ install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
44005
+ const command = [
44006
+ ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
44007
+ `set "PATH=${job2.nodeDirectory};%PATH%"`,
44008
+ `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
44009
+ ].join(" && ");
44010
+ const script = [
44011
+ "$ErrorActionPreference = 'Stop'",
44012
+ "$ProgressPreference = 'SilentlyContinue'",
44013
+ `$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument ${powershellString(`/d /v:off /s /c "${command}"`)}`,
44014
+ `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
44015
+ "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44016
+ `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44017
+ ].join(`
44018
+ `);
44019
+ return [
44020
+ Action3.Run({
44021
+ program: "powershell.exe",
44022
+ args: powershellArguments(script),
44023
+ shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
44024
+ ${script}`,
44025
+ outcome: "required",
44026
+ hint: "",
44027
+ gone: []
44028
+ })
44029
+ ];
44030
+ })),
44031
+ uninstall: [
44032
+ run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44033
+ run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above.")
44034
+ ],
44035
+ status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
43483
44036
  };
43484
- var restoreStylesAcrossRows = (preString) => {
43485
- let returnValue = "";
43486
- let activeHyperlink;
43487
- const activeStyles = [];
43488
- let index2 = 0;
43489
- let copiedIndex = 0;
43490
- while (index2 < preString.length) {
43491
- ROW_BOUNDARY_REGEX.lastIndex = index2;
43492
- const boundary = ROW_BOUNDARY_REGEX.exec(preString);
43493
- if (!boundary) {
43494
- break;
43495
- }
43496
- index2 = boundary.index;
43497
- if (boundary[0] !== `
43498
- `) {
43499
- const escape2 = matchAnsiEscape(preString, index2);
43500
- if (!escape2) {
43501
- index2++;
43502
- continue;
43503
- }
43504
- const { groups } = escape2;
43505
- if (groups.sgr !== undefined) {
43506
- applySgrParameters(groups.sgr, activeStyles);
43507
- } else if (groups.uri !== undefined) {
43508
- activeHyperlink = groups.uri.length === 0 ? undefined : { parameters: groups.parameters, uri: groups.uri };
43509
- }
43510
- index2 += escape2[0].length;
43511
- continue;
43512
- }
43513
- returnValue += preString.slice(copiedIndex, index2);
43514
- if (index2 > copiedIndex) {
43515
- if (activeHyperlink) {
43516
- returnValue += wrapAnsiHyperlink("");
44037
+ var hostScheduler = exports_Effect.gen(function* () {
44038
+ const path = yield* exports_Path.Path;
44039
+ const home = homedir2();
44040
+ const units = exports_Option.getOrElse(yield* configHome, () => path.join(home, ".config"));
44041
+ return yield* exports_Match.value(process.platform).pipe(exports_Match.when("linux", () => exports_Effect.succeed(systemdTimer(path.join(units, "systemd", "user")))), exports_Match.when("darwin", () => exports_Effect.succeed(launchAgent(home, userInfo().uid))), exports_Match.when("win32", () => exports_Effect.succeed(taskScheduler)), exports_Match.orElse((platform) => exports_Effect.fail(new ScheduleError({
44042
+ message: `No scheduler is supported on ${platform}; schedule token-ledger sync yourself.`
44043
+ }))));
44044
+ });
44045
+ var describe = (actions) => actions.map(Action3.$match({
44046
+ Write: ({ file: file2, contents }) => `write ${file2}
44047
+ ${contents.replaceAll(/^(?=.)/gm, " ")}`,
44048
+ Remove: ({ file: file2 }) => `remove ${file2}
44049
+ `,
44050
+ Run: ({ shown }) => `run ${shown}
44051
+ `
44052
+ })).join(`
44053
+ `);
44054
+ var perform = exports_Effect.fn("Schedule.perform")(function* (actions) {
44055
+ const fs = yield* exports_FileSystem.FileSystem;
44056
+ const path = yield* exports_Path.Path;
44057
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44058
+ for (const action of actions)
44059
+ yield* Action3.$match(action, {
44060
+ Write: ({ file: file2, contents }) => fs.makeDirectory(path.dirname(file2), { recursive: true }).pipe(exports_Effect.andThen(fs.writeFileString(file2, contents)), exports_Effect.mapError(() => new ScheduleError({ message: `Cannot write ${file2}.` }))),
44061
+ Remove: ({ file: file2 }) => fs.remove(file2, { force: true }).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot remove ${file2}.` }))),
44062
+ Run: ({ program, args: args2, outcome, hint, gone }) => {
44063
+ const output = outcome === "silent" || outcome === "absent" ? "ignore" : "inherit";
44064
+ const exit3 = spawner.exitCode(exports_ChildProcess.make(program, args2, { stdin: "ignore", stdout: output, stderr: output })).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot run ${program}. ${hint}`.trim() })));
44065
+ return exports_Match.value(outcome).pipe(exports_Match.when("required", () => exports_Effect.filterOrFail(exit3, (code) => code === 0, (code) => new ScheduleError({
44066
+ message: `${[program, ...args2.slice(0, 2)].join(" ")} failed with exit code ${code}. ${hint}`.trim()
44067
+ }))), exports_Match.when("reported", () => exit3), exports_Match.when("silent", () => exports_Effect.ignore(exit3)), exports_Match.when("absent", () => exit3.pipe(exports_Effect.map((code) => gone.length === 0 ? code !== 0 : gone.includes(code)), exports_Effect.orElseSucceed(() => true), exports_Effect.filterOrFail((confirmed) => confirmed, () => new ScheduleError({ message: hint })))), exports_Match.exhaustive);
43517
44068
  }
43518
- returnValue += getClosingSgrSequence(activeStyles);
43519
- }
43520
- returnValue += `
44069
+ });
44070
+ });
44071
+
44072
+ // packages/cli/src/copilot.ts
44073
+ class CopilotError extends exports_Schema.TaggedError()("CopilotError", {
44074
+ message: exports_Schema.String
44075
+ }) {
44076
+ }
44077
+ var variable = "COPILOT_OTEL_FILE_EXPORTER_PATH";
44078
+ var marker = "# Added by token-ledger copilot enable: Copilot CLI records its usage here.";
44079
+ var affectedVersion = "1.139.1";
44080
+ var builds = [
44081
+ { name: "VS Code", folder: "Code", file: "vscode-chat.jsonl" },
44082
+ { name: "VS Code Insiders", folder: "Code - Insiders", file: "vscode-insiders-chat.jsonl" }
44083
+ ];
44084
+ var placed = exports_Effect.fn("Copilot.placed")(function* (directory, file2) {
44085
+ const fs = yield* exports_FileSystem.FileSystem;
44086
+ const path = yield* exports_Path.Path;
44087
+ const resolved = (folder) => fs.realPath(folder).pipe(exports_Effect.orElseSucceed(() => folder));
44088
+ const relative = path.relative(yield* resolved(directory), path.join(yield* resolved(path.dirname(file2)), path.basename(file2)));
44089
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) ? exports_Option.some(relative) : exports_Option.none();
44090
+ });
44091
+ var copilotSources = exports_Effect.fn("Copilot.sources")(function* (directory, exporter) {
44092
+ if (exports_Option.isNone(exporter))
44093
+ return [directory];
44094
+ const relative = yield* placed(directory, exporter.value);
44095
+ if (exports_Option.isNone(relative))
44096
+ return [exporter.value];
44097
+ return /\.(?:jsonl|db)$/.test(relative.value) || relative.value === "" ? [directory] : [directory, exporter.value];
44098
+ });
44099
+ var Action4 = exports_Data.taggedEnum();
44100
+ var Step = exports_Data.taggedEnum();
44101
+ var indented = (text2, width2) => text2.replaceAll(/^(?=.)/gm, " ".repeat(width2));
44102
+ function assignedValue(assigned, home) {
44103
+ const text2 = assigned.trim();
44104
+ const single = /^'([^']*)'$/.exec(text2);
44105
+ if (single !== null)
44106
+ return exports_Option.fromUndefinedOr(single[1]);
44107
+ const double = /^"([^"\\`]*)"$/.exec(text2)?.[1];
44108
+ const bare = /^([^\s"'`\\;&|<>()#]+)$/.exec(text2)?.[1]?.replace(/^~(?=\/)/, () => home);
44109
+ const expanding = double ?? bare;
44110
+ if (expanding === undefined)
44111
+ return exports_Option.none();
44112
+ const expanded = expanding.replaceAll(/\$HOME\b|\$\{HOME\}/g, () => home);
44113
+ return expanded.includes("$") ? exports_Option.none() : exports_Option.some(expanded);
44114
+ }
44115
+ var touches = (line) => !/^\s*#/.test(line) && new RegExp(`(?<![$\\w{])${variable}\\b`).test(line);
44116
+ var StartupEdit = exports_Data.taggedEnum();
44117
+ var exportsTo = (target, home) => (line) => exports_Option.contains(exports_Option.flatMap(exports_Option.fromUndefinedOr(new RegExp(`^\\s*export\\s+${variable}=(.*)$`).exec(line)?.[1]), (assigned) => assignedValue(assigned, home)), target);
44118
+ function startupEdit(contents, wanted, satisfies) {
44119
+ const lines2 = contents.split(`
44120
+ `);
44121
+ const index2 = lines2.findLastIndex(touches);
44122
+ const current = lines2[index2];
44123
+ if (current === undefined) {
44124
+ const lead = contents === "" ? "" : contents.endsWith(`
44125
+ `) ? `
44126
+ ` : `
44127
+
43521
44128
  `;
43522
- index2++;
43523
- copiedIndex = index2;
43524
- if (index2 < preString.length && preString[index2] !== `
43525
- `) {
43526
- const openingStyles = [...activeStyles];
43527
- applyLeadingSgrResets(preString, index2, openingStyles);
43528
- returnValue += getOpeningSgrSequence(openingStyles);
43529
- if (activeHyperlink) {
43530
- returnValue += wrapAnsiHyperlink(activeHyperlink.uri, activeHyperlink.parameters);
43531
- }
43532
- }
44129
+ return exports_Option.some(StartupEdit.Append({ text: `${lead}${marker}
44130
+ ${wanted}
44131
+ ` }));
43533
44132
  }
43534
- return returnValue + preString.slice(copiedIndex);
43535
- };
43536
- var exec = (string4, columns, options3 = {}) => {
43537
- if (options3.trim !== false && string4.trim() === "") {
43538
- return "";
44133
+ if (current === wanted || satisfies(current))
44134
+ return exports_Option.none();
44135
+ return exports_Option.some(lines2[index2 - 1] === marker ? StartupEdit.Replace({ contents: lines2.with(index2, wanted).join(`
44136
+ `) }) : StartupEdit.Conflict({ line: index2 + 1, text: current.trim() }));
44137
+ }
44138
+ function homeWord(path, host, file2, quoted) {
44139
+ const relative = path.relative(host.home, file2);
44140
+ return /^(?!\.\.)[\w@+=:,./-]+$/.test(relative) && !path.isAbsolute(relative) ? `"$HOME/${relative}"` : quoted(file2);
44141
+ }
44142
+ var fishWord = (value5) => /^[\w@+=:,./-]+$/.test(value5) ? value5 : `'${value5.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
44143
+ var readOptional = exports_Effect.fn("Copilot.readOptional")(function* (file2) {
44144
+ const fs = yield* exports_FileSystem.FileSystem;
44145
+ return yield* fs.readFileString(file2).pipe(exports_Effect.map(exports_Option.some), exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.succeed(exports_Option.none())));
44146
+ });
44147
+ var bashStartup = exports_Effect.fn("Copilot.bashStartup")(function* (host) {
44148
+ const fs = yield* exports_FileSystem.FileSystem;
44149
+ const path = yield* exports_Path.Path;
44150
+ if (host.platform !== "darwin")
44151
+ return path.join(host.home, ".bashrc");
44152
+ for (const name of [".bash_profile", ".bash_login", ".profile"]) {
44153
+ const file2 = path.join(host.home, name);
44154
+ if (yield* fs.exists(file2).pipe(exports_Effect.orElseSucceed(() => false)))
44155
+ return file2;
43539
44156
  }
43540
- const words = splitWords(string4);
43541
- let rows = [""];
43542
- let rowLength = 0;
43543
- let trimmedRowIndex = -1;
43544
- let isFirstWord = true;
43545
- for (const word of words) {
43546
- const rowIndex = rows.length - 1;
43547
- if (options3.trim !== false && trimmedRowIndex !== rowIndex) {
43548
- const row = rows[rowIndex];
43549
- const trimmedRow = row.trimStart();
43550
- if (trimmedRow.length !== row.length) {
43551
- rows[rowIndex] = trimmedRow;
43552
- rowLength = getWidth(trimmedRow);
43553
- }
43554
- if (trimmedRow.length > 0) {
43555
- trimmedRowIndex = rowIndex;
43556
- }
43557
- }
43558
- if (isFirstWord) {
43559
- isFirstWord = false;
43560
- } else {
43561
- if (rowLength >= columns && (options3.wordWrap === false || options3.trim === false)) {
43562
- rows.push("");
43563
- rowLength = 0;
43564
- }
43565
- if (rowLength > 0 || options3.trim === false) {
43566
- rows[rows.length - 1] += " ";
43567
- rowLength++;
43568
- }
43569
- }
43570
- if (options3.hard && options3.wordWrap !== false && word.width > columns) {
43571
- const remainingColumns = columns - rowLength;
43572
- const breaksStartingThisLine = 1 + Math.floor((word.width - remainingColumns - 1) / columns);
43573
- const breaksStartingNextLine = Math.floor((word.width - 1) / columns);
43574
- if (breaksStartingNextLine < breaksStartingThisLine) {
43575
- rows.push("");
43576
- rowLength = 0;
43577
- }
43578
- rowLength = wrapWord(rows, word.value, columns, rowLength);
44157
+ return path.join(host.home, ".bash_profile");
44158
+ });
44159
+ var startupSteps = exports_Effect.fn("Copilot.startupSteps")(function* (host, target) {
44160
+ const fs = yield* exports_FileSystem.FileSystem;
44161
+ const path = yield* exports_Path.Path;
44162
+ const shell = exports_Option.match(host.shell, {
44163
+ onNone: () => "",
44164
+ onSome: (file3) => path.basename(file3)
44165
+ });
44166
+ const exported = `export ${variable}=${homeWord(path, host, target, posixWord)}`;
44167
+ const posix2 = (file3) => ({
44168
+ file: file3,
44169
+ line: exported,
44170
+ satisfies: exportsTo(target, host.home),
44171
+ others: []
44172
+ });
44173
+ const startup = yield* exports_Match.value(shell).pipe(exports_Match.when("zsh", () => exports_Effect.succeed(exports_Option.some(posix2(path.join(exports_Option.getOrElse(host.zshDirectory, () => host.home), ".zshrc"))))), exports_Match.when("bash", () => exports_Effect.map(bashStartup(host), (file3) => exports_Option.some(posix2(file3)))), exports_Match.when("fish", () => {
44174
+ const directory = path.join(exports_Option.getOrElse(host.configHome, () => path.join(host.home, ".config")), "fish");
44175
+ const line2 = `set -gx ${variable} ${homeWord(path, host, target, fishWord)}`;
44176
+ const snippets = path.join(directory, "conf.d");
44177
+ const file3 = path.join(snippets, "token-ledger-copilot.fish");
44178
+ return fs.readDirectory(snippets).pipe(exports_Effect.orElseSucceed(() => []), exports_Effect.map((names) => exports_Option.some({
44179
+ file: file3,
44180
+ line: line2,
44181
+ satisfies: (text2) => text2.trim() === line2,
44182
+ others: [
44183
+ ...names.toSorted((a, b) => a.localeCompare(b)).flatMap((name) => name.endsWith(".fish") && path.join(snippets, name) !== file3 ? [path.join(snippets, name)] : []),
44184
+ path.join(directory, "config.fish")
44185
+ ]
44186
+ })));
44187
+ }), exports_Match.orElse(() => exports_Effect.succeed(exports_Option.none())));
44188
+ if (exports_Option.isNone(startup))
44189
+ return [
44190
+ Step.ByHand({
44191
+ part: "cli",
44192
+ reason: shell === "" ? "SHELL is not set, so there is no startup file to choose." : `${shell} is not a shell this command sets up; it knows bash, zsh, and fish.`,
44193
+ instructions: `Add the equivalent of this line to your shell's startup file:
44194
+ ${indented(exported, 4)}`
44195
+ })
44196
+ ];
44197
+ const { file: file2, line, satisfies, others: others2 } = startup.value;
44198
+ const byHand = `Add this line to ${file2}:
44199
+ ${indented(line, 4)}`;
44200
+ const conflict = (where, found) => Step.ByHand({
44201
+ part: "cli",
44202
+ reason: `${where}, and was left alone:
44203
+ ${indented(found, 4)}`,
44204
+ instructions: `To record Copilot CLI usage where token-ledger reads it, change that line to:
44205
+ ${indented(line, 4)}`
44206
+ });
44207
+ const read2 = yield* exports_Effect.all([
44208
+ readOptional(file2),
44209
+ exports_Effect.forEach(others2, (other) => exports_Effect.map(readOptional(other), (text2) => ({
44210
+ other,
44211
+ found: exports_Option.getOrElse(text2, () => "").split(`
44212
+ `).find(touches)
44213
+ })))
44214
+ ]).pipe(exports_Effect.option);
44215
+ if (exports_Option.isNone(read2))
44216
+ return [Step.ByHand({ part: "cli", reason: `Cannot read ${file2}.`, instructions: byHand })];
44217
+ const [original, mentions] = read2.value;
44218
+ for (const { other, found } of mentions)
44219
+ if (found !== undefined)
44220
+ return [conflict(`${other} already sets ${variable}`, found.trim())];
44221
+ const existing = exports_Option.getOrElse(original, () => "");
44222
+ return [
44223
+ exports_Option.match(startupEdit(existing, line, satisfies), {
44224
+ onNone: () => Step.Kept({ part: "cli", summary: `${file2} already exports ${variable}.` }),
44225
+ onSome: StartupEdit.$match({
44226
+ Append: ({ text: text2 }) => Step.Change({
44227
+ part: "cli",
44228
+ summary: `${exports_Option.isSome(original) ? "add to the end of" : "create"} ${file2}`,
44229
+ detail: [marker, line],
44230
+ action: Action4.Write({ file: file2, contents: `${existing}${text2}`, original }),
44231
+ byHand
44232
+ }),
44233
+ Replace: ({ contents }) => Step.Change({
44234
+ part: "cli",
44235
+ summary: `correct the line this command added to ${file2}`,
44236
+ detail: [line],
44237
+ action: Action4.Write({ file: file2, contents, original }),
44238
+ byHand
44239
+ }),
44240
+ Conflict: ({ line: number4, text: text2 }) => conflict(`${file2} already sets ${variable} on line ${number4}`, text2)
44241
+ })
44242
+ })
44243
+ ];
44244
+ });
44245
+ var userVariableSteps = exports_Effect.fn("Copilot.userVariableSteps")(function* (target) {
44246
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44247
+ const assignment = `[Environment]::SetEnvironmentVariable(${powershellString(variable)}, ${powershellString(target)}, 'User')`;
44248
+ const byHand = `Run this in PowerShell:
44249
+ ${indented(assignment, 4)}`;
44250
+ const current = yield* spawner.string(exports_ChildProcess.make("powershell.exe", powershellArguments(`[Console]::Out.Write('value=' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string][Environment]::GetEnvironmentVariable(${powershellString(variable)}, 'User'))))`), { stdin: "ignore", stderr: "ignore" })).pipe(exports_Effect.map((output) => /^value=([A-Za-z0-9+/=]*)\s*$/.exec(output)?.[1]), exports_Effect.map(exports_Option.fromUndefinedOr), exports_Effect.orElseSucceed(() => exports_Option.none()), exports_Effect.map(exports_Option.map((encoded) => Buffer.from(encoded, "base64").toString("utf8"))));
44251
+ if (exports_Option.isNone(current))
44252
+ return [
44253
+ Step.ByHand({
44254
+ part: "cli",
44255
+ reason: `Cannot read the user environment variable ${variable} through PowerShell.`,
44256
+ instructions: byHand
44257
+ })
44258
+ ];
44259
+ const comparable = (file2) => file2.replaceAll("/", "\\").toLowerCase();
44260
+ return [
44261
+ comparable(current.value) === comparable(target) ? Step.Kept({
44262
+ part: "cli",
44263
+ summary: `The user environment variable ${variable} is already set.`
44264
+ }) : Step.Change({
44265
+ part: "cli",
44266
+ summary: `set the user environment variable ${variable}`,
44267
+ detail: [current.value === "" ? target : `${target} (now ${current.value})`],
44268
+ action: Action4.Run({
44269
+ program: "powershell.exe",
44270
+ args: powershellArguments([
44271
+ "$ErrorActionPreference = 'Stop'",
44272
+ "$ProgressPreference = 'SilentlyContinue'",
44273
+ assignment
44274
+ ].join(`
44275
+ `))
44276
+ }),
44277
+ byHand
44278
+ })
44279
+ ];
44280
+ });
44281
+ var installedVersion = exports_Effect.fn("Copilot.installedVersion")(function* (host) {
44282
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44283
+ const commands = host.platform === "win32" ? [exports_ChildProcess.make("cmd.exe", ["/d", "/s", "/c", "code --version"])] : [
44284
+ "code",
44285
+ ...host.platform === "darwin" ? ["/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"] : []
44286
+ ].map((program) => exports_ChildProcess.make(program, ["--version"]));
44287
+ for (const command of commands) {
44288
+ const version = yield* spawner.lines(command).pipe(exports_Effect.timeoutOption("5 seconds"), exports_Effect.map(exports_Option.flatMap((lines2) => exports_Option.fromUndefinedOr(lines2[0]))), exports_Effect.map(exports_Option.filter((line) => /^\d+\.\d+\.\d+$/.test(line))), exports_Effect.orElseSucceed(() => exports_Option.none()));
44289
+ if (exports_Option.isSome(version))
44290
+ return version;
44291
+ }
44292
+ return exports_Option.none();
44293
+ });
44294
+ var settingsSteps = exports_Effect.fn("Copilot.settingsSteps")(function* (host, directory) {
44295
+ const fs = yield* exports_FileSystem.FileSystem;
44296
+ const path = yield* exports_Path.Path;
44297
+ const root = exports_Match.value(host.platform).pipe(exports_Match.when("win32", () => exports_Option.getOrElse(host.appData, () => path.join(host.home, "AppData", "Roaming"))), exports_Match.when("darwin", () => path.join(host.home, "Library", "Application Support")), exports_Match.orElse(() => exports_Option.getOrElse(host.configHome, () => path.join(host.home, ".config"))));
44298
+ const properties = (file2) => [
44299
+ ["github.copilot.chat.otel.enabled", true],
44300
+ ["github.copilot.chat.otel.exporterType", "file"],
44301
+ ["github.copilot.chat.otel.outfile", path.join(directory, file2).replaceAll("\\", "/")],
44302
+ ["github.copilot.chat.otel.captureContent", false]
44303
+ ];
44304
+ const unsynced = [
44305
+ ["settingsSync.ignoredSettings", "github.copilot.chat.otel.outfile"]
44306
+ ];
44307
+ const unsyncing = unsynced.map(([key, item]) => `add ${JSON.stringify(item)} to the ${JSON.stringify(key)} list, so that Settings Sync does not copy this machine's path to your other machines`);
44308
+ const byHand = (lines2, lists) => [
44309
+ ...lines2.length === 0 ? [] : [
44310
+ `In VS Code, run "Preferences: Open User Settings (JSON)" from the Command Palette; in a profile other than the default, run "Preferences: Open Application Settings (JSON)" instead, where settings shared by all profiles are kept. Give each of these settings the value shown: change its line if the setting is already there, and paste the others on a new line right after the opening {
44311
+ ${indented(lines2.map((line) => `${line},`).join(`
44312
+ `), 4)}`
44313
+ ],
44314
+ ...lists.map((list) => `In the same file, ${list}.`)
44315
+ ].join(`
44316
+ `);
44317
+ const every4 = (file2) => byHand(properties(file2).map(([key, value5]) => `${JSON.stringify(key)}: ${JSON.stringify(value5)}`), unsyncing);
44318
+ const steps = [];
44319
+ for (const build2 of builds) {
44320
+ const user = path.join(root, build2.folder, "User");
44321
+ const file2 = path.join(user, "settings.json");
44322
+ if (!(yield* fs.exists(user).pipe(exports_Effect.orElseSucceed(() => false))))
43579
44323
  continue;
43580
- }
43581
- if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
43582
- if (options3.wordWrap === false && rowLength < columns) {
43583
- rowLength = wrapWord(rows, word.value, columns, rowLength);
43584
- continue;
43585
- }
43586
- rows.push("");
43587
- rowLength = 0;
43588
- }
43589
- if (rowLength + word.width > columns && options3.wordWrap === false) {
43590
- rowLength = wrapWord(rows, word.value, columns, rowLength);
44324
+ const original = yield* readOptional(file2).pipe(exports_Effect.option);
44325
+ if (exports_Option.isNone(original)) {
44326
+ steps.push(Step.ByHand({
44327
+ part: "vscode",
44328
+ reason: `Cannot read ${file2}.`,
44329
+ instructions: every4(build2.file)
44330
+ }));
43591
44331
  continue;
43592
44332
  }
43593
- rows[rows.length - 1] += word.value;
43594
- rowLength += word.width;
44333
+ steps.push(exports_Option.match(setProperties(exports_Option.getOrElse(original.value, () => ""), properties(build2.file), unsynced), {
44334
+ onNone: () => Step.ByHand({
44335
+ part: "vscode",
44336
+ reason: `${file2} has a syntax error, repeats one of these settings, or holds one in a form this command does not expect, so it was left alone.`,
44337
+ instructions: `Repair it first: VS Code marks what is wrong, and a repeated setting should be there once. Then run this command again, or finish by hand.
44338
+ ${every4(build2.file)}`
44339
+ }),
44340
+ onSome: ({ text: text2, changes: changes2, included }) => changes2.length === 0 && included.length === 0 ? Step.Kept({ part: "vscode", summary: `${file2} already has the export settings.` }) : Step.Change({
44341
+ part: "vscode",
44342
+ summary: `${exports_Option.isSome(original.value) ? "edit" : "create"} ${file2}`,
44343
+ detail: [
44344
+ ...changes2.map(({ key, value: value5, previous }) => `${JSON.stringify(key)}: ${value5}${exports_Option.match(previous, {
44345
+ onNone: () => "",
44346
+ onSome: (was) => ` (now ${was})`
44347
+ })}`),
44348
+ ...included.length === 0 ? [] : unsyncing
44349
+ ],
44350
+ action: Action4.Write({ file: file2, contents: text2, original: original.value }),
44351
+ byHand: byHand(changes2.map(({ key, value: value5 }) => `${JSON.stringify(key)}: ${value5}`), included.length === 0 ? [] : unsyncing)
44352
+ })
44353
+ }));
43595
44354
  }
43596
- if (options3.trim !== false) {
43597
- rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
44355
+ if (steps.length === 0)
44356
+ return [
44357
+ Step.ByHand({
44358
+ part: "vscode",
44359
+ reason: `No VS Code settings folder at ${path.join(root, builds[0].folder, "User")}.`,
44360
+ instructions: every4(builds[0].file)
44361
+ })
44362
+ ];
44363
+ if (exports_Option.contains(yield* installedVersion(host), affectedVersion))
44364
+ steps.push(Step.Note({
44365
+ part: "vscode",
44366
+ text: `VS Code ${affectedVersion} is installed. Its file export leaves out the repository, so Chat usage is counted but stays Unassigned. Update VS Code, or see "Workaround for VS Code's file exporter bug" in the token-ledger README.`
44367
+ }));
44368
+ return steps;
44369
+ });
44370
+ var plan = exports_Effect.fn("Copilot.plan")(function* (host, wanted) {
44371
+ const fs = yield* exports_FileSystem.FileSystem;
44372
+ const path = yield* exports_Path.Path;
44373
+ if (exports_Option.contains(host.uid, 0) && !wanted.allowRoot)
44374
+ return yield* new CopilotError({
44375
+ message: "Run this as yourself, without sudo. As root, the export folder, your shell startup file, and VS Code's settings would end up owned by root, and Copilot and VS Code could no longer write them. Nothing here needs admin rights. If root really is the account that runs Copilot, as in some containers, add --allow-root."
44376
+ });
44377
+ const directory = path.join(host.copilotHome, "otel");
44378
+ const target = path.join(directory, "usage.jsonl");
44379
+ const existing = yield* fs.stat(directory).pipe(exports_Effect.map((info2) => exports_Option.some(info2.type)), exports_Effect.orElseSucceed(() => exports_Option.none()));
44380
+ if (exports_Option.isSome(existing) && existing.value !== "Directory")
44381
+ return yield* new CopilotError({
44382
+ message: `${directory} exists but is not a folder, so Copilot cannot write its export there. Move it away, then run this again.`
44383
+ });
44384
+ for (const entry of [
44385
+ directory,
44386
+ ...wanted.cli ? [target] : [],
44387
+ ...wanted.vscode ? builds.map((build2) => path.join(directory, build2.file)) : []
44388
+ ]) {
44389
+ const folder = yield* fs.stat(entry).pipe(exports_Effect.map((info2) => entry !== directory && info2.type === "Directory"), exports_Effect.orElseSucceed(() => false));
44390
+ if (folder)
44391
+ return yield* new CopilotError({
44392
+ message: `${entry} is a folder, so Copilot cannot write its export to that name. Move it away, then run this again.`
44393
+ });
44394
+ const locked = yield* fs.access(entry, { writable: true }).pipe(exports_Effect.as(false), exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.succeed(false)), exports_Effect.orElseSucceed(() => true));
44395
+ if (locked)
44396
+ return yield* new CopilotError({
44397
+ message: `Your account cannot write to ${entry}, so Copilot could not record its usage there. Give your account write access to it, then run this again.${host.platform === "win32" ? "" : ` If it was created with sudo, take it back with: sudo chown -R "$(id -un)" ${posixWord(directory)}`}`
44398
+ });
43598
44399
  }
43599
- return restoreStylesAcrossRows(rows.join(`
43600
- `));
43601
- };
43602
- var normalizeText = (string4) => {
43603
- let normalizedString = "";
43604
- forEachSegment(string4, (plainText) => {
43605
- normalizedString += plainText.normalize();
43606
- }, (escape2) => {
43607
- normalizedString += escape2;
43608
- });
43609
- return normalizedString;
43610
- };
43611
- function wrapAnsi(string4, columns, options3) {
43612
- return normalizeText(String(string4)).replaceAll(`\r
43613
- `, `
43614
- `).split(`
43615
- `).map((line) => exec(expandTabs(line), columns, options3)).join(`
44400
+ const steps = [
44401
+ ...exports_Option.isSome(existing) ? [] : [
44402
+ Step.Change({
44403
+ part: "folder",
44404
+ summary: `create the folder ${directory}`,
44405
+ detail: [],
44406
+ action: Action4.MakeDirectory({ directory }),
44407
+ byHand: ""
44408
+ })
44409
+ ],
44410
+ ...wanted.cli ? yield* host.platform === "win32" ? userVariableSteps(target) : startupSteps(host, target) : [],
44411
+ ...wanted.vscode ? yield* settingsSteps(host, directory) : []
44412
+ ];
44413
+ const elsewhere = exports_Option.isSome(host.exporter) ? exports_Option.match(yield* placed(directory, host.exporter.value), {
44414
+ onNone: () => host.exporter,
44415
+ onSome: () => exports_Option.none()
44416
+ }) : exports_Option.none();
44417
+ const settled = steps.some((step) => step.part === "cli" && (Step.$is("Change")(step) || Step.$is("Kept")(step)));
44418
+ return {
44419
+ directory,
44420
+ steps: exports_Option.match(elsewhere, {
44421
+ onNone: () => steps,
44422
+ onSome: (file2) => [
44423
+ ...steps,
44424
+ Step.Note({
44425
+ part: "cli",
44426
+ text: `This terminal has ${variable} set to ${file2}, outside ${directory}. While it is, reports and syncs that see the variable read only that file and skip the exports in ${directory}, VS Code's among them. ${settled ? `Run them from a new terminal; if it still has that value, something else sets it, and should name ${target} instead.` : `Point it at ${target} to have both read.`}`
44427
+ })
44428
+ ]
44429
+ })
44430
+ };
44431
+ });
44432
+ var entries3 = (steps, tag4, render) => steps.flatMap((step) => Step.$is(tag4)(step) ? [indented(render(step), 2)] : []);
44433
+ var leftByHand = (steps) => entries3(steps, "ByHand", ({ reason, instructions }) => `${reason}
44434
+ ${instructions}`);
44435
+ var notes = (steps) => entries3(steps, "Note", ({ text: text2 }) => text2);
44436
+ var sections = (parts2) => parts2.flatMap(([title, lines2]) => lines2.length === 0 ? [] : [`${title}
44437
+
44438
+ ${lines2.join(lines2.some((line) => line.includes(`
44439
+ `)) ? `
44440
+
44441
+ ` : `
44442
+ `)}`]).join(`
44443
+
43616
44444
  `);
44445
+ var describe2 = (steps) => sections([
44446
+ [
44447
+ "Copilot records no usage until its local export is switched on. This will:",
44448
+ entries3(steps, "Change", ({ summary, detail }) => [summary, ...detail.map((line) => indented(line, 4))].join(`
44449
+ `))
44450
+ ],
44451
+ ["Already in place:", entries3(steps, "Kept", ({ summary }) => summary)],
44452
+ ["Left for you to do by hand:", leftByHand(steps)],
44453
+ ["Note:", notes(steps)]
44454
+ ]);
44455
+ var replaceFile = exports_Effect.fn("Copilot.replaceFile")(function* (file2, contents) {
44456
+ const fs = yield* exports_FileSystem.FileSystem;
44457
+ const path = yield* exports_Path.Path;
44458
+ yield* exports_Effect.gen(function* () {
44459
+ const target = yield* fs.realPath(file2).pipe(exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.matchEffect(fs.readLink(file2), {
44460
+ onFailure: () => exports_Effect.succeed(file2),
44461
+ onSuccess: (destination) => exports_Effect.fail(new CopilotError({
44462
+ message: `${file2} is a link to ${destination}, which does not exist, so it was left alone.`
44463
+ }))
44464
+ })));
44465
+ const mode = yield* fs.stat(target).pipe(exports_Effect.map((info2) => exports_Option.some(info2.mode & 4095)), exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.succeed(exports_Option.none())));
44466
+ yield* fs.makeDirectory(path.dirname(target), { recursive: true });
44467
+ const temporary = path.join(yield* fs.makeTempDirectoryScoped({
44468
+ directory: path.dirname(target),
44469
+ prefix: ".token-ledger-"
44470
+ }), path.basename(target));
44471
+ yield* fs.writeFileString(temporary, contents);
44472
+ if (exports_Option.isSome(mode))
44473
+ yield* fs.chmod(temporary, mode.value);
44474
+ yield* fs.rename(temporary, target);
44475
+ }).pipe(exports_Effect.scoped);
44476
+ });
44477
+ var perform2 = exports_Effect.fn("Copilot.perform")(function* (steps) {
44478
+ const fs = yield* exports_FileSystem.FileSystem;
44479
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44480
+ const results2 = [];
44481
+ for (const step of steps) {
44482
+ if (!Step.$is("Change")(step)) {
44483
+ results2.push(step);
44484
+ continue;
44485
+ }
44486
+ const { part, summary, byHand } = step;
44487
+ const done4 = Step.Done({ part, summary });
44488
+ const failed = (reason) => Step.ByHand({ part, reason, instructions: byHand });
44489
+ results2.push(yield* Action4.$match(step.action, {
44490
+ MakeDirectory: ({ directory }) => fs.makeDirectory(directory, { recursive: true }).pipe(exports_Effect.as(done4), exports_Effect.mapError(() => new CopilotError({ message: `Cannot create ${directory}.` }))),
44491
+ Write: ({ file: file2, contents, original }) => exports_Effect.gen(function* () {
44492
+ if (exports_Option.getOrNull(yield* readOptional(file2)) !== exports_Option.getOrNull(original))
44493
+ return failed(`${file2} changed while this command was waiting. Run it again.`);
44494
+ yield* replaceFile(file2, contents);
44495
+ return done4;
44496
+ }).pipe(exports_Effect.catchTag("CopilotError", ({ message }) => exports_Effect.succeed(failed(message))), exports_Effect.orElseSucceed(() => failed(`Cannot write ${file2}.`))),
44497
+ Run: ({ program, args: args2 }) => spawner.exitCode(exports_ChildProcess.make(program, args2, {
44498
+ stdin: "ignore",
44499
+ stdout: "ignore",
44500
+ stderr: "inherit"
44501
+ })).pipe(exports_Effect.map((code) => code === 0 ? done4 : failed(`${program} could not ${summary}.`)), exports_Effect.orElseSucceed(() => failed(`Cannot run ${program}.`)))
44502
+ }));
44503
+ }
44504
+ return results2;
44505
+ });
44506
+ function summarize(steps, directory) {
44507
+ const changed = (part) => steps.some((step) => Step.$is("Done")(step) && step.part === part);
44508
+ const next2 = [
44509
+ ...changed("cli") ? ["Copilot CLI: open a new terminal before you start copilot."] : [],
44510
+ ...changed("vscode") ? [
44511
+ 'VS Code: run "Developer: Reload Window" in each open window, or restart VS Code, then start a new chat.'
44512
+ ] : []
44513
+ ];
44514
+ return sections([
44515
+ ["Done:", entries3(steps, "Done", ({ summary }) => summary)],
44516
+ ["Left for you to do by hand:", leftByHand(steps)],
44517
+ ["Note:", notes(steps)],
44518
+ [
44519
+ "Next:",
44520
+ next2.length === 0 ? [] : [
44521
+ ...next2,
44522
+ `Usage is recorded in ${directory} from then on; earlier sessions cannot be recovered.`,
44523
+ "Check it with: token-ledger report --provider copilot"
44524
+ ].map((line) => indented(line, 2))
44525
+ ]
44526
+ ]);
43617
44527
  }
43618
44528
 
43619
44529
  // packages/cli/src/format.ts
43620
- function csvCell(value5) {
43621
- const text2 = value5 === null ? "" : String(value5);
43622
- const safe = /^[=+\-@\t\r\n]/.test(text2) ? `'${text2}` : text2;
43623
- return `"${safe.replaceAll('"', '""')}"`;
43624
- }
43625
- function csv(report) {
43626
- const summary = projectSummary(report, false);
43627
- const headings = summary.headings.map((heading) => heading === "API estimate" ? "API estimate (USD)" : heading);
43628
- return [headings, ...summary.rows].map((row) => row.map(csvCell).join(",")).join(`
43629
- `);
43630
- }
43631
- function terminalText(value5) {
43632
- return value5.replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
44530
+ import { styleText } from "node:util";
44531
+ var import_cli_table3 = __toESM(require_table(), 1);
44532
+
44533
+ // node_modules/.bun/ansi-regex@6.3.0/node_modules/ansi-regex/index.js
44534
+ function ansiRegex({ onlyFirst = false } = {}) {
44535
+ const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
44536
+ const osc = `(?:\\u001B\\][^\\u0007\\u001B\\u009C]*${ST})`;
44537
+ const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
44538
+ const pattern = `${osc}|${csi}`;
44539
+ return new RegExp(pattern, onlyFirst ? undefined : "g");
43633
44540
  }
43634
- function projectSummary(report, grouped2) {
43635
- const projects = new Map;
43636
- for (const row of report.rows) {
43637
- const previous = projects.get(row.project);
43638
- projects.set(row.project, {
43639
- tokens: addTokens(previous?.tokens ?? zeroTokens, row.tokens),
43640
- cost: (previous?.cost ?? 0) + row.pricedCostUsd,
43641
- unpriced: (previous?.unpriced ?? 0) + row.unpricedRecords
43642
- });
44541
+
44542
+ // node_modules/.bun/strip-ansi@7.2.0/node_modules/strip-ansi/index.js
44543
+ var regex = ansiRegex();
44544
+ function stripAnsi2(string4) {
44545
+ if (typeof string4 !== "string") {
44546
+ throw new TypeError(`Expected a \`string\`, got \`${typeof string4}\``);
43643
44547
  }
43644
- const cost = [...projects.values()].reduce((sum3, project) => sum3 + project.cost, 0);
43645
- const unpriced = [...projects.values()].reduce((sum3, project) => sum3 + project.unpriced, 0);
43646
- const headings = [
43647
- "Project",
43648
- "Input",
43649
- "Cache read",
43650
- "Cache write",
43651
- "Output",
43652
- "API estimate",
43653
- unpriced ? "Known cost %" : "Cost %"
43654
- ];
43655
- const percentage = new Intl.NumberFormat("en-US", {
43656
- style: "percent",
43657
- minimumFractionDigits: 1,
43658
- maximumFractionDigits: 1
43659
- });
43660
- const share2 = (value5) => cost > 0 ? percentage.format(value5 / cost) : "—";
43661
- const number4 = new Intl.NumberFormat("en-US", { useGrouping: grouped2 });
43662
- const dollars = new Intl.NumberFormat("en-US", {
43663
- style: "currency",
43664
- currency: "USD",
43665
- useGrouping: grouped2
43666
- });
43667
- let allTokens = zeroTokens;
43668
- const rows = [];
43669
- const ranked = [...projects].toSorted(([leftProject, left], [rightProject, right]) => right.cost - left.cost || leftProject.localeCompare(rightProject));
43670
- for (const [project, total] of ranked) {
43671
- rows.push([
43672
- project,
43673
- number4.format(total.tokens.input),
43674
- number4.format(total.tokens.cacheRead),
43675
- number4.format(total.tokens.cacheWrite),
43676
- number4.format(total.tokens.output),
43677
- `${dollars.format(total.cost)}${total.unpriced ? " + unknown" : ""}`,
43678
- share2(total.cost)
43679
- ]);
43680
- allTokens = addTokens(allTokens, total.tokens);
44548
+ if (!string4.includes("\x1B") && !string4.includes("›")) {
44549
+ return string4;
43681
44550
  }
43682
- if (projects.size > 0)
43683
- rows.push([
43684
- "Total",
43685
- number4.format(allTokens.input),
43686
- number4.format(allTokens.cacheRead),
43687
- number4.format(allTokens.cacheWrite),
43688
- number4.format(allTokens.output),
43689
- `${dollars.format(cost)}${unpriced ? " + unknown" : ""}`,
43690
- share2(cost)
43691
- ]);
43692
- return { headings, rows, allTokens, unpriced, projectCount: projects.size };
44551
+ return string4.replace(regex, "");
43693
44552
  }
43694
- function table2(report, columns = 120, colorful = false) {
43695
- const paint = (format9, value5) => colorful ? styleText(format9, value5, { validateStream: false }) : value5;
43696
- const { headings, rows, allTokens, unpriced, projectCount } = projectSummary(report, true);
43697
- const number4 = new Intl.NumberFormat("en-US");
43698
- if (projectCount === 0)
43699
- return `No observed usage from ${report.since} through ${report.until} (${report.timeZone}).`;
43700
- const numericWidths = headings.slice(1).map((heading, i) => Math.max(heading.length, ...rows.map((row) => row[i + 1]?.length ?? 0)) + 2);
43701
- const projectWidth = columns - numericWidths.reduce((sum3, width2) => sum3 + width2, 0) - (headings.length + 1);
43702
- const narrow = projectWidth < 22;
43703
- const colWidths = narrow ? [16, Math.max(4, columns - 19)] : [Math.min(50, projectWidth), ...numericWidths];
43704
- const output = new import_cli_table3.default({
43705
- head: narrow ? [] : headings.map((heading) => paint(["bold", "cyan"], heading)),
43706
- colWidths,
43707
- colAligns: narrow ? ["left", "right"] : ["left", "right", "right", "right", "right", "right", "right"],
43708
- wordWrap: false,
43709
- style: { head: [], border: [] }
43710
- });
43711
- const projectColors = [
43712
- "cyan",
43713
- "blueBright",
43714
- "magenta",
43715
- "yellow",
43716
- "green",
43717
- "cyanBright"
43718
- ];
43719
- for (const [index2, row] of rows.entries()) {
43720
- const styled = row.map((value5, column) => {
43721
- const width2 = narrow ? column === 0 ? columns - 4 : columns - 21 : (colWidths[column] ?? 4) - 2;
43722
- const cell = wrapAnsi(terminalText(value5), Math.max(2, width2), {
43723
- hard: true,
43724
- wordWrap: false,
43725
- trim: false
43726
- });
43727
- if (index2 === rows.length - 1)
43728
- return paint(["bold", "magenta"], cell);
43729
- if (column === 0)
43730
- return paint(projectColors[index2 % projectColors.length] ?? "cyan", cell);
43731
- if (column >= headings.length - 2)
43732
- return paint(value5.includes("unknown") ? "yellow" : "green", cell);
43733
- return cell === "0" ? paint("dim", cell) : cell;
43734
- });
43735
- if (narrow) {
43736
- output.push([{ content: styled[0] ?? "", colSpan: 2, hAlign: "left" }]);
43737
- for (const [i, heading] of headings.slice(1).entries()) {
43738
- output.push([paint("cyan", heading), styled[i + 1] ?? ""]);
43739
- }
44553
+
44554
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup-data.js
44555
+ var ambiguousMinimalCodePoint = 161;
44556
+ var ambiguousMaximumCodePoint = 1114109;
44557
+ var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
44558
+ var fullwidthMinimalCodePoint = 12288;
44559
+ var fullwidthMaximumCodePoint = 65510;
44560
+ var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
44561
+ var wideMinimalCodePoint = 4352;
44562
+ var wideMaximumCodePoint = 262141;
44563
+ var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101594, 101631, 101664, 101760, 101874, 101888, 102801, 102816, 102866, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110888, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110952, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127406, 127406, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128729, 128732, 128735, 128747, 128748, 128756, 128764, 128986, 128986, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129734, 129736, 129736, 129740, 129757, 129759, 129771, 129775, 129786, 131072, 196605, 196608, 262141];
44564
+
44565
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/utilities.js
44566
+ var isInRange = (ranges, codePoint) => {
44567
+ let low = 0;
44568
+ let high = Math.floor(ranges.length / 2) - 1;
44569
+ while (low <= high) {
44570
+ const mid = Math.floor((low + high) / 2);
44571
+ const i = mid * 2;
44572
+ if (codePoint < ranges[i]) {
44573
+ high = mid - 1;
44574
+ } else if (codePoint > ranges[i + 1]) {
44575
+ low = mid + 1;
43740
44576
  } else {
43741
- output.push(styled);
44577
+ return true;
43742
44578
  }
43743
44579
  }
43744
- return [
43745
- `${paint(["bold", "cyan"], colorful ? "⚡ Token Ledger" : "Token Ledger")} · ${paint("dim", `${report.since} through ${report.until} (${report.timeZone})`)}`,
43746
- "",
43747
- output.toString(),
43748
- "",
43749
- paint("bold", `${colorful ? "\uD83D\uDCCA " : ""}${number4.format(totalTokens(allTokens))} observed tokens · ${number4.format(projectCount)} ${projectCount === 1 ? "project" : "projects"}`),
43750
- ...unpriced > 0 ? [
43751
- paint("yellow", "Incomplete pricing: sorting and percentages use known API subtotals; unknown costs are additional.")
43752
- ] : [],
43753
- paint("dim", "USD API-equivalent estimates; not your subscription bill.")
43754
- ].join(`
43755
- `);
43756
- }
43757
- function syncSummary(payload, request3, storedBuckets) {
43758
- const number4 = new Intl.NumberFormat("en-US");
43759
- const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
43760
- const sessions = new Set(payload.buckets.map((bucket) => bucket.sessionKey)).size;
43761
- const cost = payload.buckets.reduce((sum3, bucket) => sum3 + (bucket.estimatedCostUsd ?? 0), 0);
43762
- const unknown2 = payload.buckets.some((bucket) => bucket.estimatedCostUsd === null);
43763
- return [
43764
- `Synced ${terminalText(payload.machine.label)} · ${request3.since} through ${request3.until} (${payload.timeZone})`,
43765
- [
43766
- `${number4.format(payload.buckets.length)} hourly buckets`,
43767
- `${number4.format(sessions)} sessions`,
43768
- `${dollars.format(cost)}${unknown2 ? " + unknown" : ""} API estimate`,
43769
- exports_Option.match(storedBuckets, {
43770
- onNone: () => "accepted by the server",
43771
- onSome: (stored) => `server stored ${number4.format(stored)}`
43772
- })
43773
- ].join(" · ")
43774
- ].join(`
43775
- `);
43776
- }
44580
+ return false;
44581
+ };
43777
44582
 
43778
- // packages/cli/src/schedule.ts
43779
- import { homedir as homedir2, userInfo } from "node:os";
43780
- // packages/cli/src/settings.ts
43781
- import { randomUUID } from "node:crypto";
43782
- import { homedir, hostname } from "node:os";
43783
- class SettingsError extends exports_Schema.TaggedError()("SettingsError", {
43784
- message: exports_Schema.String
43785
- }) {
44583
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup.js
44584
+ var commonCjkCodePoint = 19968;
44585
+ var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
44586
+ function findWideFastPathRange(ranges) {
44587
+ let fastPathStart = ranges[0];
44588
+ let fastPathEnd = ranges[1];
44589
+ for (let index2 = 0;index2 < ranges.length; index2 += 2) {
44590
+ const start = ranges[index2];
44591
+ const end3 = ranges[index2 + 1];
44592
+ if (commonCjkCodePoint >= start && commonCjkCodePoint <= end3) {
44593
+ return [start, end3];
44594
+ }
44595
+ if (end3 - start > fastPathEnd - fastPathStart) {
44596
+ fastPathStart = start;
44597
+ fastPathEnd = end3;
44598
+ }
44599
+ }
44600
+ return [fastPathStart, fastPathEnd];
43786
44601
  }
43787
- var loopback = new Set(["localhost", "127.0.0.1", "[::1]"]);
43788
- var ServerUrl = exports_Schema.URLFromString.check(exports_Schema.makeFilter((url) => url.protocol === "https:" || url.protocol === "http:" && loopback.has(url.hostname), { expected: "an https:// URL, or http:// on localhost" }));
43789
- var SyncSettings = exports_Schema.Struct({
43790
- server: exports_Schema.optionalKey(ServerUrl),
43791
- token: exports_Schema.optionalKey(exports_Schema.RedactedFromValue(exports_Schema.NonEmptyString))
43792
- });
43793
- var configHome = exports_Effect.gen(function* () {
43794
- const path = yield* exports_Path.Path;
43795
- return yield* exports_Config.String("XDG_CONFIG_HOME").pipe(exports_Config.option, exports_Effect.map(exports_Option.filter((directory) => path.isAbsolute(directory))));
43796
- });
43797
- var settingsDirectory = exports_Effect.gen(function* () {
43798
- const path = yield* exports_Path.Path;
43799
- const home = homedir();
43800
- const xdg = yield* configHome;
43801
- const appData = yield* exports_Config.String("APPDATA").pipe(exports_Config.option);
43802
- const root = exports_Option.getOrElse(xdg, () => exports_Match.value(process.platform).pipe(exports_Match.when("win32", () => exports_Option.getOrElse(appData, () => path.join(home, "AppData", "Roaming"))), exports_Match.when("darwin", () => path.join(home, "Library", "Application Support")), exports_Match.orElse(() => path.join(home, ".config"))));
43803
- return path.join(root, "token-ledger");
43804
- });
43805
- var loadMachine = exports_Effect.fn("Settings.loadMachine")(function* (directory) {
43806
- const fs = yield* exports_FileSystem.FileSystem;
43807
- const path = yield* exports_Path.Path;
43808
- const file2 = path.join(directory, "machine.json");
43809
- const read2 = fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncMachine))), exports_Effect.mapError(() => new SettingsError({ message: `Cannot read ${file2}; fix or remove it.` })));
43810
- if (yield* fs.exists(file2).pipe(exports_Effect.orElseSucceed(() => true)))
43811
- return yield* read2;
43812
- const machine = yield* SyncMachine.makeEffect({
43813
- id: randomUUID(),
43814
- label: hostname().trim() || "machine"
43815
- }).pipe(exports_Effect.orDie);
43816
- const created = yield* exports_Effect.gen(function* () {
43817
- yield* fs.makeDirectory(directory, { recursive: true });
43818
- const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
43819
- directory,
43820
- prefix: ".machine-"
43821
- });
43822
- const temporary = path.join(temporaryDirectory, "machine.json");
43823
- yield* fs.writeFileString(temporary, `${JSON.stringify(machine, null, 2)}
43824
- `, {
43825
- flag: "wx",
43826
- mode: 384
43827
- });
43828
- return yield* fs.link(temporary, file2).pipe(exports_Effect.as(true), exports_Effect.catchReason("PlatformError", "AlreadyExists", () => exports_Effect.succeed(false)));
43829
- }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot create ${file2}.` })));
43830
- return created ? machine : yield* read2;
43831
- });
43832
- var loadSyncSettings = exports_Effect.fn("Settings.loadSync")(function* (directory) {
43833
- const fs = yield* exports_FileSystem.FileSystem;
43834
- const path = yield* exports_Path.Path;
43835
- const file2 = path.join(directory, "sync.json");
43836
- const failure = new SettingsError({ message: `Cannot read or decode ${file2}.` });
43837
- if (!(yield* fs.exists(file2).pipe(exports_Effect.mapError(() => failure))))
43838
- return {};
43839
- return yield* fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncSettings))), exports_Effect.mapError(() => failure));
43840
- });
43841
- var saveSyncSettings = exports_Effect.fn("Settings.saveSync")(function* (directory, server, token) {
43842
- const fs = yield* exports_FileSystem.FileSystem;
43843
- const path = yield* exports_Path.Path;
43844
- const file2 = path.join(directory, "sync.json");
43845
- yield* exports_Effect.gen(function* () {
43846
- const settings = yield* exports_Schema.encodeEffect(SyncSettings)({ server, token });
43847
- yield* fs.makeDirectory(directory, { recursive: true });
43848
- const temporaryDirectory = yield* fs.makeTempDirectoryScoped({ directory, prefix: ".sync-" });
43849
- const temporary = path.join(temporaryDirectory, "sync.json");
43850
- yield* fs.writeFileString(temporary, `${JSON.stringify(settings, null, 2)}
43851
- `, {
43852
- flag: "wx",
43853
- mode: 384
43854
- });
43855
- yield* fs.rename(temporary, file2);
43856
- }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot save ${file2}.` })));
43857
- return file2;
43858
- });
44602
+ var isAmbiguous = (codePoint) => {
44603
+ if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) {
44604
+ return false;
44605
+ }
44606
+ return isInRange(ambiguousRanges, codePoint);
44607
+ };
44608
+ var isFullwidth = (codePoint) => {
44609
+ if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) {
44610
+ return false;
44611
+ }
44612
+ return isInRange(fullwidthRanges, codePoint);
44613
+ };
44614
+ var isWide = (codePoint) => {
44615
+ if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
44616
+ return true;
44617
+ }
44618
+ if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) {
44619
+ return false;
44620
+ }
44621
+ return isInRange(wideRanges, codePoint);
44622
+ };
43859
44623
 
43860
- // packages/cli/src/schedule.ts
43861
- class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
43862
- message: exports_Schema.String
43863
- }) {
43864
- }
43865
- var TimeOfDay = exports_Schema.String.check(exports_Schema.isPattern(/^(?:[01]\d|2[0-3]):[0-5]\d$/));
43866
- var Action3 = exports_Data.taggedEnum();
43867
- var unit = "token-ledger-sync";
43868
- var label = "com.github.ponbac.token-ledger.sync";
43869
- var task = "token-ledger sync";
43870
- var packageSpec = "@ponbac/token-ledger@latest";
43871
- function run6(outcome, program, args2, hint = "") {
43872
- return Action3.Run({
43873
- program,
43874
- args: args2,
43875
- shown: [program, ...args2].join(" "),
43876
- outcome,
43877
- hint,
43878
- gone: []
43879
- });
44624
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/index.js
44625
+ function validate3(codePoint) {
44626
+ if (!Number.isSafeInteger(codePoint)) {
44627
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
44628
+ }
43880
44629
  }
43881
- function quotable(job, forbidden2, described) {
43882
- const offending = [job.nodeDirectory, ...exports_Option.toArray(job.configHome), ...job.flags].find((value5) => forbidden2.test(value5));
43883
- return offending === undefined ? exports_Effect.succeed(job) : exports_Effect.fail(new ScheduleError({
43884
- message: `Cannot schedule with ${JSON.stringify(offending)}: it contains ${described}.`
43885
- }));
44630
+ function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
44631
+ validate3(codePoint);
44632
+ if (isFullwidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
44633
+ return 2;
44634
+ }
44635
+ return 1;
43886
44636
  }
43887
- var posixWord = (value5) => /^[\w@+=:,./-]+$/.test(value5) ? value5 : `'${value5.replaceAll("'", "'\\''")}'`;
43888
- var posixScript = (job) => [
43889
- "cd /",
43890
- ...exports_Option.toArray(job.configHome).map((directory) => `export XDG_CONFIG_HOME=${posixWord(directory)}`),
43891
- `export PATH=${posixWord(job.nodeDirectory)}:"$PATH"`,
43892
- `exec npx --yes ${packageSpec} ${["sync", ...job.flags].map(posixWord).join(" ")}`
43893
- ].join("; ");
43894
- var posixJob = (job) => quotable(job, /\p{Cc}/u, "a control character");
43895
- var systemdQuoted = (value5) => `"${value5.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("%", "%%").replaceAll("$", () => "$$")}"`;
43896
- function systemdTimer(directory) {
43897
- const service4 = `${directory}/${unit}.service`;
43898
- const timer = `${directory}/${unit}.timer`;
43899
- const systemctl = (outcome, args2, hint = "") => run6(outcome, "systemctl", ["--user", ...args2], hint);
43900
- return {
43901
- name: "systemd user timer",
43902
- install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => [
43903
- systemctl("required", ["daemon-reload"], "A systemd user session is required; without one, add the cron entry from the README."),
43904
- Action3.Write({
43905
- file: service4,
43906
- contents: `[Unit]
43907
- Description=Upload AI usage to toki2
43908
-
43909
- [Service]
43910
- Type=oneshot
43911
- ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
43912
- `
43913
- }),
43914
- Action3.Write({
43915
- file: timer,
43916
- contents: `[Unit]
43917
- Description=Daily AI usage sync
43918
-
43919
- [Timer]
43920
- OnCalendar=*-*-* ${job2.at}:00
43921
- Persistent=true
43922
- RandomizedDelaySec=10m
43923
44637
 
43924
- [Install]
43925
- WantedBy=timers.target
43926
- `
43927
- }),
43928
- systemctl("required", ["daemon-reload"]),
43929
- systemctl("required", ["enable", `${unit}.timer`]),
43930
- systemctl("required", ["restart", `${unit}.timer`])
43931
- ])),
43932
- uninstall: [
43933
- systemctl("reported", ["disable", "--now", `${unit}.timer`]),
43934
- systemctl("reported", ["clean", "--what=state", `${unit}.timer`]),
43935
- Action3.Remove({ file: service4 }),
43936
- Action3.Remove({ file: timer }),
43937
- systemctl("reported", ["daemon-reload"]),
43938
- Action3.Run({
43939
- ...systemctl("absent", ["is-active", "--quiet", `${unit}.timer`], "Cannot confirm that the timer is gone; systemd's reason is shown above."),
43940
- gone: [3, 4]
43941
- })
43942
- ],
43943
- status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])]
43944
- };
44638
+ // node_modules/.bun/string-width@8.2.2/node_modules/string-width/index.js
44639
+ var segmenter = new Intl.Segmenter;
44640
+ var zeroWidthClusterRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Nonspacing_Mark}|\p{Enclosing_Mark}|\p{Surrogate})+$/v;
44641
+ var leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]+/v;
44642
+ var spacingMarkRegex = /\p{Spacing_Mark}/v;
44643
+ var rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
44644
+ var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
44645
+ var extendedPictographicRegex = /\p{Extended_Pictographic}/gu;
44646
+ function isDoubleWidthNonRgiEmojiSequence(segment) {
44647
+ if (segment.length > 50) {
44648
+ return false;
44649
+ }
44650
+ if (unqualifiedKeycapRegex.test(segment)) {
44651
+ return true;
44652
+ }
44653
+ if (segment.includes("‍")) {
44654
+ const pictographics = segment.match(extendedPictographicRegex);
44655
+ return pictographics !== null && pictographics.length >= 2;
44656
+ }
44657
+ return false;
43945
44658
  }
43946
- var xmlText = (value5) => value5.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
43947
- function launchAgent(home, uid) {
43948
- const plist = `${home}/Library/LaunchAgents/${label}.plist`;
43949
- const log3 = `${home}/Library/Logs/${unit}.log`;
43950
- const domain = `gui/${uid}`;
43951
- return {
43952
- name: "launchd agent",
43953
- install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => {
43954
- const [hour2, minute] = job2.at.split(":").map(Number);
43955
- return [
43956
- Action3.Write({
43957
- file: plist,
43958
- contents: `<?xml version="1.0" encoding="UTF-8"?>
43959
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
43960
- <plist version="1.0">
43961
- <dict>
43962
- <key>Label</key>
43963
- <string>${label}</string>
43964
- <key>ProgramArguments</key>
43965
- <array>
43966
- <string>/bin/zsh</string>
43967
- <string>-lc</string>
43968
- <string>${xmlText(posixScript(job2))}</string>
43969
- </array>
43970
- <key>RunAtLoad</key>
43971
- <true/>
43972
- <key>StartCalendarInterval</key>
43973
- <dict>
43974
- <key>Hour</key>
43975
- <integer>${hour2}</integer>
43976
- <key>Minute</key>
43977
- <integer>${minute}</integer>
43978
- </dict>
43979
- <key>StandardOutPath</key>
43980
- <string>${xmlText(log3)}</string>
43981
- <key>StandardErrorPath</key>
43982
- <string>${xmlText(log3)}</string>
43983
- </dict>
43984
- </plist>
43985
- `
43986
- }),
43987
- run6("silent", "launchctl", ["bootout", `${domain}/${label}`]),
43988
- run6("required", "launchctl", ["bootstrap", domain, plist])
43989
- ];
43990
- })),
43991
- uninstall: [
43992
- run6("reported", "launchctl", ["bootout", `${domain}/${label}`]),
43993
- Action3.Remove({ file: plist }),
43994
- run6("absent", "launchctl", ["print", `${domain}/${label}`], "The agent is still loaded; launchd's reason is shown above.")
43995
- ],
43996
- status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])]
43997
- };
44659
+ function baseVisible(segment) {
44660
+ return segment.replace(leadingNonPrintingRegex, "");
44661
+ }
44662
+ function isZeroWidthCluster(segment) {
44663
+ return zeroWidthClusterRegex.test(segment);
44664
+ }
44665
+ function isHangulLeadingJamo(codePoint) {
44666
+ return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
44667
+ }
44668
+ function isHangulVowelJamo(codePoint) {
44669
+ return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
44670
+ }
44671
+ function isHangulTrailingJamo(codePoint) {
44672
+ return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
44673
+ }
44674
+ function isHangulJamo(codePoint) {
44675
+ return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
44676
+ }
44677
+ function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
44678
+ const codePoints = [];
44679
+ for (const character of visibleSegment) {
44680
+ if (zeroWidthClusterRegex.test(character)) {
44681
+ continue;
44682
+ }
44683
+ codePoints.push(character.codePointAt(0));
44684
+ }
44685
+ if (codePoints.length === 0) {
44686
+ return;
44687
+ }
44688
+ let width2 = 0;
44689
+ for (let index2 = 0;index2 < codePoints.length; index2++) {
44690
+ const codePoint = codePoints[index2];
44691
+ if (!isHangulJamo(codePoint)) {
44692
+ if (width2 === 0) {
44693
+ return;
44694
+ }
44695
+ for (let remaining = index2;remaining < codePoints.length; remaining++) {
44696
+ width2 += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
44697
+ }
44698
+ return width2;
44699
+ }
44700
+ if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index2 + 1])) {
44701
+ width2 += 2;
44702
+ index2 += isHangulTrailingJamo(codePoints[index2 + 2]) ? 2 : 1;
44703
+ continue;
44704
+ }
44705
+ width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
44706
+ }
44707
+ return width2;
44708
+ }
44709
+ function trailingWidth(visibleSegment, eastAsianWidthOptions) {
44710
+ let extra = 0;
44711
+ let first = true;
44712
+ for (const character of visibleSegment) {
44713
+ if (first) {
44714
+ first = false;
44715
+ continue;
44716
+ }
44717
+ if (spacingMarkRegex.test(character) || character >= "＀" && character <= "￯") {
44718
+ extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
44719
+ }
44720
+ }
44721
+ return extra;
44722
+ }
44723
+ function stringWidth(input, options3 = {}) {
44724
+ if (typeof input !== "string" || input.length === 0) {
44725
+ return 0;
44726
+ }
44727
+ const {
44728
+ ambiguousIsNarrow = true,
44729
+ countAnsiEscapeCodes = false
44730
+ } = options3;
44731
+ let string4 = input;
44732
+ if (!countAnsiEscapeCodes && (string4.includes("\x1B") || string4.includes("›"))) {
44733
+ string4 = stripAnsi2(string4);
44734
+ }
44735
+ if (string4.length === 0) {
44736
+ return 0;
44737
+ }
44738
+ if (/^[\u0020-\u007E]*$/.test(string4)) {
44739
+ return string4.length;
44740
+ }
44741
+ let width2 = 0;
44742
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
44743
+ for (const { segment } of segmenter.segment(string4)) {
44744
+ if (isZeroWidthCluster(segment)) {
44745
+ continue;
44746
+ }
44747
+ if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
44748
+ width2 += 2;
44749
+ continue;
44750
+ }
44751
+ const visibleSegment = baseVisible(segment);
44752
+ const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
44753
+ if (hangulWidth !== undefined) {
44754
+ width2 += hangulWidth;
44755
+ continue;
44756
+ }
44757
+ const codePoint = visibleSegment.codePointAt(0);
44758
+ width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
44759
+ width2 += trailingWidth(visibleSegment, eastAsianWidthOptions);
44760
+ }
44761
+ return width2;
44762
+ }
44763
+
44764
+ // node_modules/.bun/ansi-styles@6.2.3/node_modules/ansi-styles/index.js
44765
+ var ANSI_BACKGROUND_OFFSET = 10;
44766
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
44767
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
44768
+ var wrapAnsi16m = (offset = 0) => (red2, green2, blue) => `\x1B[${38 + offset};2;${red2};${green2};${blue}m`;
44769
+ var styles = {
44770
+ modifier: {
44771
+ reset: [0, 0],
44772
+ bold: [1, 22],
44773
+ dim: [2, 22],
44774
+ italic: [3, 23],
44775
+ underline: [4, 24],
44776
+ overline: [53, 55],
44777
+ inverse: [7, 27],
44778
+ hidden: [8, 28],
44779
+ strikethrough: [9, 29]
44780
+ },
44781
+ color: {
44782
+ black: [30, 39],
44783
+ red: [31, 39],
44784
+ green: [32, 39],
44785
+ yellow: [33, 39],
44786
+ blue: [34, 39],
44787
+ magenta: [35, 39],
44788
+ cyan: [36, 39],
44789
+ white: [37, 39],
44790
+ blackBright: [90, 39],
44791
+ gray: [90, 39],
44792
+ grey: [90, 39],
44793
+ redBright: [91, 39],
44794
+ greenBright: [92, 39],
44795
+ yellowBright: [93, 39],
44796
+ blueBright: [94, 39],
44797
+ magentaBright: [95, 39],
44798
+ cyanBright: [96, 39],
44799
+ whiteBright: [97, 39]
44800
+ },
44801
+ bgColor: {
44802
+ bgBlack: [40, 49],
44803
+ bgRed: [41, 49],
44804
+ bgGreen: [42, 49],
44805
+ bgYellow: [43, 49],
44806
+ bgBlue: [44, 49],
44807
+ bgMagenta: [45, 49],
44808
+ bgCyan: [46, 49],
44809
+ bgWhite: [47, 49],
44810
+ bgBlackBright: [100, 49],
44811
+ bgGray: [100, 49],
44812
+ bgGrey: [100, 49],
44813
+ bgRedBright: [101, 49],
44814
+ bgGreenBright: [102, 49],
44815
+ bgYellowBright: [103, 49],
44816
+ bgBlueBright: [104, 49],
44817
+ bgMagentaBright: [105, 49],
44818
+ bgCyanBright: [106, 49],
44819
+ bgWhiteBright: [107, 49]
44820
+ }
44821
+ };
44822
+ var modifierNames = Object.keys(styles.modifier);
44823
+ var foregroundColorNames = Object.keys(styles.color);
44824
+ var backgroundColorNames = Object.keys(styles.bgColor);
44825
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
44826
+ function assembleStyles() {
44827
+ const codes2 = new Map;
44828
+ for (const [groupName, group2] of Object.entries(styles)) {
44829
+ for (const [styleName, style] of Object.entries(group2)) {
44830
+ styles[styleName] = {
44831
+ open: `\x1B[${style[0]}m`,
44832
+ close: `\x1B[${style[1]}m`
44833
+ };
44834
+ group2[styleName] = styles[styleName];
44835
+ codes2.set(style[0], style[1]);
44836
+ }
44837
+ Object.defineProperty(styles, groupName, {
44838
+ value: group2,
44839
+ enumerable: false
44840
+ });
44841
+ }
44842
+ Object.defineProperty(styles, "codes", {
44843
+ value: codes2,
44844
+ enumerable: false
44845
+ });
44846
+ styles.color.close = "\x1B[39m";
44847
+ styles.bgColor.close = "\x1B[49m";
44848
+ styles.color.ansi = wrapAnsi16();
44849
+ styles.color.ansi256 = wrapAnsi256();
44850
+ styles.color.ansi16m = wrapAnsi16m();
44851
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
44852
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
44853
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
44854
+ Object.defineProperties(styles, {
44855
+ rgbToAnsi256: {
44856
+ value(red2, green2, blue) {
44857
+ if (red2 === green2 && green2 === blue) {
44858
+ if (red2 < 8) {
44859
+ return 16;
44860
+ }
44861
+ if (red2 > 248) {
44862
+ return 231;
44863
+ }
44864
+ return Math.round((red2 - 8) / 247 * 24) + 232;
44865
+ }
44866
+ return 16 + 36 * Math.round(red2 / 255 * 5) + 6 * Math.round(green2 / 255 * 5) + Math.round(blue / 255 * 5);
44867
+ },
44868
+ enumerable: false
44869
+ },
44870
+ hexToRgb: {
44871
+ value(hex2) {
44872
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex2.toString(16));
44873
+ if (!matches) {
44874
+ return [0, 0, 0];
44875
+ }
44876
+ let [colorString] = matches;
44877
+ if (colorString.length === 3) {
44878
+ colorString = [...colorString].map((character) => character + character).join("");
44879
+ }
44880
+ const integer = Number.parseInt(colorString, 16);
44881
+ return [
44882
+ integer >> 16 & 255,
44883
+ integer >> 8 & 255,
44884
+ integer & 255
44885
+ ];
44886
+ },
44887
+ enumerable: false
44888
+ },
44889
+ hexToAnsi256: {
44890
+ value: (hex2) => styles.rgbToAnsi256(...styles.hexToRgb(hex2)),
44891
+ enumerable: false
44892
+ },
44893
+ ansi256ToAnsi: {
44894
+ value(code) {
44895
+ if (code < 8) {
44896
+ return 30 + code;
44897
+ }
44898
+ if (code < 16) {
44899
+ return 90 + (code - 8);
44900
+ }
44901
+ let red2;
44902
+ let green2;
44903
+ let blue;
44904
+ if (code >= 232) {
44905
+ red2 = ((code - 232) * 10 + 8) / 255;
44906
+ green2 = red2;
44907
+ blue = red2;
44908
+ } else {
44909
+ code -= 16;
44910
+ const remainder2 = code % 36;
44911
+ red2 = Math.floor(code / 36) / 5;
44912
+ green2 = Math.floor(remainder2 / 6) / 5;
44913
+ blue = remainder2 % 6 / 5;
44914
+ }
44915
+ const value5 = Math.max(red2, green2, blue) * 2;
44916
+ if (value5 === 0) {
44917
+ return 30;
44918
+ }
44919
+ let result6 = 30 + (Math.round(blue) << 2 | Math.round(green2) << 1 | Math.round(red2));
44920
+ if (value5 === 2) {
44921
+ result6 += 60;
44922
+ }
44923
+ return result6;
44924
+ },
44925
+ enumerable: false
44926
+ },
44927
+ rgbToAnsi: {
44928
+ value: (red2, green2, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red2, green2, blue)),
44929
+ enumerable: false
44930
+ },
44931
+ hexToAnsi: {
44932
+ value: (hex2) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex2)),
44933
+ enumerable: false
44934
+ }
44935
+ });
44936
+ return styles;
44937
+ }
44938
+ var ansiStyles = assembleStyles();
44939
+ var ansi_styles_default = ansiStyles;
44940
+
44941
+ // node_modules/.bun/wrap-ansi@10.0.2/node_modules/wrap-ansi/index.js
44942
+ var ANSI_ESCAPE = "\x1B";
44943
+ var ANSI_ESCAPE_BELL = "\x07";
44944
+ var C1_CSI = "›";
44945
+ var ANSI_CSI = "[";
44946
+ var ANSI_OSC = "]";
44947
+ var ANSI_SGR_TERMINATOR = "m";
44948
+ var ANSI_SGR_RESET = 0;
44949
+ var ANSI_SGR_RESET_FOREGROUND = 39;
44950
+ var ANSI_SGR_RESET_BACKGROUND = 49;
44951
+ var ANSI_SGR_RESET_UNDERLINE_COLOR = 59;
44952
+ var ANSI_SGR_FOREGROUND_EXTENDED = 38;
44953
+ var ANSI_SGR_BACKGROUND_EXTENDED = 48;
44954
+ var ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;
44955
+ var ANSI_SGR_COLOR_MODE_RGB = 2;
44956
+ var ANSI_SGR_COLOR_MODE_256 = 5;
44957
+ var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;`;
44958
+ var ESCAPES = new Set([
44959
+ ANSI_ESCAPE,
44960
+ C1_CSI
44961
+ ]);
44962
+ var ESCAPE_CHARACTERS = [...ESCAPES].join("");
44963
+ var CSI_INTRODUCER = `(?:${ANSI_ESCAPE}\\${ANSI_CSI}|${C1_CSI})`;
44964
+ var CSI_PARAMETERS = "[0-?]*[ -/]*[@-~]";
44965
+ var SGR_PARAMETERS = `(?<sgr>[0-9;:]*)${ANSI_SGR_TERMINATOR}`;
44966
+ var OSC_STRING_TERMINATOR = `(?:${ANSI_ESCAPE_BELL}|${ANSI_ESCAPE}\\\\)`;
44967
+ var OSC_STRING_PAYLOAD = String.raw`[^\u0000-\u001F\u007F-\u009F]*`;
44968
+ var LINK_PARAMETERS = String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${OSC_STRING_PAYLOAD})${OSC_STRING_TERMINATOR}`;
44969
+ var OSC_STRING = `${OSC_STRING_PAYLOAD}${OSC_STRING_TERMINATOR}`;
44970
+ var ANSI_ESCAPE_REGEX = new RegExp(`${CSI_INTRODUCER}(?:${SGR_PARAMETERS}|${CSI_PARAMETERS})` + `|${ANSI_ESCAPE}\\${ANSI_OSC}(?:${LINK_PARAMETERS}|${OSC_STRING})`, "y");
44971
+ var ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansi_styles_default.codes.values());
44972
+ ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);
44973
+ var segmenter2 = new Intl.Segmenter;
44974
+ var getStringWidth = (string4) => stringWidth(string4, { countAnsiEscapeCodes: true });
44975
+ var TAB_SIZE = 8;
44976
+ var ESCAPE_INTRODUCER_REGEX = new RegExp(`[${ESCAPE_CHARACTERS}]`, "g");
44977
+ var ROW_BOUNDARY_REGEX = new RegExp(`[\\n${ESCAPE_CHARACTERS}]`, "g");
44978
+ var ASCII_PRINTABLE_REGEX = /^[ -~]*$/;
44979
+ var wrapAnsiCode = (code) => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
44980
+ var wrapAnsiHyperlink = (url, parameters = "") => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${parameters};${url}${ANSI_ESCAPE_BELL}`;
44981
+ var matchAnsiEscape = (string4, index2) => {
44982
+ if (!ESCAPES.has(string4[index2])) {
44983
+ return;
44984
+ }
44985
+ ANSI_ESCAPE_REGEX.lastIndex = index2;
44986
+ return ANSI_ESCAPE_REGEX.exec(string4) ?? undefined;
44987
+ };
44988
+ var forEachSegment = (string4, onPlainText, onEscape = () => {}) => {
44989
+ let plainStart = 0;
44990
+ let index2 = 0;
44991
+ while (index2 < string4.length) {
44992
+ ESCAPE_INTRODUCER_REGEX.lastIndex = index2;
44993
+ const introducer = ESCAPE_INTRODUCER_REGEX.exec(string4);
44994
+ if (!introducer) {
44995
+ break;
44996
+ }
44997
+ const escape2 = matchAnsiEscape(string4, introducer.index);
44998
+ if (!escape2) {
44999
+ index2 = introducer.index + 1;
45000
+ continue;
45001
+ }
45002
+ if (introducer.index > plainStart) {
45003
+ onPlainText(string4.slice(plainStart, introducer.index));
45004
+ }
45005
+ onEscape(escape2[0]);
45006
+ index2 = introducer.index + escape2[0].length;
45007
+ plainStart = index2;
45008
+ }
45009
+ if (plainStart < string4.length) {
45010
+ onPlainText(string4.slice(plainStart));
45011
+ }
45012
+ };
45013
+ var getWidth = (string4) => {
45014
+ let plainText = "";
45015
+ forEachSegment(string4, (part) => {
45016
+ plainText += part;
45017
+ });
45018
+ return getStringWidth(plainText);
45019
+ };
45020
+ var getTokens = (string4) => {
45021
+ const tokens = [];
45022
+ forEachSegment(string4, (plainText) => {
45023
+ if (ASCII_PRINTABLE_REGEX.test(plainText)) {
45024
+ for (const character of plainText) {
45025
+ tokens.push({ value: character, width: 1 });
45026
+ }
45027
+ return;
45028
+ }
45029
+ for (const { segment } of segmenter2.segment(plainText)) {
45030
+ tokens.push({ value: segment, width: getStringWidth(segment) });
45031
+ }
45032
+ }, (escape2) => {
45033
+ tokens.push({ value: escape2, width: 0 });
45034
+ });
45035
+ return tokens;
45036
+ };
45037
+ var splitWords = (string4) => {
45038
+ let currentWord = { value: "", plainText: "" };
45039
+ const words = [currentWord];
45040
+ forEachSegment(string4, (plainText) => {
45041
+ const parts2 = plainText.split(" ");
45042
+ currentWord.value += parts2[0];
45043
+ currentWord.plainText += parts2[0];
45044
+ for (let index2 = 1;index2 < parts2.length; index2++) {
45045
+ currentWord = { value: parts2[index2], plainText: parts2[index2] };
45046
+ words.push(currentWord);
45047
+ }
45048
+ }, (escape2) => {
45049
+ currentWord.value += escape2;
45050
+ });
45051
+ for (const word of words) {
45052
+ word.width = getStringWidth(word.plainText);
45053
+ }
45054
+ return words;
45055
+ };
45056
+ var getColonColorToken = (parameter) => {
45057
+ const parts2 = parameter.split(":");
45058
+ const code = Number.parseInt(parts2[0], 10);
45059
+ const mode = Number.parseInt(parts2[1], 10);
45060
+ if (![ANSI_SGR_FOREGROUND_EXTENDED, ANSI_SGR_BACKGROUND_EXTENDED, ANSI_SGR_UNDERLINE_COLOR_EXTENDED].includes(code)) {
45061
+ return;
45062
+ }
45063
+ if (mode === ANSI_SGR_COLOR_MODE_256 && parts2.length === 3 && /^\d+$/.test(parts2[2])) {
45064
+ return { code, open: parameter, hasArguments: true };
45065
+ }
45066
+ if (mode !== ANSI_SGR_COLOR_MODE_RGB) {
45067
+ return;
45068
+ }
45069
+ const components = parts2.length === 6 ? parts2.slice(3) : parts2.slice(2);
45070
+ const colorSpace = parts2.length === 6 ? parts2[2] : undefined;
45071
+ if (components.length === 3 && components.every((component) => /^\d+$/.test(component)) && (colorSpace === undefined || /^\d*$/.test(colorSpace))) {
45072
+ return { code, open: parameter, hasArguments: true };
45073
+ }
45074
+ };
45075
+ var getSgrTokens = (sgrParameters) => {
45076
+ const parameters = sgrParameters.split(";");
45077
+ const sgrTokens = [];
45078
+ for (let index2 = 0;index2 < parameters.length; index2++) {
45079
+ const parameter = parameters[index2];
45080
+ if (parameter.includes(":")) {
45081
+ const colonColorToken = getColonColorToken(parameter);
45082
+ if (colonColorToken) {
45083
+ sgrTokens.push(colonColorToken);
45084
+ }
45085
+ continue;
45086
+ }
45087
+ const code = parameter === "" ? ANSI_SGR_RESET : Number.parseInt(parameter, 10);
45088
+ if (!Number.isFinite(code)) {
45089
+ continue;
45090
+ }
45091
+ if (code === ANSI_SGR_FOREGROUND_EXTENDED || code === ANSI_SGR_BACKGROUND_EXTENDED || code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED) {
45092
+ if (index2 + 1 >= parameters.length) {
45093
+ break;
45094
+ }
45095
+ const mode = Number.parseInt(parameters[index2 + 1], 10);
45096
+ const colorIndex = Number.parseInt(parameters[index2 + 2], 10);
45097
+ if (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(colorIndex)) {
45098
+ sgrTokens.push({ code, open: [code, mode, colorIndex].join(";"), hasArguments: true });
45099
+ index2 += 2;
45100
+ continue;
45101
+ }
45102
+ const red2 = Number.parseInt(parameters[index2 + 2], 10);
45103
+ const green2 = Number.parseInt(parameters[index2 + 3], 10);
45104
+ const blue = Number.parseInt(parameters[index2 + 4], 10);
45105
+ if (mode === ANSI_SGR_COLOR_MODE_RGB && Number.isFinite(red2) && Number.isFinite(green2) && Number.isFinite(blue)) {
45106
+ sgrTokens.push({ code, open: [code, mode, red2, green2, blue].join(";"), hasArguments: true });
45107
+ index2 += 4;
45108
+ continue;
45109
+ }
45110
+ break;
45111
+ }
45112
+ sgrTokens.push({ code, open: String(code), hasArguments: false });
45113
+ }
45114
+ return sgrTokens;
45115
+ };
45116
+ var removeActiveStyle = (activeStyles, family) => {
45117
+ const activeStyleIndex = activeStyles.findIndex((activeStyle) => activeStyle.family === family);
45118
+ if (activeStyleIndex !== -1) {
45119
+ activeStyles.splice(activeStyleIndex, 1);
45120
+ }
45121
+ };
45122
+ var upsertActiveStyle = (activeStyles, nextActiveStyle) => {
45123
+ removeActiveStyle(activeStyles, nextActiveStyle.family);
45124
+ activeStyles.push(nextActiveStyle);
45125
+ };
45126
+ var removeModifierStylesByClose = (activeStyles, closeCode) => {
45127
+ for (let index2 = activeStyles.length - 1;index2 >= 0; index2--) {
45128
+ const activeStyle = activeStyles[index2];
45129
+ if (activeStyle.family.startsWith("modifier-") && activeStyle.close === closeCode) {
45130
+ activeStyles.splice(index2, 1);
45131
+ }
45132
+ }
45133
+ };
45134
+ var getColorStyle = (sgrToken) => {
45135
+ const { code, open: open3, hasArguments } = sgrToken;
45136
+ if (code >= 30 && code <= 37 || code >= 90 && code <= 97 || code === ANSI_SGR_FOREGROUND_EXTENDED && hasArguments) {
45137
+ return {
45138
+ family: "foreground",
45139
+ open: open3,
45140
+ close: ANSI_SGR_RESET_FOREGROUND
45141
+ };
45142
+ }
45143
+ if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === ANSI_SGR_BACKGROUND_EXTENDED && hasArguments) {
45144
+ return {
45145
+ family: "background",
45146
+ open: open3,
45147
+ close: ANSI_SGR_RESET_BACKGROUND
45148
+ };
45149
+ }
45150
+ if (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && hasArguments) {
45151
+ return {
45152
+ family: "underlineColor",
45153
+ open: open3,
45154
+ close: ANSI_SGR_RESET_UNDERLINE_COLOR
45155
+ };
45156
+ }
45157
+ };
45158
+ var applySgrResetCode = (code, activeStyles) => {
45159
+ if (code === ANSI_SGR_RESET) {
45160
+ activeStyles.length = 0;
45161
+ return true;
45162
+ }
45163
+ if (code === ANSI_SGR_RESET_FOREGROUND) {
45164
+ removeActiveStyle(activeStyles, "foreground");
45165
+ return true;
45166
+ }
45167
+ if (code === ANSI_SGR_RESET_BACKGROUND) {
45168
+ removeActiveStyle(activeStyles, "background");
45169
+ return true;
45170
+ }
45171
+ if (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {
45172
+ removeActiveStyle(activeStyles, "underlineColor");
45173
+ return true;
45174
+ }
45175
+ if (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {
45176
+ removeModifierStylesByClose(activeStyles, code);
45177
+ return true;
45178
+ }
45179
+ return false;
45180
+ };
45181
+ var applySgrToken = (sgrToken, activeStyles) => {
45182
+ const { code } = sgrToken;
45183
+ if (applySgrResetCode(code, activeStyles)) {
45184
+ return;
45185
+ }
45186
+ const colorStyle = getColorStyle(sgrToken);
45187
+ if (colorStyle) {
45188
+ upsertActiveStyle(activeStyles, colorStyle);
45189
+ return;
45190
+ }
45191
+ const close3 = ansi_styles_default.codes.get(code);
45192
+ if (close3 !== undefined && close3 !== ANSI_SGR_RESET) {
45193
+ upsertActiveStyle(activeStyles, {
45194
+ family: `modifier-${code}`,
45195
+ open: sgrToken.open,
45196
+ close: close3
45197
+ });
45198
+ }
45199
+ };
45200
+ var applySgrParameters = (sgrParameters, activeStyles) => {
45201
+ for (const sgrToken of getSgrTokens(sgrParameters)) {
45202
+ applySgrToken(sgrToken, activeStyles);
45203
+ }
45204
+ };
45205
+ var applySgrResets = (sgrParameters, activeStyles) => {
45206
+ for (const { code } of getSgrTokens(sgrParameters)) {
45207
+ applySgrResetCode(code, activeStyles);
45208
+ }
45209
+ };
45210
+ var applyLeadingSgrResets = (string4, startIndex, activeStyles) => {
45211
+ let index2 = startIndex;
45212
+ while (index2 < string4.length) {
45213
+ const match10 = matchAnsiEscape(string4, index2);
45214
+ if (!match10) {
45215
+ break;
45216
+ }
45217
+ if (match10.groups.sgr !== undefined) {
45218
+ applySgrResets(match10.groups.sgr, activeStyles);
45219
+ }
45220
+ index2 += match10[0].length;
45221
+ }
45222
+ };
45223
+ var getClosingSgrSequence = (activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join("");
45224
+ var getOpeningSgrSequence = (activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join("");
45225
+ var wrapWord = (rows, word, columns, rowWidth) => {
45226
+ const tokens = getTokens(word);
45227
+ let visible = rowWidth;
45228
+ for (let index2 = 0;index2 < tokens.length; index2++) {
45229
+ const token = tokens[index2];
45230
+ if (token.width > 0 && visible > 0 && visible + token.width > columns) {
45231
+ rows.push("");
45232
+ visible = 0;
45233
+ }
45234
+ rows[rows.length - 1] += token.value;
45235
+ visible += token.width;
45236
+ if (visible === columns && index2 < tokens.length - 1) {
45237
+ rows.push("");
45238
+ visible = 0;
45239
+ }
45240
+ }
45241
+ if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
45242
+ rows[rows.length - 2] += rows.pop();
45243
+ }
45244
+ return getWidth(rows.at(-1));
45245
+ };
45246
+ var stringVisibleTrimSpacesRight = (string4) => {
45247
+ if (!string4.includes(" ")) {
45248
+ return string4;
45249
+ }
45250
+ const segments = [];
45251
+ forEachSegment(string4, (plainText) => {
45252
+ segments.push({ value: plainText, isEscape: false });
45253
+ }, (escape2) => {
45254
+ segments.push({ value: escape2, isEscape: true });
45255
+ });
45256
+ for (let index2 = segments.length - 1;index2 >= 0; index2--) {
45257
+ const segment = segments[index2];
45258
+ if (segment.isEscape) {
45259
+ continue;
45260
+ }
45261
+ let end3 = segment.value.length;
45262
+ while (end3 > 0 && segment.value[end3 - 1] === " ") {
45263
+ end3--;
45264
+ }
45265
+ segment.value = segment.value.slice(0, end3);
45266
+ if (getStringWidth(segment.value) > 0) {
45267
+ break;
45268
+ }
45269
+ }
45270
+ return segments.map((segment) => segment.value).join("");
45271
+ };
45272
+ var expandTabs = (line) => {
45273
+ if (!line.includes("\t")) {
45274
+ return line;
45275
+ }
45276
+ let visible = 0;
45277
+ let expandedLine = "";
45278
+ let plainTextSinceTab = "";
45279
+ const expandPlainText = (plainText) => {
45280
+ const segments = plainText.split("\t");
45281
+ for (const [index2, segment] of segments.entries()) {
45282
+ expandedLine += segment;
45283
+ plainTextSinceTab += segment;
45284
+ if (index2 < segments.length - 1) {
45285
+ visible += getStringWidth(plainTextSinceTab);
45286
+ plainTextSinceTab = "";
45287
+ const spaces = TAB_SIZE - visible % TAB_SIZE;
45288
+ expandedLine += " ".repeat(spaces);
45289
+ visible += spaces;
45290
+ }
45291
+ }
45292
+ };
45293
+ forEachSegment(line, expandPlainText, (escape2) => {
45294
+ expandedLine += escape2;
45295
+ });
45296
+ return expandedLine;
45297
+ };
45298
+ var restoreStylesAcrossRows = (preString) => {
45299
+ let returnValue = "";
45300
+ let activeHyperlink;
45301
+ const activeStyles = [];
45302
+ let index2 = 0;
45303
+ let copiedIndex = 0;
45304
+ while (index2 < preString.length) {
45305
+ ROW_BOUNDARY_REGEX.lastIndex = index2;
45306
+ const boundary = ROW_BOUNDARY_REGEX.exec(preString);
45307
+ if (!boundary) {
45308
+ break;
45309
+ }
45310
+ index2 = boundary.index;
45311
+ if (boundary[0] !== `
45312
+ `) {
45313
+ const escape2 = matchAnsiEscape(preString, index2);
45314
+ if (!escape2) {
45315
+ index2++;
45316
+ continue;
45317
+ }
45318
+ const { groups } = escape2;
45319
+ if (groups.sgr !== undefined) {
45320
+ applySgrParameters(groups.sgr, activeStyles);
45321
+ } else if (groups.uri !== undefined) {
45322
+ activeHyperlink = groups.uri.length === 0 ? undefined : { parameters: groups.parameters, uri: groups.uri };
45323
+ }
45324
+ index2 += escape2[0].length;
45325
+ continue;
45326
+ }
45327
+ returnValue += preString.slice(copiedIndex, index2);
45328
+ if (index2 > copiedIndex) {
45329
+ if (activeHyperlink) {
45330
+ returnValue += wrapAnsiHyperlink("");
45331
+ }
45332
+ returnValue += getClosingSgrSequence(activeStyles);
45333
+ }
45334
+ returnValue += `
45335
+ `;
45336
+ index2++;
45337
+ copiedIndex = index2;
45338
+ if (index2 < preString.length && preString[index2] !== `
45339
+ `) {
45340
+ const openingStyles = [...activeStyles];
45341
+ applyLeadingSgrResets(preString, index2, openingStyles);
45342
+ returnValue += getOpeningSgrSequence(openingStyles);
45343
+ if (activeHyperlink) {
45344
+ returnValue += wrapAnsiHyperlink(activeHyperlink.uri, activeHyperlink.parameters);
45345
+ }
45346
+ }
45347
+ }
45348
+ return returnValue + preString.slice(copiedIndex);
45349
+ };
45350
+ var exec = (string4, columns, options3 = {}) => {
45351
+ if (options3.trim !== false && string4.trim() === "") {
45352
+ return "";
45353
+ }
45354
+ const words = splitWords(string4);
45355
+ let rows = [""];
45356
+ let rowLength = 0;
45357
+ let trimmedRowIndex = -1;
45358
+ let isFirstWord = true;
45359
+ for (const word of words) {
45360
+ const rowIndex = rows.length - 1;
45361
+ if (options3.trim !== false && trimmedRowIndex !== rowIndex) {
45362
+ const row = rows[rowIndex];
45363
+ const trimmedRow = row.trimStart();
45364
+ if (trimmedRow.length !== row.length) {
45365
+ rows[rowIndex] = trimmedRow;
45366
+ rowLength = getWidth(trimmedRow);
45367
+ }
45368
+ if (trimmedRow.length > 0) {
45369
+ trimmedRowIndex = rowIndex;
45370
+ }
45371
+ }
45372
+ if (isFirstWord) {
45373
+ isFirstWord = false;
45374
+ } else {
45375
+ if (rowLength >= columns && (options3.wordWrap === false || options3.trim === false)) {
45376
+ rows.push("");
45377
+ rowLength = 0;
45378
+ }
45379
+ if (rowLength > 0 || options3.trim === false) {
45380
+ rows[rows.length - 1] += " ";
45381
+ rowLength++;
45382
+ }
45383
+ }
45384
+ if (options3.hard && options3.wordWrap !== false && word.width > columns) {
45385
+ const remainingColumns = columns - rowLength;
45386
+ const breaksStartingThisLine = 1 + Math.floor((word.width - remainingColumns - 1) / columns);
45387
+ const breaksStartingNextLine = Math.floor((word.width - 1) / columns);
45388
+ if (breaksStartingNextLine < breaksStartingThisLine) {
45389
+ rows.push("");
45390
+ rowLength = 0;
45391
+ }
45392
+ rowLength = wrapWord(rows, word.value, columns, rowLength);
45393
+ continue;
45394
+ }
45395
+ if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
45396
+ if (options3.wordWrap === false && rowLength < columns) {
45397
+ rowLength = wrapWord(rows, word.value, columns, rowLength);
45398
+ continue;
45399
+ }
45400
+ rows.push("");
45401
+ rowLength = 0;
45402
+ }
45403
+ if (rowLength + word.width > columns && options3.wordWrap === false) {
45404
+ rowLength = wrapWord(rows, word.value, columns, rowLength);
45405
+ continue;
45406
+ }
45407
+ rows[rows.length - 1] += word.value;
45408
+ rowLength += word.width;
45409
+ }
45410
+ if (options3.trim !== false) {
45411
+ rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
45412
+ }
45413
+ return restoreStylesAcrossRows(rows.join(`
45414
+ `));
45415
+ };
45416
+ var normalizeText = (string4) => {
45417
+ let normalizedString = "";
45418
+ forEachSegment(string4, (plainText) => {
45419
+ normalizedString += plainText.normalize();
45420
+ }, (escape2) => {
45421
+ normalizedString += escape2;
45422
+ });
45423
+ return normalizedString;
45424
+ };
45425
+ function wrapAnsi(string4, columns, options3) {
45426
+ return normalizeText(String(string4)).replaceAll(`\r
45427
+ `, `
45428
+ `).split(`
45429
+ `).map((line) => exec(expandTabs(line), columns, options3)).join(`
45430
+ `);
43998
45431
  }
43999
- var cmdWord = (value5) => /^[\w@+=:,./\\-]+$/.test(value5) ? value5 : `"${value5}"`;
44000
- var powershellString = (value5) => `'${value5.replaceAll("'", "''")}'`;
44001
- var taskScheduler = {
44002
- name: "Task Scheduler task",
44003
- install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
44004
- const command = [
44005
- ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
44006
- `set "PATH=${job2.nodeDirectory};%PATH%"`,
44007
- `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
44008
- ].join(" && ");
44009
- const script = [
44010
- "$ErrorActionPreference = 'Stop'",
44011
- "$ProgressPreference = 'SilentlyContinue'",
44012
- `$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument ${powershellString(`/d /v:off /s /c "${command}"`)}`,
44013
- `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
44014
- "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44015
- `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44016
- ].join(`
45432
+
45433
+ // packages/cli/src/format.ts
45434
+ function csvCell(value5) {
45435
+ const text2 = value5 === null ? "" : String(value5);
45436
+ const safe = /^[=+\-@\t\r\n]/.test(text2) ? `'${text2}` : text2;
45437
+ return `"${safe.replaceAll('"', '""')}"`;
45438
+ }
45439
+ function csv(report) {
45440
+ const summary = projectSummary(report, false);
45441
+ const headings = summary.headings.map((heading) => heading === "API estimate" ? "API estimate (USD)" : heading);
45442
+ return [headings, ...summary.rows].map((row) => row.map(csvCell).join(",")).join(`
44017
45443
  `);
44018
- const options3 = ["-NoProfile", "-NonInteractive", "-EncodedCommand"];
44019
- return [
44020
- Action3.Run({
44021
- program: "powershell.exe",
44022
- args: [...options3, Buffer.from(script, "utf16le").toString("base64")],
44023
- shown: `powershell.exe ${options3.join(" ")} <the script below, as UTF-16LE Base64>
44024
- ${script}`,
44025
- outcome: "required",
44026
- hint: "",
44027
- gone: []
45444
+ }
45445
+ function terminalText(value5) {
45446
+ return value5.replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
45447
+ }
45448
+ function projectSummary(report, grouped2) {
45449
+ const projects = new Map;
45450
+ for (const row of report.rows) {
45451
+ const previous = projects.get(row.project);
45452
+ projects.set(row.project, {
45453
+ tokens: addTokens(previous?.tokens ?? zeroTokens, row.tokens),
45454
+ cost: (previous?.cost ?? 0) + row.pricedCostUsd,
45455
+ unpriced: (previous?.unpriced ?? 0) + row.unpricedRecords
45456
+ });
45457
+ }
45458
+ const cost = [...projects.values()].reduce((sum3, project) => sum3 + project.cost, 0);
45459
+ const unpriced = [...projects.values()].reduce((sum3, project) => sum3 + project.unpriced, 0);
45460
+ const headings = [
45461
+ "Project",
45462
+ "Input",
45463
+ "Cache read",
45464
+ "Cache write",
45465
+ "Output",
45466
+ "API estimate",
45467
+ unpriced ? "Known cost %" : "Cost %"
45468
+ ];
45469
+ const percentage = new Intl.NumberFormat("en-US", {
45470
+ style: "percent",
45471
+ minimumFractionDigits: 1,
45472
+ maximumFractionDigits: 1
45473
+ });
45474
+ const share2 = (value5) => cost > 0 ? percentage.format(value5 / cost) : "—";
45475
+ const number4 = new Intl.NumberFormat("en-US", { useGrouping: grouped2 });
45476
+ const dollars = new Intl.NumberFormat("en-US", {
45477
+ style: "currency",
45478
+ currency: "USD",
45479
+ useGrouping: grouped2
45480
+ });
45481
+ let allTokens = zeroTokens;
45482
+ const rows = [];
45483
+ const ranked = [...projects].toSorted(([leftProject, left], [rightProject, right]) => right.cost - left.cost || leftProject.localeCompare(rightProject));
45484
+ for (const [project, total] of ranked) {
45485
+ rows.push([
45486
+ project,
45487
+ number4.format(total.tokens.input),
45488
+ number4.format(total.tokens.cacheRead),
45489
+ number4.format(total.tokens.cacheWrite),
45490
+ number4.format(total.tokens.output),
45491
+ `${dollars.format(total.cost)}${total.unpriced ? " + unknown" : ""}`,
45492
+ share2(total.cost)
45493
+ ]);
45494
+ allTokens = addTokens(allTokens, total.tokens);
45495
+ }
45496
+ if (projects.size > 0)
45497
+ rows.push([
45498
+ "Total",
45499
+ number4.format(allTokens.input),
45500
+ number4.format(allTokens.cacheRead),
45501
+ number4.format(allTokens.cacheWrite),
45502
+ number4.format(allTokens.output),
45503
+ `${dollars.format(cost)}${unpriced ? " + unknown" : ""}`,
45504
+ share2(cost)
45505
+ ]);
45506
+ return { headings, rows, allTokens, unpriced, projectCount: projects.size };
45507
+ }
45508
+ function table2(report, columns = 120, colorful = false) {
45509
+ const paint = (format10, value5) => colorful ? styleText(format10, value5, { validateStream: false }) : value5;
45510
+ const { headings, rows, allTokens, unpriced, projectCount } = projectSummary(report, true);
45511
+ const number4 = new Intl.NumberFormat("en-US");
45512
+ if (projectCount === 0)
45513
+ return `No observed usage from ${report.since} through ${report.until} (${report.timeZone}).`;
45514
+ const numericWidths = headings.slice(1).map((heading, i) => Math.max(heading.length, ...rows.map((row) => row[i + 1]?.length ?? 0)) + 2);
45515
+ const projectWidth = columns - numericWidths.reduce((sum3, width2) => sum3 + width2, 0) - (headings.length + 1);
45516
+ const narrow = projectWidth < 22;
45517
+ const colWidths = narrow ? [16, Math.max(4, columns - 19)] : [Math.min(50, projectWidth), ...numericWidths];
45518
+ const output = new import_cli_table3.default({
45519
+ head: narrow ? [] : headings.map((heading) => paint(["bold", "cyan"], heading)),
45520
+ colWidths,
45521
+ colAligns: narrow ? ["left", "right"] : ["left", "right", "right", "right", "right", "right", "right"],
45522
+ wordWrap: false,
45523
+ style: { head: [], border: [] }
45524
+ });
45525
+ const projectColors = [
45526
+ "cyan",
45527
+ "blueBright",
45528
+ "magenta",
45529
+ "yellow",
45530
+ "green",
45531
+ "cyanBright"
45532
+ ];
45533
+ for (const [index2, row] of rows.entries()) {
45534
+ const styled = row.map((value5, column) => {
45535
+ const width2 = narrow ? column === 0 ? columns - 4 : columns - 21 : (colWidths[column] ?? 4) - 2;
45536
+ const cell = wrapAnsi(terminalText(value5), Math.max(2, width2), {
45537
+ hard: true,
45538
+ wordWrap: false,
45539
+ trim: false
45540
+ });
45541
+ if (index2 === rows.length - 1)
45542
+ return paint(["bold", "magenta"], cell);
45543
+ if (column === 0)
45544
+ return paint(projectColors[index2 % projectColors.length] ?? "cyan", cell);
45545
+ if (column >= headings.length - 2)
45546
+ return paint(value5.includes("unknown") ? "yellow" : "green", cell);
45547
+ return cell === "0" ? paint("dim", cell) : cell;
45548
+ });
45549
+ if (narrow) {
45550
+ output.push([{ content: styled[0] ?? "", colSpan: 2, hAlign: "left" }]);
45551
+ for (const [i, heading] of headings.slice(1).entries()) {
45552
+ output.push([paint("cyan", heading), styled[i + 1] ?? ""]);
45553
+ }
45554
+ } else {
45555
+ output.push(styled);
45556
+ }
45557
+ }
45558
+ return [
45559
+ `${paint(["bold", "cyan"], colorful ? "⚡ Token Ledger" : "Token Ledger")} · ${paint("dim", `${report.since} through ${report.until} (${report.timeZone})`)}`,
45560
+ "",
45561
+ output.toString(),
45562
+ "",
45563
+ paint("bold", `${colorful ? "\uD83D\uDCCA " : ""}${number4.format(totalTokens(allTokens))} observed tokens · ${number4.format(projectCount)} ${projectCount === 1 ? "project" : "projects"}`),
45564
+ ...unpriced > 0 ? [
45565
+ paint("yellow", "Incomplete pricing: sorting and percentages use known API subtotals; unknown costs are additional.")
45566
+ ] : [],
45567
+ paint("dim", "USD API-equivalent estimates; not your subscription bill.")
45568
+ ].join(`
45569
+ `);
45570
+ }
45571
+ function syncSummary(payload, request3, storedBuckets) {
45572
+ const number4 = new Intl.NumberFormat("en-US");
45573
+ const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
45574
+ const sessions = new Set(payload.buckets.map((bucket) => bucket.sessionKey)).size;
45575
+ const cost = payload.buckets.reduce((sum3, bucket) => sum3 + (bucket.estimatedCostUsd ?? 0), 0);
45576
+ const unknown2 = payload.buckets.some((bucket) => bucket.estimatedCostUsd === null);
45577
+ return [
45578
+ `Synced ${terminalText(payload.machine.label)} · ${request3.since} through ${request3.until} (${payload.timeZone})`,
45579
+ [
45580
+ `${number4.format(payload.buckets.length)} hourly buckets`,
45581
+ `${number4.format(sessions)} sessions`,
45582
+ `${dollars.format(cost)}${unknown2 ? " + unknown" : ""} API estimate`,
45583
+ exports_Option.match(storedBuckets, {
45584
+ onNone: () => "accepted by the server",
45585
+ onSome: (stored) => `server stored ${number4.format(stored)}`
44028
45586
  })
44029
- ];
44030
- })),
44031
- uninstall: [
44032
- run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44033
- run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above.")
44034
- ],
44035
- status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
44036
- };
44037
- var hostScheduler = exports_Effect.gen(function* () {
44038
- const path = yield* exports_Path.Path;
44039
- const home = homedir2();
44040
- const units = exports_Option.getOrElse(yield* configHome, () => path.join(home, ".config"));
44041
- return yield* exports_Match.value(process.platform).pipe(exports_Match.when("linux", () => exports_Effect.succeed(systemdTimer(path.join(units, "systemd", "user")))), exports_Match.when("darwin", () => exports_Effect.succeed(launchAgent(home, userInfo().uid))), exports_Match.when("win32", () => exports_Effect.succeed(taskScheduler)), exports_Match.orElse((platform) => exports_Effect.fail(new ScheduleError({
44042
- message: `No scheduler is supported on ${platform}; schedule token-ledger sync yourself.`
44043
- }))));
44044
- });
44045
- var describe = (actions) => actions.map(Action3.$match({
44046
- Write: ({ file: file2, contents }) => `write ${file2}
44047
- ${contents.replaceAll(/^(?=.)/gm, " ")}`,
44048
- Remove: ({ file: file2 }) => `remove ${file2}
44049
- `,
44050
- Run: ({ shown }) => `run ${shown}
44051
- `
44052
- })).join(`
45587
+ ].join(" · ")
45588
+ ].join(`
44053
45589
  `);
44054
- var perform = exports_Effect.fn("Schedule.perform")(function* (actions) {
44055
- const fs = yield* exports_FileSystem.FileSystem;
44056
- const path = yield* exports_Path.Path;
44057
- const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44058
- for (const action of actions)
44059
- yield* Action3.$match(action, {
44060
- Write: ({ file: file2, contents }) => fs.makeDirectory(path.dirname(file2), { recursive: true }).pipe(exports_Effect.andThen(fs.writeFileString(file2, contents)), exports_Effect.mapError(() => new ScheduleError({ message: `Cannot write ${file2}.` }))),
44061
- Remove: ({ file: file2 }) => fs.remove(file2, { force: true }).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot remove ${file2}.` }))),
44062
- Run: ({ program, args: args2, outcome, hint, gone }) => {
44063
- const output = outcome === "silent" || outcome === "absent" ? "ignore" : "inherit";
44064
- const exit3 = spawner.exitCode(exports_ChildProcess.make(program, args2, { stdin: "ignore", stdout: output, stderr: output })).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot run ${program}. ${hint}`.trim() })));
44065
- return exports_Match.value(outcome).pipe(exports_Match.when("required", () => exports_Effect.filterOrFail(exit3, (code) => code === 0, (code) => new ScheduleError({
44066
- message: `${[program, ...args2.slice(0, 2)].join(" ")} failed with exit code ${code}. ${hint}`.trim()
44067
- }))), exports_Match.when("reported", () => exit3), exports_Match.when("silent", () => exports_Effect.ignore(exit3)), exports_Match.when("absent", () => exit3.pipe(exports_Effect.map((code) => gone.length === 0 ? code !== 0 : gone.includes(code)), exports_Effect.orElseSucceed(() => true), exports_Effect.filterOrFail((confirmed) => confirmed, () => new ScheduleError({ message: hint })))), exports_Match.exhaustive);
44068
- }
44069
- });
44070
- });
45590
+ }
44071
45591
 
44072
45592
  // packages/cli/src/upload.ts
44073
45593
  class SyncUnreachable extends exports_Schema.TaggedError()("SyncUnreachable", {
@@ -44090,6 +45610,17 @@ class SyncRejected extends exports_Schema.TaggedError()("SyncRejected", {
44090
45610
  }) {
44091
45611
  }
44092
45612
  var Acknowledgement = exports_Schema.Struct({ storedBuckets: exports_Schema.Natural });
45613
+ var MachineList = exports_Schema.Struct({
45614
+ staleAfterDays: exports_Schema.Number,
45615
+ from: exports_Schema.String,
45616
+ to: exports_Schema.String,
45617
+ machines: exports_Schema.Array(exports_Schema.Struct({ machineId: exports_Schema.String.check(exports_Schema.isUUID()) }))
45618
+ });
45619
+ function endpoint(server, path) {
45620
+ const base = new URL(server);
45621
+ base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
45622
+ return new URL(path, base);
45623
+ }
44093
45624
  var VersionRejection = exports_Schema.Struct({ supportedVersions: exports_Schema.Array(exports_Schema.Int) });
44094
45625
  var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, version) {
44095
45626
  const status = response.status;
@@ -44111,9 +45642,7 @@ var readResponse = exports_Effect.fn("Sync.readResponse")(function* (response, v
44111
45642
  });
44112
45643
  var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload) {
44113
45644
  const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
44114
- const base = new URL(server);
44115
- base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
44116
- const url = new URL(`ai-usage/machines/${payload.machine.id}/usage`, base);
45645
+ const url = endpoint(server, `ai-usage/machines/${payload.machine.id}/usage`);
44117
45646
  const request3 = yield* exports_HttpClientRequest.put(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson, exports_HttpClientRequest.schemaBodyJson(SyncPayload)(payload), exports_Effect.orDie);
44118
45647
  return yield* client.execute(request3).pipe(exports_Effect.flatMap((response) => readResponse(response, payload.version)), exports_Effect.scoped, exports_Effect.timeout("60 seconds"), exports_Effect.catchTag(["HttpClientError", "TimeoutError"], () => exports_Effect.fail(new SyncUnreachable({ message: `Cannot reach ${url.origin}; try again later.` }))), exports_Effect.retry({
44119
45648
  while: exports_Predicate.isTagged("SyncUnreachable"),
@@ -44121,6 +45650,14 @@ var upload = exports_Effect.fn("Sync.upload")(function* (server, token, payload)
44121
45650
  times: 3
44122
45651
  }));
44123
45652
  });
45653
+ var hasUploaded = exports_Effect.fn("Sync.hasUploaded")(function* (server, token, id2) {
45654
+ const client = (yield* exports_HttpClient.HttpClient).pipe(exports_HttpClient.withScope);
45655
+ const url = endpoint(server, "ai-usage/machines");
45656
+ const unanswered = new SyncUnreachable({
45657
+ message: `Could not ask ${url.origin} whether this machine has uploaded before.`
45658
+ });
45659
+ return yield* client.execute(exports_HttpClientRequest.get(url).pipe(exports_HttpClientRequest.bearerToken(token), exports_HttpClientRequest.acceptJson)).pipe(exports_Effect.filterOrFail((response) => response.status === 200, () => unanswered), exports_Effect.flatMap(exports_HttpClientResponse.schemaBodyJson(MachineList)), exports_Effect.map(({ machines }) => machines.some((machine) => machine.machineId.toLowerCase() === id2.toLowerCase())), exports_Effect.scoped, exports_Effect.timeout("20 seconds"), exports_Effect.provideService(exports_FetchHttpClient.RequestInit, { redirect: "error" }), exports_Effect.mapError(() => unanswered));
45660
+ });
44124
45661
 
44125
45662
  // packages/cli/src/main.ts
44126
45663
  class CliError2 extends exports_Schema.TaggedError()("CliError", { message: exports_Schema.String }) {
@@ -44168,13 +45705,7 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
44168
45705
  { provider: "codex", path: path.join(expand(codexHome), "archived_sessions") },
44169
45706
  { provider: "claude", path: path.join(expand(claudeHome), "projects") },
44170
45707
  { provider: "grok", path: path.join(expand(grokHome), "sessions") },
44171
- {
44172
- provider: "copilot",
44173
- path: exports_Option.match(copilotFile, {
44174
- onNone: () => path.join(expand(copilotHome), "otel"),
44175
- onSome: (value5) => expand(value5)
44176
- })
44177
- },
45708
+ ...(yield* copilotSources(path.join(expand(copilotHome), "otel"), exports_Option.map(copilotFile, (value5) => expand(value5)))).map((source) => ({ provider: "copilot", path: source })),
44178
45709
  {
44179
45710
  provider: "pi",
44180
45711
  path: exports_Option.match(piSessions, {
@@ -44250,7 +45781,7 @@ var serverFlag = exports_Flag.String("server").pipe(exports_Flag.withSchema(Serv
44250
45781
  var tokenFlag = exports_Flag.Redacted("token").pipe(exports_Flag.withFallbackConfig(exports_Config.Redacted("TOKI_API_TOKEN")), exports_Flag.optional);
44251
45782
  var claudeRetentionDays = 30;
44252
45783
  var sync6 = exports_Command.make("sync", {
44253
- ...usageFlags("13 days before --until", "Exit 2 without uploading for missing/partial sources or unpriced usage"),
45784
+ ...usageFlags("13 days before --until; a machine's first sync goes back to its earliest usage", "Exit 2 without uploading for missing/partial sources or unpriced usage"),
44254
45785
  server: serverFlag.pipe(exports_Flag.withDescription("toki2 URL; otherwise TOKEN_LEDGER_SERVER or sync.json")),
44255
45786
  token: tokenFlag.pipe(exports_Flag.withDescription("toki2 API token; prefer TOKI_API_TOKEN or sync.json")),
44256
45787
  dryRun: exports_Flag.Boolean("dry-run").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Print the payload as JSON and upload nothing"))
@@ -44260,42 +45791,69 @@ var sync6 = exports_Command.make("sync", {
44260
45791
  const { request: request3, today } = yield* usageRequest({ ...flags, source: exports_Option.none() }, (today2) => addDays(until ?? today2, -13));
44261
45792
  const machine = yield* loadMachine(directory);
44262
45793
  const ledger = yield* Ledger;
44263
- const payload = yield* ledger.syncPayload(request3, {
44264
- machine,
44265
- version: package_default.version
44266
- });
44267
- for (const entry of payload.coverage) {
44268
- if (entry.status !== "ok")
44269
- yield* exports_Console.error(`${entry.provider}: ${entry.status}; ${entry.files} files, ${entry.filesBeforeWindow ?? 0} older files not opened, ${entry.unreadable} unreadable, ${entry.malformedLines} malformed lines, ${entry.skippedRecords} skipped records.${entry.status === "failed" ? " Not uploaded; the server keeps its stored usage." : ""}`);
44270
- }
44271
- if (request3.sources.some((source) => source.provider === "claude") && request3.since < addDays(today, 1 - claudeRetentionDays))
45794
+ const client = { machine, version: package_default.version };
45795
+ const unsaved = {};
45796
+ const saved = exports_Option.isSome(flags.server) && exports_Option.isSome(flags.token) ? exports_Result.succeed(unsaved) : yield* loadSyncSettings(directory).pipe(exports_Effect.result);
45797
+ const settings = exports_Result.isSuccess(saved) ? saved.success : unsaved;
45798
+ const server = exports_Option.orElse(flags.server, () => exports_Option.fromUndefinedOr(settings.server));
45799
+ const token = exports_Option.orElse(flags.token, () => exports_Option.fromUndefinedOr(settings.token));
45800
+ const unlisted2 = exports_Option.isSome(flags.since) || exports_Option.isNone(server) || exports_Option.isNone(token) ? exports_Option.none() : yield* hasUploaded(server.value, token.value, machine.id).pipe(exports_Effect.map((listed2) => !listed2), exports_Effect.option);
45801
+ const whole = exports_Option.contains(unlisted2, true);
45802
+ const reachable = exports_Option.isSome(server) && exports_Option.isSome(token);
45803
+ if (exports_Option.isNone(unlisted2) && exports_Option.isNone(flags.since) && (reachable || flags.dryRun))
45804
+ yield* exports_Console.error(`${reachable ? "Could not ask the server whether this machine has uploaded before" : "No server and API token to ask whether this machine has uploaded before"}, so the window is ${request3.since} through ${request3.until}. If this is its first upload, send its earlier history with --since.`);
45805
+ const first = whole ? yield* ledger.historyPayload(request3, client) : { payload: yield* ledger.syncPayload(request3, client), since: request3.since };
45806
+ if (whole)
45807
+ yield* exports_Console.error(`First upload from this machine: taking in all the history found, from ${first.since}. Later syncs cover the last 14 days.${flags.provider === "all" ? "" : ` Only ${flags.provider} is included; the other tools' earlier history is not sent later by itself, so send it with --provider and --since.`}`);
45808
+ const examine = exports_Effect.fn("CLI.examine")(function* (payload) {
45809
+ for (const entry of payload.coverage) {
45810
+ if (entry.status !== "ok")
45811
+ yield* exports_Console.error(`${entry.provider}: ${entry.status}; ${entry.files} files, ${entry.filesBeforeWindow ?? 0} older files not opened, ${entry.unreadable} unreadable, ${entry.malformedLines} malformed lines, ${entry.skippedRecords} skipped records.${entry.status === "failed" ? " Not uploaded; the server keeps its stored usage." : ""}`);
45812
+ if (whole && entry.status === "failed")
45813
+ yield* exports_Console.error(`${entry.provider}: once its history can be read, send the earlier part with token-ledger sync --provider ${entry.provider} --since <first day>.`);
45814
+ }
45815
+ return payload.coverage.some((entry) => entry.status !== "ok") || payload.buckets.some((bucket) => bucket.unpricedRecords > 0);
45816
+ });
45817
+ const incomplete = yield* examine(first.payload);
45818
+ if (!whole && request3.sources.some((source) => source.provider === "claude") && request3.since < addDays(today, 1 - claudeRetentionDays))
44272
45819
  yield* exports_Console.error(`Warning: the window starts more than ${claudeRetentionDays} days ago. Claude Code deletes older transcripts by default, and the server replaces the whole window, so pruned history would lower its totals.`);
44273
- const incomplete = payload.coverage.some((entry) => entry.status !== "ok") || payload.buckets.some((bucket) => bucket.unpricedRecords > 0);
44274
45820
  if (flags.dryRun) {
44275
- yield* exports_Console.log(JSON.stringify(payload, null, 2));
45821
+ yield* exports_Console.log(JSON.stringify(first.payload, null, 2));
44276
45822
  if (flags.strict && incomplete)
44277
45823
  process.exitCode = 2;
44278
45824
  return;
44279
45825
  }
44280
- if (flags.strict && incomplete) {
45826
+ const refused = exports_Effect.gen(function* () {
44281
45827
  yield* exports_Console.error("Not syncing: coverage is incomplete or usage is unpriced (--strict).");
44282
45828
  process.exitCode = 2;
44283
- return;
44284
- }
44285
- const settings = exports_Option.isSome(flags.server) && exports_Option.isSome(flags.token) ? {} : yield* loadSyncSettings(directory);
44286
- const server = exports_Option.orElse(flags.server, () => exports_Option.fromUndefinedOr(settings.server));
44287
- const token = exports_Option.orElse(flags.token, () => exports_Option.fromUndefinedOr(settings.token));
45829
+ });
45830
+ if (flags.strict && incomplete)
45831
+ return yield* refused;
45832
+ if (exports_Result.isFailure(saved))
45833
+ return yield* exports_Effect.fail(saved.failure);
44288
45834
  if (exports_Option.isNone(server) || exports_Option.isNone(token))
44289
45835
  return yield* new CliError2({
44290
45836
  message: `Missing ${exports_Option.isNone(server) ? "server" : "API token"}: pass --server/--token, set TOKEN_LEDGER_SERVER/TOKI_API_TOKEN, or add it to ${directory}/sync.json.`
44291
45837
  });
44292
- const outcome = yield* upload(server.value, token.value, payload).pipe(exports_Effect.result);
45838
+ const send = (payload) => upload(server.value, token.value, payload).pipe(exports_Effect.result);
45839
+ const usual = exports_Effect.fn("CLI.usual")(function* (reason) {
45840
+ yield* exports_Console.error(`${reason} Uploading ${request3.since} through ${request3.until} instead; send earlier history in parts with --since and --until.`);
45841
+ const payload = yield* ledger.syncPayload(request3, client);
45842
+ return (yield* examine(payload)) && flags.strict ? exports_Option.none() : exports_Option.some({ sent: { payload, since: request3.since }, outcome: yield* send(payload) });
45843
+ });
45844
+ const still = !whole || !(yield* hasUploaded(server.value, token.value, machine.id).pipe(exports_Effect.orElseSucceed(() => true)));
45845
+ let result6 = still ? exports_Option.some({ sent: first, outcome: yield* send(first.payload) }) : yield* usual("This machine has uploaded since it was asked about.");
45846
+ if (whole && exports_Option.isSome(result6) && exports_Result.isFailure(result6.value.outcome) && exports_Match.value(result6.value.outcome.failure).pipe(exports_Match.tag("SyncRejected", () => still), exports_Match.orElse(() => false)))
45847
+ result6 = yield* usual(result6.value.outcome.failure.message);
45848
+ if (exports_Option.isNone(result6))
45849
+ return yield* refused;
45850
+ const { sent, outcome } = result6.value;
44293
45851
  if (exports_Result.isFailure(outcome)) {
44294
45852
  yield* exports_Console.error(outcome.failure.message);
44295
45853
  process.exitCode = exports_Match.value(outcome.failure).pipe(exports_Match.tag("SyncUnreachable", () => 3), exports_Match.tag("SyncUnauthorized", () => 4), exports_Match.tag("SyncUnsupportedVersion", () => 5), exports_Match.tag("SyncRejected", () => 6), exports_Match.exhaustive);
44296
45854
  return;
44297
45855
  }
44298
- yield* exports_Console.log(syncSummary(payload, request3, outcome.success));
45856
+ yield* exports_Console.log(syncSummary(sent.payload, { ...request3, since: sent.since }, outcome.success));
44299
45857
  })).pipe(exports_Command.withDescription("Upload hourly usage buckets from this machine to toki2; the server replaces the window"));
44300
45858
  var interactive = (prompt) => exports_Prompt.run(prompt).pipe(exports_Effect.mapError(() => new CliError2({
44301
45859
  message: "Nothing was saved. Without a terminal, pass --server and set TOKI_API_TOKEN."
@@ -44366,6 +45924,65 @@ var scheduleUninstall = exports_Command.make("uninstall", {}, exports_Effect.fn(
44366
45924
  yield* exports_Console.log(`Removed the ${scheduler.name}. Saved settings were kept.`);
44367
45925
  })).pipe(exports_Command.withDescription("Remove the daily sync; saved settings stay"));
44368
45926
  var schedule4 = exports_Command.make("schedule").pipe(exports_Command.withDescription("Run sync daily with systemd, launchd, or Task Scheduler"), exports_Command.withSubcommands([scheduleInstall, scheduleStatus, scheduleUninstall]));
45927
+ var copilotEnable = exports_Command.make("enable", {
45928
+ cli: exports_Flag.Boolean("cli").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Copilot CLI: export its usage from every new terminal")),
45929
+ vscode: exports_Flag.Boolean("vscode").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("VS Code Copilot Chat: set its export in the user settings.json")),
45930
+ yes: exports_Flag.Boolean("yes").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Make the listed changes without asking")),
45931
+ dryRun: exports_Flag.Boolean("dry-run").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Print the changes; change nothing")),
45932
+ allowRoot: exports_Flag.Boolean("allow-root").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Run as root, where root is the account that uses Copilot"))
45933
+ }, exports_Effect.fn("CLI.copilotEnable")(function* (flags) {
45934
+ const path = yield* exports_Path.Path;
45935
+ const copilotHome = yield* exports_Config.String("COPILOT_HOME").pipe(exports_Config.withDefault(path.join(home, ".copilot")));
45936
+ const host = {
45937
+ platform: process.platform,
45938
+ home,
45939
+ uid: exports_Option.fromUndefinedOr(process.getuid?.()),
45940
+ copilotHome: expandPath(path, copilotHome),
45941
+ shell: yield* exports_Config.String("SHELL").pipe(exports_Config.option),
45942
+ zshDirectory: yield* exports_Config.String("ZDOTDIR").pipe(exports_Config.option),
45943
+ configHome: yield* configHome,
45944
+ appData: yield* exports_Config.String("APPDATA").pipe(exports_Config.option),
45945
+ exporter: exports_Option.map(yield* exports_Config.String("COPILOT_OTEL_FILE_EXPORTER_PATH").pipe(exports_Config.option), (file2) => expandPath(path, file2))
45946
+ };
45947
+ const stop = (message) => exports_Console.error(message).pipe(exports_Effect.andThen(exports_Effect.sync(() => {
45948
+ process.exitCode = 1;
45949
+ })));
45950
+ const planned = yield* plan(host, {
45951
+ cli: flags.cli || !flags.vscode,
45952
+ vscode: flags.vscode || !flags.cli,
45953
+ allowRoot: flags.allowRoot
45954
+ }).pipe(exports_Effect.result);
45955
+ if (exports_Result.isFailure(planned))
45956
+ return yield* stop(planned.failure.message);
45957
+ const { directory, steps } = planned.success;
45958
+ const incomplete = (results3) => {
45959
+ if (results3.some(Step.$is("ByHand")))
45960
+ process.exitCode = 2;
45961
+ };
45962
+ if (!steps.some(Step.$is("Change"))) {
45963
+ yield* exports_Console.log(steps.some(Step.$is("ByHand")) ? describe2(steps) : `Copilot's usage export is already on; nothing to change.
45964
+
45965
+ ${describe2(steps)}`);
45966
+ return incomplete(steps);
45967
+ }
45968
+ yield* exports_Console.log(`${describe2(steps)}
45969
+ `);
45970
+ if (flags.dryRun)
45971
+ return incomplete(steps);
45972
+ if (!flags.yes) {
45973
+ if (!process.stdin.isTTY)
45974
+ return yield* stop("Nothing was changed: there is no terminal to ask on. Run it again with --yes to make these changes.");
45975
+ const agreed = yield* exports_Prompt.run(exports_Prompt.Confirm({ message: "Make these changes?", initial: true })).pipe(exports_Effect.orElseSucceed(() => false));
45976
+ if (!agreed)
45977
+ return yield* stop("Nothing was changed.");
45978
+ }
45979
+ const results2 = yield* perform2(steps).pipe(exports_Effect.result);
45980
+ if (exports_Result.isFailure(results2))
45981
+ return yield* stop(results2.failure.message);
45982
+ yield* exports_Console.log(summarize(results2.success, directory));
45983
+ return incomplete(results2.success);
45984
+ })).pipe(exports_Command.withDescription("Switch on Copilot's local usage export, after listing the changes and asking"));
45985
+ var copilot = exports_Command.make("copilot").pipe(exports_Command.withDescription("Set up Copilot CLI and VS Code Copilot Chat to record usage"), exports_Command.withSubcommands([copilotEnable]));
44369
45986
  var example = exports_Command.make("config-example", {}, () => exports_Console.log(JSON.stringify({
44370
45987
  projects: [
44371
45988
  {
@@ -44376,4 +45993,4 @@ var example = exports_Command.make("config-example", {}, () => exports_Console.l
44376
45993
  ],
44377
45994
  prices: { "example-model": { input: 2, output: 10, cacheRead: 0.2, cacheWrite: null } }
44378
45995
  }, null, 2))).pipe(exports_Command.withDescription("Print an example configuration to customize"));
44379
- exports_Command.make("token-ledger").pipe(exports_Command.withDescription("Local token accounting across coding agents. API estimates, not subscription bills."), exports_Command.withSubcommands([report, sync6, login, schedule4, example]), exports_Command.run({ version: package_default.version }), exports_Effect.provide(Ledger.layer), exports_Effect.provide(exports_NodeServices.layer), exports_Effect.provide(exports_FetchHttpClient.layer), exports_NodeRuntime.runMain);
45996
+ exports_Command.make("token-ledger").pipe(exports_Command.withDescription("Local token accounting across coding agents. API estimates, not subscription bills."), exports_Command.withSubcommands([report, sync6, login, schedule4, copilot, example]), exports_Command.run({ version: package_default.version }), exports_Effect.provide(Ledger.layer), exports_Effect.provide(exports_NodeServices.layer), exports_Effect.provide(exports_FetchHttpClient.layer), exports_NodeRuntime.runMain);