tenjin-cli 0.1.0-alpha.5 → 0.1.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +169 -199
  2. package/dist/{buy-YMXXVNFH.js → buy-K2G6XQY2.js} +20 -18
  3. package/dist/{candidate-H7FR4AU5.js → candidate-DJB2NNTG.js} +7 -8
  4. package/dist/{chunk-ZW3B5LWX.js → chunk-2YX6LTCD.js} +5 -5
  5. package/dist/{chunk-4WVKXKDK.js → chunk-6OE2IJMH.js} +29 -238
  6. package/dist/chunk-6OE2IJMH.js.map +1 -0
  7. package/dist/{chunk-ADJYSM45.js → chunk-6ZBZCBR7.js} +27 -13
  8. package/dist/chunk-6ZBZCBR7.js.map +1 -0
  9. package/dist/{chunk-HTDALK7M.js → chunk-B7YB4MMU.js} +15 -12
  10. package/dist/{chunk-HTDALK7M.js.map → chunk-B7YB4MMU.js.map} +1 -1
  11. package/dist/{chunk-NFSOVL3C.js → chunk-BBUYCDSG.js} +12 -3
  12. package/dist/chunk-BBUYCDSG.js.map +1 -0
  13. package/dist/chunk-C3S6725N.js +337 -0
  14. package/dist/chunk-C3S6725N.js.map +1 -0
  15. package/dist/chunk-CYRYVZPN.js +213 -0
  16. package/dist/chunk-CYRYVZPN.js.map +1 -0
  17. package/dist/{chunk-MDDGEGSW.js → chunk-DAJ56EUU.js} +3 -3
  18. package/dist/{chunk-IOPWPMT2.js → chunk-DH6D6QIO.js} +5 -5
  19. package/dist/{chunk-NJF2WENW.js → chunk-DQDGBWWH.js} +4 -2
  20. package/dist/chunk-DQDGBWWH.js.map +1 -0
  21. package/dist/chunk-EDENZN2Q.js +614 -0
  22. package/dist/chunk-EDENZN2Q.js.map +1 -0
  23. package/dist/chunk-GABYDXWL.js +190 -0
  24. package/dist/chunk-GABYDXWL.js.map +1 -0
  25. package/dist/{chunk-LAM66WFJ.js → chunk-GM4RZUVU.js} +6 -8
  26. package/dist/{chunk-LAM66WFJ.js.map → chunk-GM4RZUVU.js.map} +1 -1
  27. package/dist/{chunk-PAUXMRSF.js → chunk-J6CVKC4M.js} +73 -2
  28. package/dist/chunk-J6CVKC4M.js.map +1 -0
  29. package/dist/chunk-L6AV2Q73.js +105 -0
  30. package/dist/chunk-L6AV2Q73.js.map +1 -0
  31. package/dist/{chunk-PYNSGYBE.js → chunk-NVHQCTIC.js} +249 -552
  32. package/dist/chunk-NVHQCTIC.js.map +1 -0
  33. package/dist/{chunk-CVX6JNGD.js → chunk-OTDI5FXG.js} +3 -5
  34. package/dist/{chunk-CVX6JNGD.js.map → chunk-OTDI5FXG.js.map} +1 -1
  35. package/dist/{chunk-3IRDP7TN.js → chunk-P3FBESBB.js} +6 -4
  36. package/dist/{chunk-3IRDP7TN.js.map → chunk-P3FBESBB.js.map} +1 -1
  37. package/dist/{chunk-FU6MCSLG.js → chunk-PCLPVJ3J.js} +16 -78
  38. package/dist/chunk-PCLPVJ3J.js.map +1 -0
  39. package/dist/chunk-QB2NNV6C.js +143 -0
  40. package/dist/chunk-QB2NNV6C.js.map +1 -0
  41. package/dist/{chunk-C444K6MI.js → chunk-RGFBBNGP.js} +42 -17
  42. package/dist/{chunk-C444K6MI.js.map → chunk-RGFBBNGP.js.map} +1 -1
  43. package/dist/{chunk-TXPPMK4L.js → chunk-RGTTACP3.js} +5 -5
  44. package/dist/chunk-SGK2B724.js +67 -0
  45. package/dist/chunk-SGK2B724.js.map +1 -0
  46. package/dist/{chunk-ZDY2KY5X.js → chunk-URSGGRO4.js} +28 -11
  47. package/dist/chunk-URSGGRO4.js.map +1 -0
  48. package/dist/{chunk-5SCU253N.js → chunk-UYP7G3GZ.js} +2 -2
  49. package/dist/{chunk-ZIYVN4CD.js → chunk-VZ3AJCO5.js} +3 -5
  50. package/dist/{chunk-ZIYVN4CD.js.map → chunk-VZ3AJCO5.js.map} +1 -1
  51. package/dist/{chunk-QONTBYQW.js → chunk-WRWCDLVK.js} +4 -6
  52. package/dist/{chunk-QONTBYQW.js.map → chunk-WRWCDLVK.js.map} +1 -1
  53. package/dist/chunk-XBJ3VLWX.js +35 -0
  54. package/dist/chunk-XBJ3VLWX.js.map +1 -0
  55. package/dist/{chunk-RTJLLPFA.js → chunk-XFHZWORF.js} +123 -24
  56. package/dist/chunk-XFHZWORF.js.map +1 -0
  57. package/dist/{chunk-BIKAUVC2.js → chunk-ZA3RFDAV.js} +40 -6
  58. package/dist/chunk-ZA3RFDAV.js.map +1 -0
  59. package/dist/{cli-IW76QTN3.js → cli-KNCYWMAG.js} +237 -25
  60. package/dist/cli-KNCYWMAG.js.map +1 -0
  61. package/dist/{config-VCOS7P5K.js → config-SAQEQRFB.js} +5 -6
  62. package/dist/dist-U4M6QCKE.js +2842 -0
  63. package/dist/dist-U4M6QCKE.js.map +1 -0
  64. package/dist/{doctor-WS65JG3V.js → doctor-FBRQNOUQ.js} +10 -9
  65. package/dist/{publish-DSFWQRUN.js → edit-IZZ2HIMR.js} +20 -18
  66. package/dist/index.js +1 -1
  67. package/dist/{inspect-SFJWUQHO.js → inspect-BFWZ5XOP.js} +17 -16
  68. package/dist/{install-RVPQPCKH.js → install-QXZCHIBT.js} +400 -166
  69. package/dist/install-QXZCHIBT.js.map +1 -0
  70. package/dist/outcome-VXCBEGNC.js +20 -0
  71. package/dist/publish-5NTCRF2V.js +40 -0
  72. package/dist/read-T6OTMU72.js +158 -0
  73. package/dist/read-T6OTMU72.js.map +1 -0
  74. package/dist/{run-OMPKA43G.js → run-5OGX64IY.js} +106 -32
  75. package/dist/{run-OMPKA43G.js.map → run-5OGX64IY.js.map} +1 -1
  76. package/dist/search-LIIWUMWV.js +24 -0
  77. package/dist/{send-3G4C64HJ.js → send-ENE47KQE.js} +7 -7
  78. package/dist/session-HY4QIWHV.js +87 -0
  79. package/dist/session-HY4QIWHV.js.map +1 -0
  80. package/dist/{wallet-PP22LAX7.js → wallet-OCCGEH6H.js} +7 -7
  81. package/dist/{wallet-B7KJS2R5.js → wallet-RBDVNZVR.js} +5 -5
  82. package/dist/wallet-RBDVNZVR.js.map +1 -0
  83. package/docs/agent-permissions.md +255 -0
  84. package/package.json +3 -1
  85. package/skills/tenjin/SKILL.md +57 -13
  86. package/skills/tenjin-publish/SKILL.md +12 -4
  87. package/skills/tenjin-search/SKILL.md +68 -12
  88. package/dist/chunk-2JQ5JSG6.js +0 -68
  89. package/dist/chunk-2JQ5JSG6.js.map +0 -1
  90. package/dist/chunk-4WVKXKDK.js.map +0 -1
  91. package/dist/chunk-ADJYSM45.js.map +0 -1
  92. package/dist/chunk-BIKAUVC2.js.map +0 -1
  93. package/dist/chunk-FU6MCSLG.js.map +0 -1
  94. package/dist/chunk-L4IHCN6B.js +0 -63
  95. package/dist/chunk-L4IHCN6B.js.map +0 -1
  96. package/dist/chunk-NFSOVL3C.js.map +0 -1
  97. package/dist/chunk-NJF2WENW.js.map +0 -1
  98. package/dist/chunk-PAUXMRSF.js.map +0 -1
  99. package/dist/chunk-PYNSGYBE.js.map +0 -1
  100. package/dist/chunk-RTJLLPFA.js.map +0 -1
  101. package/dist/chunk-ZDY2KY5X.js.map +0 -1
  102. package/dist/cli-IW76QTN3.js.map +0 -1
  103. package/dist/install-RVPQPCKH.js.map +0 -1
  104. package/dist/outcome-GNYCSZ7J.js +0 -20
  105. package/dist/search-KOI6Y7P6.js +0 -24
  106. /package/dist/{buy-YMXXVNFH.js.map → buy-K2G6XQY2.js.map} +0 -0
  107. /package/dist/{candidate-H7FR4AU5.js.map → candidate-DJB2NNTG.js.map} +0 -0
  108. /package/dist/{chunk-ZW3B5LWX.js.map → chunk-2YX6LTCD.js.map} +0 -0
  109. /package/dist/{chunk-MDDGEGSW.js.map → chunk-DAJ56EUU.js.map} +0 -0
  110. /package/dist/{chunk-IOPWPMT2.js.map → chunk-DH6D6QIO.js.map} +0 -0
  111. /package/dist/{chunk-TXPPMK4L.js.map → chunk-RGTTACP3.js.map} +0 -0
  112. /package/dist/{chunk-5SCU253N.js.map → chunk-UYP7G3GZ.js.map} +0 -0
  113. /package/dist/{config-VCOS7P5K.js.map → config-SAQEQRFB.js.map} +0 -0
  114. /package/dist/{doctor-WS65JG3V.js.map → doctor-FBRQNOUQ.js.map} +0 -0
  115. /package/dist/{inspect-SFJWUQHO.js.map → edit-IZZ2HIMR.js.map} +0 -0
  116. /package/dist/{outcome-GNYCSZ7J.js.map → inspect-BFWZ5XOP.js.map} +0 -0
  117. /package/dist/{publish-DSFWQRUN.js.map → outcome-VXCBEGNC.js.map} +0 -0
  118. /package/dist/{search-KOI6Y7P6.js.map → publish-5NTCRF2V.js.map} +0 -0
  119. /package/dist/{wallet-B7KJS2R5.js.map → search-LIIWUMWV.js.map} +0 -0
  120. /package/dist/{send-3G4C64HJ.js.map → send-ENE47KQE.js.map} +0 -0
  121. /package/dist/{wallet-PP22LAX7.js.map → wallet-OCCGEH6H.js.map} +0 -0
@@ -1,17 +1,17 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  latestSearch
4
- } from "./chunk-CVX6JNGD.js";
4
+ } from "./chunk-OTDI5FXG.js";
5
5
  import {
6
6
  buildOutcomeItem,
7
7
  postOutcomes
8
- } from "./chunk-3IRDP7TN.js";
8
+ } from "./chunk-P3FBESBB.js";
9
9
  import {
10
10
  resolveContextSettings
11
- } from "./chunk-MDDGEGSW.js";
11
+ } from "./chunk-DAJ56EUU.js";
12
12
  import {
13
13
  CliError
14
- } from "./chunk-PAUXMRSF.js";
14
+ } from "./chunk-J6CVKC4M.js";
15
15
 
16
16
  // src/commands/outcome.ts
17
17
  async function runOutcome(args, ctx, deps = {}) {
@@ -56,4 +56,4 @@ async function resolveSearchId(args, ctx) {
56
56
  export {
57
57
  runOutcome
58
58
  };
59
- //# sourceMappingURL=chunk-TXPPMK4L.js.map
59
+ //# sourceMappingURL=chunk-RGTTACP3.js.map
@@ -0,0 +1,67 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/markdown.ts
4
+ function headingOutline(bodyMd) {
5
+ const headings = [];
6
+ let inFence = false;
7
+ for (const line of bodyMd.split(/\r?\n/)) {
8
+ if (/^\s*(```|~~~)/.test(line)) {
9
+ inFence = !inFence;
10
+ continue;
11
+ }
12
+ if (inFence) continue;
13
+ const m = /^(#{1,6})\s+(.*\S)\s*$/.exec(line);
14
+ if (m && m[1] !== void 0 && m[2] !== void 0) {
15
+ headings.push({ level: m[1].length, text: m[2] });
16
+ }
17
+ }
18
+ return headings;
19
+ }
20
+ function estimateTokens(text) {
21
+ const words = text.split(/\s+/).filter((w) => w.length > 0).length;
22
+ return Math.ceil(words * 1.33);
23
+ }
24
+ function splitSections(bodyMd) {
25
+ const sections = [];
26
+ let heading = null;
27
+ let level = 0;
28
+ let lines = [];
29
+ let inFence = false;
30
+ const push = () => {
31
+ const body = lines.join("\n").trim();
32
+ if (heading === null && body.length === 0) return;
33
+ sections.push({ heading, level, body, estimatedTokens: estimateTokens(body) });
34
+ };
35
+ for (const line of bodyMd.split(/\r?\n/)) {
36
+ if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
37
+ const m = inFence ? null : /^(#{1,6})\s+(.*\S)\s*$/.exec(line);
38
+ if (m && m[1] !== void 0 && m[2] !== void 0) {
39
+ push();
40
+ heading = m[2].trim();
41
+ level = m[1].length;
42
+ lines = [];
43
+ } else {
44
+ lines.push(line);
45
+ }
46
+ }
47
+ push();
48
+ return sections;
49
+ }
50
+ function selectSections(sections, budgetTokens) {
51
+ const selected = [];
52
+ let spent = 0;
53
+ for (const section of sections) {
54
+ if (selected.length > 0 && spent + section.estimatedTokens > budgetTokens) break;
55
+ selected.push(section);
56
+ spent += section.estimatedTokens;
57
+ if (spent >= budgetTokens) break;
58
+ }
59
+ return selected;
60
+ }
61
+
62
+ export {
63
+ headingOutline,
64
+ splitSections,
65
+ selectSections
66
+ };
67
+ //# sourceMappingURL=chunk-SGK2B724.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/markdown.ts"],"sourcesContent":["/**\n * Deterministic markdown structure helpers for delivery output: the heading\n * outline that replaces the body on stdout, and the `--sections` budgeted\n * selection. No model calls, no scoring; identical input always yields\n * identical output. Split from library.ts so filesystem delivery and text\n * shaping stay separate concerns.\n */\n\nexport interface Heading {\n level: number;\n text: string;\n}\n\n/**\n * Deterministic ATX-heading outline for the stdout summary, never the body, so\n * agent transcripts stay small (spec 10). Skips fenced code blocks so a `#`\n * comment inside a code sample is not mistaken for a heading.\n */\nexport function headingOutline(bodyMd: string): Heading[] {\n const headings: Heading[] = [];\n let inFence = false;\n for (const line of bodyMd.split(/\\r?\\n/)) {\n if (/^\\s*(```|~~~)/.test(line)) {\n inFence = !inFence;\n continue;\n }\n if (inFence) continue;\n const m = /^(#{1,6})\\s+(.*\\S)\\s*$/.exec(line);\n if (m && m[1] !== undefined && m[2] !== undefined) {\n headings.push({ level: m[1].length, text: m[2] });\n }\n }\n return headings;\n}\n\nexport interface MarkdownSection {\n /** Heading text without the leading #s; null for preamble before any heading. */\n heading: string | null;\n level: number;\n body: string;\n estimatedTokens: number;\n}\n\n/** The server's own heuristic: ceil(words x 1.33). A display hint, never a boundary. */\nexport function estimateTokens(text: string): number {\n const words = text.split(/\\s+/).filter((w) => w.length > 0).length;\n return Math.ceil(words * 1.33);\n}\n\n/**\n * Deterministic heading-split of the body for `--sections` delivery: no model\n * calls, no scoring; the same input always splits identically. Fenced code\n * blocks are ignored for heading detection, like headingOutline.\n */\nexport function splitSections(bodyMd: string): MarkdownSection[] {\n const sections: MarkdownSection[] = [];\n let heading: string | null = null;\n let level = 0;\n let lines: string[] = [];\n let inFence = false;\n\n const push = (): void => {\n const body = lines.join('\\n').trim();\n if (heading === null && body.length === 0) return;\n sections.push({ heading, level, body, estimatedTokens: estimateTokens(body) });\n };\n\n for (const line of bodyMd.split(/\\r?\\n/)) {\n if (/^\\s*(```|~~~)/.test(line)) inFence = !inFence;\n const m = inFence ? null : /^(#{1,6})\\s+(.*\\S)\\s*$/.exec(line);\n if (m && m[1] !== undefined && m[2] !== undefined) {\n push();\n heading = m[2].trim();\n level = m[1].length;\n lines = [];\n } else {\n lines.push(line);\n }\n }\n push();\n return sections;\n}\n\n/**\n * Sections in document order until the budget is spent. The first section always\n * ships even when it alone exceeds the budget, so a tiny budget still returns\n * something rather than an empty selection.\n */\nexport function selectSections(\n sections: MarkdownSection[],\n budgetTokens: number,\n): MarkdownSection[] {\n const selected: MarkdownSection[] = [];\n let spent = 0;\n for (const section of sections) {\n if (selected.length > 0 && spent + section.estimatedTokens > budgetTokens) break;\n selected.push(section);\n spent += section.estimatedTokens;\n if (spent >= budgetTokens) break;\n }\n return selected;\n}\n"],"mappings":";;;AAkBO,SAAS,eAAe,QAA2B;AACxD,QAAM,WAAsB,CAAC;AAC7B,MAAI,UAAU;AACd,aAAW,QAAQ,OAAO,MAAM,OAAO,GAAG;AACxC,QAAI,gBAAgB,KAAK,IAAI,GAAG;AAC9B,gBAAU,CAAC;AACX;AAAA,IACF;AACA,QAAI,QAAS;AACb,UAAM,IAAI,yBAAyB,KAAK,IAAI;AAC5C,QAAI,KAAK,EAAE,CAAC,MAAM,UAAa,EAAE,CAAC,MAAM,QAAW;AACjD,eAAS,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,QAAQ,MAAM,EAAE,CAAC,EAAE,CAAC;AAAA,IAClD;AAAA,EACF;AACA,SAAO;AACT;AAWO,SAAS,eAAe,MAAsB;AACnD,QAAM,QAAQ,KAAK,MAAM,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE;AAC5D,SAAO,KAAK,KAAK,QAAQ,IAAI;AAC/B;AAOO,SAAS,cAAc,QAAmC;AAC/D,QAAM,WAA8B,CAAC;AACrC,MAAI,UAAyB;AAC7B,MAAI,QAAQ;AACZ,MAAI,QAAkB,CAAC;AACvB,MAAI,UAAU;AAEd,QAAM,OAAO,MAAY;AACvB,UAAM,OAAO,MAAM,KAAK,IAAI,EAAE,KAAK;AACnC,QAAI,YAAY,QAAQ,KAAK,WAAW,EAAG;AAC3C,aAAS,KAAK,EAAE,SAAS,OAAO,MAAM,iBAAiB,eAAe,IAAI,EAAE,CAAC;AAAA,EAC/E;AAEA,aAAW,QAAQ,OAAO,MAAM,OAAO,GAAG;AACxC,QAAI,gBAAgB,KAAK,IAAI,EAAG,WAAU,CAAC;AAC3C,UAAM,IAAI,UAAU,OAAO,yBAAyB,KAAK,IAAI;AAC7D,QAAI,KAAK,EAAE,CAAC,MAAM,UAAa,EAAE,CAAC,MAAM,QAAW;AACjD,WAAK;AACL,gBAAU,EAAE,CAAC,EAAE,KAAK;AACpB,cAAQ,EAAE,CAAC,EAAE;AACb,cAAQ,CAAC;AAAA,IACX,OAAO;AACL,YAAM,KAAK,IAAI;AAAA,IACjB;AAAA,EACF;AACA,OAAK;AACL,SAAO;AACT;AAOO,SAAS,eACd,UACA,cACmB;AACnB,QAAM,WAA8B,CAAC;AACrC,MAAI,QAAQ;AACZ,aAAW,WAAW,UAAU;AAC9B,QAAI,SAAS,SAAS,KAAK,QAAQ,QAAQ,kBAAkB,aAAc;AAC3E,aAAS,KAAK,OAAO;AACrB,aAAS,QAAQ;AACjB,QAAI,SAAS,aAAc;AAAA,EAC7B;AACA,SAAO;AACT;","names":[]}
@@ -1,9 +1,18 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  package_default
4
- } from "./chunk-NJF2WENW.js";
4
+ } from "./chunk-DQDGBWWH.js";
5
5
 
6
6
  // src/lib/http.ts
7
+ var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
8
+ "sign-in-with-x",
9
+ "payment-signature",
10
+ "x-payment",
11
+ "tenjin-session-delegation"
12
+ ]);
13
+ function carriesSignedMaterial(headers) {
14
+ return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));
15
+ }
7
16
  async function fetchJson(url, opts) {
8
17
  const doFetch = opts.fetchImpl ?? fetch;
9
18
  const controller = new AbortController();
@@ -86,19 +95,33 @@ async function httpRequest(url, opts) {
86
95
  body = JSON.stringify(opts.jsonBody);
87
96
  headers["content-type"] = "application/json";
88
97
  }
89
- if (opts.method === "POST" || body !== void 0) headers["accept"] ??= "application/json";
98
+ if (opts.method === "POST" || opts.method === "PUT" || body !== void 0) {
99
+ headers["accept"] ??= "application/json";
100
+ }
101
+ const signed = carriesSignedMaterial(headers);
102
+ const pinned = signed || opts.blockRedirects === true;
90
103
  let res;
91
104
  try {
92
105
  res = await doFetch(url, {
93
106
  method: opts.method ?? "GET",
94
107
  headers,
95
108
  body,
96
- signal: controller.signal
109
+ signal: controller.signal,
110
+ ...pinned ? { redirect: "manual" } : {}
97
111
  });
98
112
  } catch (err) {
99
113
  return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
100
114
  }
101
115
  const requestId = res.headers.get("x-request-id") ?? void 0;
116
+ if (pinned && res.status >= 300 && res.status < 400) {
117
+ return {
118
+ ok: false,
119
+ kind: "blocked-redirect",
120
+ status: res.status,
121
+ ...requestId !== void 0 ? { requestId } : {},
122
+ message: signed ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; refusing to follow it, because the signature is bound to the configured origin.` : `Request to ${url} was redirected (${res.status}); refusing to follow it, because the response must come from the configured origin.`
123
+ };
124
+ }
102
125
  let text;
103
126
  try {
104
127
  text = await res.text();
@@ -138,15 +161,9 @@ function errorMessage(err) {
138
161
  // src/lib/client-meta.ts
139
162
  var CLIENT_HEADER = `tenjin-cli/${package_default.version}`;
140
163
 
141
- // src/lib/url.ts
142
- function trimSlash(url) {
143
- return url.replace(/\/+$/, "");
144
- }
145
-
146
164
  export {
147
165
  fetchJson,
148
166
  httpRequest,
149
- CLIENT_HEADER,
150
- trimSlash
167
+ CLIENT_HEADER
151
168
  };
152
- //# sourceMappingURL=chunk-ZDY2KY5X.js.map
169
+ //# sourceMappingURL=chunk-URSGGRO4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/http.ts","../src/lib/client-meta.ts"],"sourcesContent":["import { CliError } from './errors';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers (doctor sends the X-Tenjin-Client label). */\n headers?: Record<string, string>;\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect';\n status?: number;\n requestId?: string;\n message: string;\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n try {\n res = await doFetch(url, {\n signal: controller.signal,\n ...(opts.headers !== undefined ? { headers: opts.headers } : {}),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n fetchImpl?: typeof fetch;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal transport.\n */\n blockRedirects?: boolean;\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n const headers: Record<string, string> = { ...(opts.headers ?? {}) };\n let body: string | undefined;\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n headers['content-type'] = 'application/json';\n }\n if (opts.method === 'POST' || opts.method === 'PUT' || body !== undefined) {\n headers['accept'] ??= 'application/json';\n }\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n const pinned = signed || opts.blockRedirects === true;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n try {\n text = await res.text();\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import pkg from '../../package.json';\n\n/**\n * The `X-Tenjin-Client` value on every B2 request (spec 09 §purchase-attribution):\n * the server classifies views/payments by this label, so a CLI search-flow\n * purchase is never mixed with a web checkout. Format `tenjin-cli/<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AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,IAAI;AAAA,MACZ,QAAQ,CAAC,SAAS,IAAI,QAAQ,IAAI,IAAI,KAAK;AAAA,MAC3C;AAAA,MACA,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,IACjD;AAAA,EACF,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AA8BA,SAAS,aAAa,KAAsB;AAC1C,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;;ACjUO,IAAM,gBAAgB,cAAc,gBAAI,OAAO;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  CliError,
4
4
  configPath,
5
5
  external_exports
6
- } from "./chunk-PAUXMRSF.js";
6
+ } from "./chunk-J6CVKC4M.js";
7
7
 
8
8
  // src/lib/skills-source.ts
9
9
  import { existsSync } from "fs";
@@ -409,4 +409,4 @@ export {
409
409
  toMoney,
410
410
  formatUsdDisplay
411
411
  };
412
- //# sourceMappingURL=chunk-5SCU253N.js.map
412
+ //# sourceMappingURL=chunk-UYP7G3GZ.js.map
@@ -7,11 +7,9 @@ import {
7
7
  hasCode
8
8
  } from "./chunk-2I4QTOLB.js";
9
9
  import {
10
+ external_exports,
10
11
  writeFileAtomicExclusive
11
- } from "./chunk-2JQ5JSG6.js";
12
- import {
13
- external_exports
14
- } from "./chunk-PAUXMRSF.js";
12
+ } from "./chunk-J6CVKC4M.js";
15
13
 
16
14
  // src/lib/candidate-store.ts
17
15
  import { mkdir, readFile, readdir, rm, stat } from "fs/promises";
@@ -123,4 +121,4 @@ export {
123
121
  listCandidates,
124
122
  dropCandidate
125
123
  };
126
- //# sourceMappingURL=chunk-ZIYVN4CD.js.map
124
+ //# sourceMappingURL=chunk-VZ3AJCO5.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/candidate-store.ts"],"sourcesContent":["import { mkdir, readFile, readdir, rm, stat } from 'node:fs/promises';\nimport type { Dirent } from 'node:fs';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { writeFileAtomicExclusive } from './atomic-json';\nimport { hasCode } from './errno';\nimport { newId, UUID_RE } from './ids';\n\n/**\n * The D40 candidate store: publish drafts parked locally that never touch the\n * network and never upload — only a later `tenjin publish --candidate <id>`\n * sends one, under the D38 consent scan. Each candidate is its OWN directory\n * `~/.tenjin/candidates/<id>/` holding the draft markdown plus a meta.json.\n *\n * Custody mirrors the wallet key discipline: the candidates tree is 0700 and\n * every file 0600, written create-once through writeFileAtomicExclusive so a\n * reader sees a complete file or none and a uuid collision is loud, never a\n * silent overwrite. Unlike search-store's single shared ledger, there is no shared\n * mutable file here — a fresh uuid per add means two concurrent adds land in two\n * distinct dirs and cannot contend — so no cross-process lock is needed. The\n * meta.json is written LAST and atomically, making it the commit point: `list`\n * skips any dir whose meta is absent or unreadable, so a torn or half-written\n * add reads as not-yet-there rather than a broken candidate, the same\n * best-effort posture loadSearches takes on a corrupt store. A crash mid-add is\n * cleaned up eagerly (the dir is removed on any write failure), and `drop` can\n * still remove a metaless orphan by id so a leaked draft is never stranded.\n */\n\nconst DRAFT_FILE = 'draft.md';\nconst META_FILE = 'meta.json';\n\nconst CandidateMetaSchema = z.object({\n schemaVersion: z.literal(1),\n searchId: z.string(),\n question: z.string().optional(),\n // Fixed-width UTC ISO-8601 (a trailing Z, never an offset): listCandidates\n // sorts newest-first lexicographically on this string, which is only a valid\n // proxy for chronological order when every value is same-zone UTC. z.iso\n // .datetime() rejects offsets and non-datetime strings, pinning that invariant.\n created: z.iso.datetime(),\n /** The repo root the add ran in, or the cwd when not in a repo. */\n sourceProject: z.string(),\n});\nexport type CandidateMeta = z.infer<typeof CandidateMetaSchema>;\n\nexport interface CandidateRecord {\n id: string;\n meta: CandidateMeta;\n /** Absolute path of the candidate directory. */\n dir: string;\n /** Absolute path of the draft markdown inside the directory. */\n draftPath: string;\n}\n\nexport interface CreateCandidateInput {\n /** The draft markdown, copied verbatim into the candidate. */\n draft: string;\n searchId: string;\n question?: string;\n /** ISO-8601 creation time; the command supplies it via its clock seam. */\n created: string;\n sourceProject: string;\n}\n\nfunction candidatesDir(dataDir: string): string {\n return join(dataDir, 'candidates');\n}\n\nfunction candidateDir(dataDir: string, id: string): string {\n return join(candidatesDir(dataDir), id);\n}\n\n/** Park a draft as a new candidate and return the created record. Both files are\n * written create-once (no-clobber, fsynced) at a fresh uuid path, meta.json\n * last, so the candidate is either fully present to `list`/`read` or absent,\n * never half-there. */\nexport async function createCandidate(\n dataDir: string,\n input: CreateCandidateInput,\n): Promise<CandidateRecord> {\n const id = newId();\n const dir = candidateDir(dataDir, id);\n await mkdir(dir, { recursive: true, mode: 0o700 });\n\n const draftPath = join(dir, DRAFT_FILE);\n const meta: CandidateMeta = {\n schemaVersion: 1,\n searchId: input.searchId,\n ...(input.question !== undefined ? { question: input.question } : {}),\n created: input.created,\n sourceProject: input.sourceProject,\n };\n try {\n // Exclusive (create-or-EEXIST, fsynced) so a uuid collision is loud, not a\n // silent overwrite of an existing candidate, and the crash-durable commit of\n // meta.json is the last, atomic step.\n await writeFileAtomicExclusive(draftPath, input.draft, { mode: 0o600, dirMode: 0o700 });\n await writeFileAtomicExclusive(join(dir, META_FILE), `${JSON.stringify(meta, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n // An EEXIST means something already lived at this fresh-uuid path (a real\n // collision, astronomically unlikely): surface it loudly and NEVER delete\n // what was already there. Any other failure is a partial write of our own\n // fresh dir — remove it so a crash mid-add can't strand a hidden dir holding\n // the (secrets-adjacent) draft that `list` skips and no one can name to `drop`.\n if (!hasCode(err, 'EEXIST')) {\n await rm(dir, { recursive: true, force: true }).catch(() => undefined);\n }\n throw err;\n }\n\n return { id, meta, dir, draftPath };\n}\n\n/** One candidate by id, or null when it is unknown (or the id is malformed, so a\n * stray argument can never traverse out of the store). */\nexport async function readCandidate(dataDir: string, id: string): Promise<CandidateRecord | null> {\n if (!UUID_RE.test(id)) return null;\n const dir = candidateDir(dataDir, id);\n const meta = await readMeta(dir);\n if (meta === null) return null;\n return { id, meta, dir, draftPath: join(dir, DRAFT_FILE) };\n}\n\n/** Every pending candidate, newest first by `created` (no auto-expiry — stale\n * candidates stay visible, D40). Tie-broken on id so the order is total. */\nexport async function listCandidates(dataDir: string): Promise<CandidateRecord[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(candidatesDir(dataDir), { withFileTypes: true });\n } catch {\n return [];\n }\n const records: CandidateRecord[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory() || !UUID_RE.test(entry.name)) continue;\n const record = await readCandidate(dataDir, entry.name);\n if (record !== null) records.push(record);\n }\n records.sort((a, b) => {\n if (a.meta.created !== b.meta.created) return a.meta.created < b.meta.created ? 1 : -1;\n return a.id < b.id ? 1 : -1;\n });\n return records;\n}\n\n/** Discard one candidate by id. Returns false when the id is malformed or no\n * such dir exists, so the command can surface a clean not-found; nothing is\n * ever auto-deleted. Removes the dir even when its meta is absent or corrupt,\n * so a crash-orphaned candidate can still be cleaned up by id (the id is\n * UUID-gated first, so a stray argument can never target a path outside the\n * store). */\nexport async function dropCandidate(dataDir: string, id: string): Promise<boolean> {\n if (!UUID_RE.test(id)) return false;\n const dir = candidateDir(dataDir, id);\n try {\n if (!(await stat(dir)).isDirectory()) return false;\n } catch {\n return false; // no such candidate\n }\n await rm(dir, { recursive: true, force: true });\n return true;\n}\n\n/** Read and validate a candidate's meta.json; null on any absence/corruption. */\nasync function readMeta(dir: string): Promise<CandidateMeta | null> {\n let raw: string;\n try {\n raw = await readFile(join(dir, META_FILE), 'utf8');\n } catch {\n return null;\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return null;\n }\n const parsed = CandidateMetaSchema.safeParse(json);\n return parsed.success ? parsed.data : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,SAAS,IAAI,YAAY;AAEnD,SAAS,YAAY;AA0BrB,IAAM,aAAa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,SAAS,KAA4C;AAClE,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,KAAK,KAAK,SAAS,GAAG,MAAM;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,SAAS,oBAAoB,UAAU,IAAI;AACjD,SAAO,OAAO,UAAU,OAAO,OAAO;AACxC;","names":[]}
1
+ {"version":3,"sources":["../src/lib/candidate-store.ts"],"sourcesContent":["import { mkdir, readFile, readdir, rm, stat } from 'node:fs/promises';\nimport type { Dirent } from 'node:fs';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { writeFileAtomicExclusive } from './atomic-json';\nimport { hasCode } from './errno';\nimport { newId, UUID_RE } from './ids';\n\n/**\n * The D40 candidate store: publish drafts parked locally that never touch the\n * network and never upload — only a later `tenjin publish --candidate <id>`\n * sends one, under the D38 consent scan. Each candidate is its OWN directory\n * `~/.tenjin/candidates/<id>/` holding the draft markdown plus a meta.json.\n *\n * Custody mirrors the wallet key discipline: the candidates tree is 0700 and\n * every file 0600, written create-once through writeFileAtomicExclusive so a\n * reader sees a complete file or none and a uuid collision is loud, never a\n * silent overwrite. Unlike search-store's single shared ledger, there is no shared\n * mutable file here — a fresh uuid per add means two concurrent adds land in two\n * distinct dirs and cannot contend — so no cross-process lock is needed. The\n * meta.json is written LAST and atomically, making it the commit point: `list`\n * skips any dir whose meta is absent or unreadable, so a torn or half-written\n * add reads as not-yet-there rather than a broken candidate, the same\n * best-effort posture loadSearches takes on a corrupt store. A crash mid-add is\n * cleaned up eagerly (the dir is removed on any write failure), and `drop` can\n * still remove a metaless orphan by id so a leaked draft is never stranded.\n */\n\nconst DRAFT_FILE = 'draft.md';\nconst META_FILE = 'meta.json';\n\nconst CandidateMetaSchema = z.object({\n schemaVersion: z.literal(1),\n searchId: z.string(),\n question: z.string().optional(),\n // Fixed-width UTC ISO-8601 (a trailing Z, never an offset): listCandidates\n // sorts newest-first lexicographically on this string, which is only a valid\n // proxy for chronological order when every value is same-zone UTC. z.iso\n // .datetime() rejects offsets and non-datetime strings, pinning that invariant.\n created: z.iso.datetime(),\n /** The repo root the add ran in, or the cwd when not in a repo. */\n sourceProject: z.string(),\n});\nexport type CandidateMeta = z.infer<typeof CandidateMetaSchema>;\n\nexport interface CandidateRecord {\n id: string;\n meta: CandidateMeta;\n /** Absolute path of the candidate directory. */\n dir: string;\n /** Absolute path of the draft markdown inside the directory. */\n draftPath: string;\n}\n\nexport interface CreateCandidateInput {\n /** The draft markdown, copied verbatim into the candidate. */\n draft: string;\n searchId: string;\n question?: string;\n /** ISO-8601 creation time; the command supplies it via its clock seam. */\n created: string;\n sourceProject: string;\n}\n\nfunction candidatesDir(dataDir: string): string {\n return join(dataDir, 'candidates');\n}\n\nfunction candidateDir(dataDir: string, id: string): string {\n return join(candidatesDir(dataDir), id);\n}\n\n/** Park a draft as a new candidate and return the created record. Both files are\n * written create-once (no-clobber, fsynced) at a fresh uuid path, meta.json\n * last, so the candidate is either fully present to `list`/`read` or absent,\n * never half-there. */\nexport async function createCandidate(\n dataDir: string,\n input: CreateCandidateInput,\n): Promise<CandidateRecord> {\n const id = newId();\n const dir = candidateDir(dataDir, id);\n await mkdir(dir, { recursive: true, mode: 0o700 });\n\n const draftPath = join(dir, DRAFT_FILE);\n const meta: CandidateMeta = {\n schemaVersion: 1,\n searchId: input.searchId,\n ...(input.question !== undefined ? { question: input.question } : {}),\n created: input.created,\n sourceProject: input.sourceProject,\n };\n try {\n // Exclusive (create-or-EEXIST, fsynced) so a uuid collision is loud, not a\n // silent overwrite of an existing candidate, and the crash-durable commit of\n // meta.json is the last, atomic step.\n await writeFileAtomicExclusive(draftPath, input.draft, { mode: 0o600, dirMode: 0o700 });\n await writeFileAtomicExclusive(join(dir, META_FILE), `${JSON.stringify(meta, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n // An EEXIST means something already lived at this fresh-uuid path (a real\n // collision, astronomically unlikely): surface it loudly and NEVER delete\n // what was already there. Any other failure is a partial write of our own\n // fresh dir — remove it so a crash mid-add can't strand a hidden dir holding\n // the (secrets-adjacent) draft that `list` skips and no one can name to `drop`.\n if (!hasCode(err, 'EEXIST')) {\n await rm(dir, { recursive: true, force: true }).catch(() => undefined);\n }\n throw err;\n }\n\n return { id, meta, dir, draftPath };\n}\n\n/** One candidate by id, or null when it is unknown (or the id is malformed, so a\n * stray argument can never traverse out of the store). */\nexport async function readCandidate(dataDir: string, id: string): Promise<CandidateRecord | null> {\n if (!UUID_RE.test(id)) return null;\n const dir = candidateDir(dataDir, id);\n const meta = await readMeta(dir);\n if (meta === null) return null;\n return { id, meta, dir, draftPath: join(dir, DRAFT_FILE) };\n}\n\n/** Every pending candidate, newest first by `created` (no auto-expiry — stale\n * candidates stay visible, D40). Tie-broken on id so the order is total. */\nexport async function listCandidates(dataDir: string): Promise<CandidateRecord[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(candidatesDir(dataDir), { withFileTypes: true });\n } catch {\n return [];\n }\n const records: CandidateRecord[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory() || !UUID_RE.test(entry.name)) continue;\n const record = await readCandidate(dataDir, entry.name);\n if (record !== null) records.push(record);\n }\n records.sort((a, b) => {\n if (a.meta.created !== b.meta.created) return a.meta.created < b.meta.created ? 1 : -1;\n return a.id < b.id ? 1 : -1;\n });\n return records;\n}\n\n/** Discard one candidate by id. Returns false when the id is malformed or no\n * such dir exists, so the command can surface a clean not-found; nothing is\n * ever auto-deleted. Removes the dir even when its meta is absent or corrupt,\n * so a crash-orphaned candidate can still be cleaned up by id (the id is\n * UUID-gated first, so a stray argument can never target a path outside the\n * store). */\nexport async function dropCandidate(dataDir: string, id: string): Promise<boolean> {\n if (!UUID_RE.test(id)) return false;\n const dir = candidateDir(dataDir, id);\n try {\n if (!(await stat(dir)).isDirectory()) return false;\n } catch {\n return false; // no such candidate\n }\n await rm(dir, { recursive: true, force: true });\n return true;\n}\n\n/** Read and validate a candidate's meta.json; null on any absence/corruption. */\nasync function readMeta(dir: string): Promise<CandidateMeta | null> {\n let raw: string;\n try {\n raw = await readFile(join(dir, META_FILE), 'utf8');\n } catch {\n return null;\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return null;\n }\n const parsed = CandidateMetaSchema.safeParse(json);\n return parsed.success ? parsed.data : null;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,SAAS,IAAI,YAAY;AAEnD,SAAS,YAAY;AA0BrB,IAAM,aAAa;AACnB,IAAM,YAAY;AAElB,IAAM,sBAAsB,iBAAE,OAAO;AAAA,EACnC,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,UAAU,iBAAE,OAAO;AAAA,EACnB,UAAU,iBAAE,OAAO,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9B,SAAS,iBAAE,IAAI,SAAS;AAAA;AAAA,EAExB,eAAe,iBAAE,OAAO;AAC1B,CAAC;AAsBD,SAAS,cAAc,SAAyB;AAC9C,SAAO,KAAK,SAAS,YAAY;AACnC;AAEA,SAAS,aAAa,SAAiB,IAAoB;AACzD,SAAO,KAAK,cAAc,OAAO,GAAG,EAAE;AACxC;AAMA,eAAsB,gBACpB,SACA,OAC0B;AAC1B,QAAM,KAAK,MAAM;AACjB,QAAM,MAAM,aAAa,SAAS,EAAE;AACpC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAEjD,QAAM,YAAY,KAAK,KAAK,UAAU;AACtC,QAAM,OAAsB;AAAA,IAC1B,eAAe;AAAA,IACf,UAAU,MAAM;AAAA,IAChB,GAAI,MAAM,aAAa,SAAY,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;AAAA,IACnE,SAAS,MAAM;AAAA,IACf,eAAe,MAAM;AAAA,EACvB;AACA,MAAI;AAIF,UAAM,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I;AACpF,WAAO,EAAE,KAAK,EAAE,KAAK,IAAI;AAAA,EAC3B,CAAC;AACD,SAAO;AACT;AAQA,eAAsB,cAAc,SAAiB,IAA8B;AACjF,MAAI,CAAC,QAAQ,KAAK,EAAE,EAAG,QAAO;AAC9B,QAAM,MAAM,aAAa,SAAS,EAAE;AACpC,MAAI;AACF,QAAI,EAAE,MAAM,KAAK,GAAG,GAAG,YAAY,EAAG,QAAO;AAAA,EAC/C,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,GAAG,KAAK,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAC9C,SAAO;AACT;AAGA,eAAe,SAAS,KAA4C;AAClE,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,KAAK,KAAK,SAAS,GAAG,MAAM;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,SAAS,oBAAoB,UAAU,IAAI;AACjD,SAAO,OAAO,UAAU,OAAO,OAAO;AACxC;","names":[]}
@@ -2,14 +2,12 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  hasCode
4
4
  } from "./chunk-2I4QTOLB.js";
5
- import {
6
- writeFileAtomicExclusive
7
- } from "./chunk-2JQ5JSG6.js";
8
5
  import {
9
6
  CliError,
10
7
  external_exports,
11
- walletPath
12
- } from "./chunk-PAUXMRSF.js";
8
+ walletPath,
9
+ writeFileAtomicExclusive
10
+ } from "./chunk-J6CVKC4M.js";
13
11
 
14
12
  // src/lib/wallet/store.ts
15
13
  import { readFile, stat } from "fs/promises";
@@ -126,4 +124,4 @@ export {
126
124
  walletExistsError,
127
125
  writeWalletRecord
128
126
  };
129
- //# sourceMappingURL=chunk-QONTBYQW.js.map
127
+ //# sourceMappingURL=chunk-WRWCDLVK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/wallet/store.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { writeFileAtomicExclusive } from '../atomic-json';\nimport { hasCode } from '../errno';\nimport { walletPath } from '../paths';\n\n/** A 0x-prefixed 32-byte hex private key (case-insensitive). */\nexport const PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The at-rest shape of a Keystore v3 document (Web3 Secret Storage). Validated\n * structurally on read so an obviously-corrupt keystore fails as\n * WALLET_INVALID_KEY before we ever ask for a passphrase; the real integrity\n * check is the keystore's own MAC, verified by ox at decrypt time. `kdfparams`\n * stays an open object because scrypt and pbkdf2 carry different fields and only\n * ox needs to interpret them.\n */\nconst KeystoreV3Schema = z.object({\n crypto: z.object({\n cipher: z.literal('aes-128-ctr'),\n ciphertext: z.string(),\n cipherparams: z.object({ iv: z.string() }),\n kdf: z.enum(['scrypt', 'pbkdf2']),\n kdfparams: z.record(z.string(), z.unknown()),\n mac: z.string(),\n }),\n id: z.string(),\n version: z.literal(3),\n});\n\n/**\n * The persisted wallet record (schema v2). The private key is NEVER stored in\n * cleartext: `keystore` is a Keystore v3 document (scrypt + AES-128-CTR) and the\n * key is recovered only by decrypting it with the wallet passphrase. `address`\n * stays top-level in cleartext ON PURPOSE so `show`/`balance`/`doctor` keep\n * working without a passphrase; only signing decrypts. The `provider`\n * discriminator keeps the schema from implying every future wallet embeds a\n * keystore. Validated on read (a corrupt file is WALLET_INVALID_KEY, never a\n * silent partial parse).\n */\nexport const WalletRecordSchema = z.object({\n schemaVersion: z.literal(2),\n provider: z.literal('local'),\n address: z.string().regex(ADDRESS_RE, 'expected a 0x-prefixed 20-byte address'),\n keystore: KeystoreV3Schema,\n createdAt: z.string(),\n});\nexport type WalletRecord = Omit<z.infer<typeof WalletRecordSchema>, 'keystore'> & {\n keystore: Keystore.Keystore;\n};\n\nexport async function walletFileExists(dir: string): Promise<boolean> {\n return (await walletFileMode(dir)) !== null;\n}\n\n/** File permission bits (`mode & 0o777`), or null when the wallet file is absent. */\nexport async function walletFileMode(dir: string): Promise<number | null> {\n try {\n return (await stat(walletPath(dir))).mode & 0o777;\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n}\n\n/** Read + validate the wallet record; null when absent, WALLET_INVALID_KEY when corrupt. */\nexport async function readWalletRecord(dir: string): Promise<WalletRecord | null> {\n const path = walletPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return null;\n throw new CliError('WALLET_INVALID_KEY', `Could not read the wallet file at ${path}.`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('WALLET_INVALID_KEY', `The wallet file at ${path} is not valid JSON.`, {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n cause: err,\n });\n }\n // A pre-encryption record (schema v1 stored the raw key). There is no in-place\n // migration: the old key must be swept and a fresh encrypted wallet created.\n if (isPreEncryptionRecord(json)) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} predates encrypted storage.`,\n {\n fix: `Move ${path} aside and run \\`tenjin wallet create\\`; sweep any funds from the old address first.`,\n },\n );\n }\n const parsed = WalletRecordSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} is not a valid wallet record.`,\n {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data as WalletRecord;\n}\n\n/**\n * The one WALLET_EXISTS error, shared by the create pre-check and the exclusive\n * write's race loser so the two surfaces can never drift apart.\n */\nexport function walletExistsError(dir: string, cause?: unknown): CliError {\n const path = walletPath(dir);\n return new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Run \\`tenjin wallet create --replace\\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable — never delete the credential-store entry, or the wallet's funds are stranded.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n/**\n * Persist a validated record at 0600 in a 0700 dir, NO-CLOBBER. The exclusive\n * write — not an earlier existence check — is the authority: two concurrent\n * `create` runs can both pass a pre-check, but only one can win the atomic\n * commit; the loser surfaces as WALLET_EXISTS instead of silently overwriting\n * (and losing) a non-recoverable key.\n */\nexport async function writeWalletRecord(dir: string, record: WalletRecord): Promise<void> {\n const validated = WalletRecordSchema.parse(record);\n const path = walletPath(dir);\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n if (hasCode(err, 'EEXIST')) throw walletExistsError(dir, err);\n throw err;\n }\n}\n\n/** A cleartext-key record from before encrypted storage: schema v1 or a bare `privateKey`. */\nfunction isPreEncryptionRecord(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) return false;\n const rec = json as Record<string, unknown>;\n return rec.schemaVersion === 1 || 'privateKey' in rec;\n}\n\nfunction isNotFound(err: unknown): boolean {\n return hasCode(err, 'ENOENT');\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AASxB,IAAM,iBAAiB;AAC9B,IAAM,aAAa;AAUnB,IAAM,mBAAmB,iBAAE,OAAO;AAAA,EAChC,QAAQ,iBAAE,OAAO;AAAA,IACf,QAAQ,iBAAE,QAAQ,aAAa;AAAA,IAC/B,YAAY,iBAAE,OAAO;AAAA,IACrB,cAAc,iBAAE,OAAO,EAAE,IAAI,iBAAE,OAAO,EAAE,CAAC;AAAA,IACzC,KAAK,iBAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;AAAA,IAChC,WAAW,iBAAE,OAAO,iBAAE,OA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AA,MACA,sBAAsB,IAAI;AAAA,MAC1B;AAAA,QACE,KAAK,QAAQ,IAAI;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AACA,QAAM,SAAS,mBAAmB,UAAU,IAAI;AAChD,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,sBAAsB,IAAI;AAAA,MAC1B;AAAA,QACE,KAAK,QAAQ,IAAI;AAAA,QACjB,SAAS,OAAO,MAAM;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO;AAChB;AAMO,SAAS,kBAAkB,KAAa,OAA2B;AACxE,QAAM,OAAO,WAAW,GAAG;AAC3B,SAAO,IAAI,SAAS,iBAAiB,8BAA8B,IAAI,KAAK;AAAA,IAC1E,KAAK;AAAA,IACL,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;AAAA,EACzC,CAAC;AACH;AASA,eAAsB,kBAAkB,KAAa,QAAqC;AACxF,QAAM,YAAY,mBAAmB,MAAM,MAAM;AACjD,QAAM,OAAO,WAAW,GAAG;AAC3B,MAAI;AACF,UAAM,yBAAyB,MAAM,GAAG,KAAK,UAAU,WAAW,MAAM,CAAC,CAAC;AAAA,GAAM;AAAA,MAC9E,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,QAAI,QAAQ,KAAK,QAAQ,EAAG,OAAM,kBAAkB,KAAK,GAAG;AAC5D,UAAM;AAAA,EACR;AACF;AAGA,SAAS,sBAAsB,MAAwB;AACrD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAM;AACZ,SAAO,IAAI,kBAAkB,KAAK,gBAAgB;AACpD;AAEA,SAAS,WAAW,KAAuB;AACzC,SAAO,QAAQ,KAAK,QAAQ;AAC9B;","names":[]}
1
+ {"version":3,"sources":["../src/lib/wallet/store.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { writeFileAtomicExclusive } from '../atomic-json';\nimport { hasCode } from '../errno';\nimport { walletPath } from '../paths';\n\n/** A 0x-prefixed 32-byte hex private key (case-insensitive). */\nexport const PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The at-rest shape of a Keystore v3 document (Web3 Secret Storage). Validated\n * structurally on read so an obviously-corrupt keystore fails as\n * WALLET_INVALID_KEY before we ever ask for a passphrase; the real integrity\n * check is the keystore's own MAC, verified by ox at decrypt time. `kdfparams`\n * stays an open object because scrypt and pbkdf2 carry different fields and only\n * ox needs to interpret them.\n */\nconst KeystoreV3Schema = z.object({\n crypto: z.object({\n cipher: z.literal('aes-128-ctr'),\n ciphertext: z.string(),\n cipherparams: z.object({ iv: z.string() }),\n kdf: z.enum(['scrypt', 'pbkdf2']),\n kdfparams: z.record(z.string(), z.unknown()),\n mac: z.string(),\n }),\n id: z.string(),\n version: z.literal(3),\n});\n\n/**\n * The persisted wallet record (schema v2). The private key is NEVER stored in\n * cleartext: `keystore` is a Keystore v3 document (scrypt + AES-128-CTR) and the\n * key is recovered only by decrypting it with the wallet passphrase. `address`\n * stays top-level in cleartext ON PURPOSE so `show`/`balance`/`doctor` keep\n * working without a passphrase; only signing decrypts. The `provider`\n * discriminator keeps the schema from implying every future wallet embeds a\n * keystore. Validated on read (a corrupt file is WALLET_INVALID_KEY, never a\n * silent partial parse).\n */\nexport const WalletRecordSchema = z.object({\n schemaVersion: z.literal(2),\n provider: z.literal('local'),\n address: z.string().regex(ADDRESS_RE, 'expected a 0x-prefixed 20-byte address'),\n keystore: KeystoreV3Schema,\n createdAt: z.string(),\n});\nexport type WalletRecord = Omit<z.infer<typeof WalletRecordSchema>, 'keystore'> & {\n keystore: Keystore.Keystore;\n};\n\nexport async function walletFileExists(dir: string): Promise<boolean> {\n return (await walletFileMode(dir)) !== null;\n}\n\n/** File permission bits (`mode & 0o777`), or null when the wallet file is absent. */\nexport async function walletFileMode(dir: string): Promise<number | null> {\n try {\n return (await stat(walletPath(dir))).mode & 0o777;\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n}\n\n/** Read + validate the wallet record; null when absent, WALLET_INVALID_KEY when corrupt. */\nexport async function readWalletRecord(dir: string): Promise<WalletRecord | null> {\n const path = walletPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return null;\n throw new CliError('WALLET_INVALID_KEY', `Could not read the wallet file at ${path}.`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('WALLET_INVALID_KEY', `The wallet file at ${path} is not valid JSON.`, {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n cause: err,\n });\n }\n // A pre-encryption record (schema v1 stored the raw key). There is no in-place\n // migration: the old key must be swept and a fresh encrypted wallet created.\n if (isPreEncryptionRecord(json)) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} predates encrypted storage.`,\n {\n fix: `Move ${path} aside and run \\`tenjin wallet create\\`; sweep any funds from the old address first.`,\n },\n );\n }\n const parsed = WalletRecordSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} is not a valid wallet record.`,\n {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data as WalletRecord;\n}\n\n/**\n * The one WALLET_EXISTS error, shared by the create pre-check and the exclusive\n * write's race loser so the two surfaces can never drift apart.\n */\nexport function walletExistsError(dir: string, cause?: unknown): CliError {\n const path = walletPath(dir);\n return new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Run \\`tenjin wallet create --replace\\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable — never delete the credential-store entry, or the wallet's funds are stranded.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n/**\n * Persist a validated record at 0600 in a 0700 dir, NO-CLOBBER. The exclusive\n * write — not an earlier existence check — is the authority: two concurrent\n * `create` runs can both pass a pre-check, but only one can win the atomic\n * commit; the loser surfaces as WALLET_EXISTS instead of silently overwriting\n * (and losing) a non-recoverable key.\n */\nexport async function writeWalletRecord(dir: string, record: WalletRecord): Promise<void> {\n const validated = WalletRecordSchema.parse(record);\n const path = walletPath(dir);\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n if (hasCode(err, 'EEXIST')) throw walletExistsError(dir, err);\n throw err;\n }\n}\n\n/** A cleartext-key record from before encrypted storage: schema v1 or a bare `privateKey`. */\nfunction isPreEncryptionRecord(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) return false;\n const rec = json as Record<string, unknown>;\n return rec.schemaVersion === 1 || 'privateKey' in rec;\n}\n\nfunction isNotFound(err: unknown): boolean {\n return hasCode(err, 'ENOENT');\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AASxB,IAAM,iBAAiB;AAC9B,IAAM,aAAa;AAUnB,IAAM,mBAAmB,iBAAE,OAAO;AAAA,EAChC,QAAQ,iBAAE,OAAO;AAAA,IACf,QAAQ,iBAAE,QAAQ,aAAa;AAAA,IAC/B,YAAY,iBAAE,OAAO;AAAA,IACrB,cAAc,iBAAE,OAAO,EAAE,IAAI,iBAAE,OAAO,EAAE,CAAC;AAAA,IACzC,KAAK,iBAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;AAAA,IAChC,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC;AAAA,IAC3C,KAAK,iBAAE,OAAO;AAAA,EAChB,CAAC;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AA,IACF;AAAA,EACF;AACA,QAAM,SAAS,mBAAmB,UAAU,IAAI;AAChD,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,sBAAsB,IAAI;AAAA,MAC1B;AAAA,QACE,KAAK,QAAQ,IAAI;AAAA,QACjB,SAAS,OAAO,MAAM;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO;AAChB;AAMO,SAAS,kBAAkB,KAAa,OAA2B;AACxE,QAAM,OAAO,WAAW,GAAG;AAC3B,SAAO,IAAI,SAAS,iBAAiB,8BAA8B,IAAI,KAAK;AAAA,IAC1E,KAAK;AAAA,IACL,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;AAAA,EACzC,CAAC;AACH;AASA,eAAsB,kBAAkB,KAAa,QAAqC;AACxF,QAAM,YAAY,mBAAmB,MAAM,MAAM;AACjD,QAAM,OAAO,WAAW,GAAG;AAC3B,MAAI;AACF,UAAM,yBAAyB,MAAM,GAAG,KAAK,UAAU,WAAW,MAAM,CAAC,CAAC;AAAA,GAAM;AAAA,MAC9E,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,QAAI,QAAQ,KAAK,QAAQ,EAAG,OAAM,kBAAkB,KAAK,GAAG;AAC5D,UAAM;AAAA,EACR;AACF;AAGA,SAAS,sBAAsB,MAAwB;AACrD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAM;AACZ,SAAO,IAAI,kBAAkB,KAAK,gBAAgB;AACpD;AAEA,SAAS,WAAW,KAAuB;AACzC,SAAO,QAAQ,KAAK,QAAQ;AAC9B;","names":[]}
@@ -0,0 +1,35 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ CliError
4
+ } from "./chunk-J6CVKC4M.js";
5
+
6
+ // src/lib/url.ts
7
+ function trimSlash(url) {
8
+ return url.replace(/\/+$/, "");
9
+ }
10
+ function tryOriginOf(url) {
11
+ let parsed;
12
+ try {
13
+ parsed = new URL(url);
14
+ } catch {
15
+ return null;
16
+ }
17
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
18
+ return parsed.origin;
19
+ }
20
+ function originOf(url) {
21
+ const origin = tryOriginOf(url);
22
+ if (origin === null) {
23
+ throw new CliError("USAGE", `Invalid base URL: ${JSON.stringify(url)}`, {
24
+ fix: "Set an absolute http(s) base URL: `tenjin config set baseUrl <url>`."
25
+ });
26
+ }
27
+ return origin;
28
+ }
29
+
30
+ export {
31
+ trimSlash,
32
+ tryOriginOf,
33
+ originOf
34
+ };
35
+ //# sourceMappingURL=chunk-XBJ3VLWX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/url.ts"],"sourcesContent":["import { CliError } from './errors';\n\n/** Drop trailing slashes from a base URL so `${base}/path` never doubles a slash. */\nexport function trimSlash(url: string): string {\n return url.replace(/\\/+$/, '');\n}\n\n/**\n * The `scheme://host[:port]` of an http(s) URL, or null if it is not one.\n *\n * Non-http schemes are rejected rather than passed through, and that is the whole\n * reason this is not a one-line `new URL(url).origin`: for any non-special\n * scheme the WHATWG origin is the opaque string `\"null\"`, so `foo://tenjin.blog`\n * and `bar://evil.example` compare EQUAL. This value binds a wallet-derived\n * credential to one deployment, so an equal-comparing sentinel is exactly the\n * failure it exists to prevent — the same shape as the unparseable case, just\n * spelled differently.\n */\nexport function tryOriginOf(url: string): string | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;\n return parsed.origin;\n}\n\n/**\n * `tryOriginOf` for callers that cannot proceed without an origin. Throws USAGE\n * rather than returning a sentinel; anything that must survive a bad base URL\n * (diagnostics, above all) uses `tryOriginOf` and handles the null.\n */\nexport function originOf(url: string): string {\n const origin = tryOriginOf(url);\n if (origin === null) {\n throw new CliError('USAGE', `Invalid base URL: ${JSON.stringify(url)}`, {\n fix: 'Set an absolute http(s) base URL: `tenjin config set baseUrl <url>`.',\n });\n }\n return origin;\n}\n"],"mappings":";;;;;;AAGO,SAAS,UAAU,KAAqB;AAC7C,SAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;AAaO,SAAS,YAAY,KAA4B;AACtD,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,OAAO,aAAa,WAAW,OAAO,aAAa,SAAU,QAAO;AACxE,SAAO,OAAO;AAChB;AAOO,SAAS,SAAS,KAAqB;AAC5C,QAAM,SAAS,YAAY,GAAG;AAC9B,MAAI,WAAW,MAAM;AACnB,UAAM,IAAI,SAAS,SAAS,qBAAqB,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,MACtE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":[]}