dsh-inkmap 0.3.8 → 0.3.11

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 (62) hide show
  1. package/README.md +15 -15
  2. package/README.zh.md +29 -15
  3. package/client.js +14 -3
  4. package/host.js +654 -371
  5. package/package.json +1 -1
  6. package/web/assets/{abnfDiagram-S7VZAUFO-Cv52kI-2.js → abnfDiagram-S7VZAUFO-BG5MYX3Z.js} +1 -1
  7. package/web/assets/{architectureDiagram-YGSQEFNW-C5siUviK.js → architectureDiagram-YGSQEFNW-xhOdCZHT.js} +1 -1
  8. package/web/assets/{blockDiagram-APKKGZFW-D9Cx18Cy.js → blockDiagram-APKKGZFW-om09jcTu.js} +1 -1
  9. package/web/assets/{c4Diagram-KJ2TOQU5-Cvk1QesM.js → c4Diagram-KJ2TOQU5-bf-oCj-6.js} +1 -1
  10. package/web/assets/{chunk-2Q5K7J3B-BvpOcdWP.js → chunk-2Q5K7J3B-Cd6Zuyl0.js} +1 -1
  11. package/web/assets/{chunk-5VM5RSS4-Bk04rbHq.js → chunk-5VM5RSS4-D_9yIgMi.js} +1 -1
  12. package/web/assets/{chunk-HFQBQIA3-C2qMwyd_.js → chunk-HFQBQIA3-BSpJ_KUx.js} +1 -1
  13. package/web/assets/{chunk-JWPE2WC7-DoowW69r.js → chunk-JWPE2WC7-Bd1mTs5z.js} +1 -1
  14. package/web/assets/{chunk-KQLB2F66-BQcHY-wd.js → chunk-KQLB2F66-BjvuoG6k.js} +2 -2
  15. package/web/assets/{chunk-KS47KZWR-CJcu1y9y.js → chunk-KS47KZWR-DQnmQr8q.js} +1 -1
  16. package/web/assets/{chunk-OY52VR5R-Dh-uJO9r.js → chunk-OY52VR5R-CavAtvvE.js} +1 -1
  17. package/web/assets/{chunk-TU62E6Q5-D51xn01O.js → chunk-TU62E6Q5-DGB27D5M.js} +1 -1
  18. package/web/assets/{chunk-XXDRQBXY-BUe08pSx.js → chunk-XXDRQBXY-DiUpl_oE.js} +1 -1
  19. package/web/assets/{classDiagram-v2-L25IHNXF-BGwiHkBO.js → classDiagram-v2-L25IHNXF-ByAHR9p1.js} +1 -1
  20. package/web/assets/{cose-bilkent-JH36ORCC-ATmSDzBm.js → cose-bilkent-JH36ORCC-T2AuyNNM.js} +1 -1
  21. package/web/assets/{cynefin-EF2NZ3EQ-BFiIOe-P.js → cynefin-EF2NZ3EQ-CWvVLSHN.js} +1 -1
  22. package/web/assets/{cynefinDiagram-L36ESFBY-DRTNpfDL.js → cynefinDiagram-L36ESFBY-EyBF2aYr.js} +1 -1
  23. package/web/assets/{dagre-SPEB5RXH-by7IaF5F.js → dagre-SPEB5RXH-DzCJs6d8.js} +1 -1
  24. package/web/assets/{diagram-3B7GL73J-rcNPo48m.js → diagram-3B7GL73J-BpqB4EyM.js} +1 -1
  25. package/web/assets/{diagram-DNEMPZML-iBi9Aax-.js → diagram-DNEMPZML-ByMvtGvg.js} +1 -1
  26. package/web/assets/{diagram-L3MUGCDN-DNcvt2mz.js → diagram-L3MUGCDN-BZlcEYsl.js} +1 -1
  27. package/web/assets/{diagram-LA4NIPWU-DEyZS6bD.js → diagram-LA4NIPWU-3kIxJzbY.js} +1 -1
  28. package/web/assets/{diagram-MHCOC4E2-D8atr--z.js → diagram-MHCOC4E2-BrWZm3sI.js} +1 -1
  29. package/web/assets/{diagram-XPFHEONP-D6H6iXV8.js → diagram-XPFHEONP-BjI1Mh1e.js} +1 -1
  30. package/web/assets/{ebnfDiagram-UZSYDL2S-TOp29H5n.js → ebnfDiagram-UZSYDL2S-BQb2XwWh.js} +1 -1
  31. package/web/assets/{elk-XV6XMXQE-D_I6bqGt.js → elk-XV6XMXQE-okjyR_tN.js} +1 -1
  32. package/web/assets/{erDiagram-EYBAPDEH-BfLIdaNH.js → erDiagram-EYBAPDEH-D_A5Ddgs.js} +1 -1
  33. package/web/assets/{flowDiagram-MALGAFMO-Bznd9mmI.js → flowDiagram-MALGAFMO-tTRMeUpP.js} +1 -1
  34. package/web/assets/{ganttDiagram-23REXITY-B1d5Izgt.js → ganttDiagram-23REXITY-Dko0e4pt.js} +1 -1
  35. package/web/assets/{gitGraphDiagram-STJD7YCW-4oJOXeNt.js → gitGraphDiagram-STJD7YCW-CLpH2Llw.js} +1 -1
  36. package/web/assets/index-BjS7o_Gs.js +767 -0
  37. package/web/assets/{index-BZG1D6oJ.css → index-BubxFPMN.css} +1 -1
  38. package/web/assets/{infoDiagram-KBXO4MBG-s8ALIoGd.js → infoDiagram-KBXO4MBG-Cf_YXaCy.js} +1 -1
  39. package/web/assets/{ishikawaDiagram-M35NCXHK-CCLGdUCq.js → ishikawaDiagram-M35NCXHK-BNUjJR-I.js} +1 -1
  40. package/web/assets/{journeyDiagram-OPLOXDXO-DVUeKyL8.js → journeyDiagram-OPLOXDXO-DW9CX1jJ.js} +1 -1
  41. package/web/assets/{kanban-definition-BZKZHSQY-z-Im93V7.js → kanban-definition-BZKZHSQY-D5kMETGg.js} +1 -1
  42. package/web/assets/{mermaid.core-Bpeij6Eb.js → mermaid.core-DrKMwEZo.js} +4 -4
  43. package/web/assets/{mindmap-definition-I2QAS2VK-BcrLb6db.js → mindmap-definition-I2QAS2VK-CGTN7dUC.js} +1 -1
  44. package/web/assets/{pegDiagram-FD4XPPHP-CIx8lMXF.js → pegDiagram-FD4XPPHP-B8pSeDvB.js} +1 -1
  45. package/web/assets/{pieDiagram-J4AKIIQI-uCHWsO4S.js → pieDiagram-J4AKIIQI-unMZGSAm.js} +1 -1
  46. package/web/assets/{quadrantDiagram-XTYBLID2-BX2qwhme.js → quadrantDiagram-XTYBLID2-CNr8tGSd.js} +1 -1
  47. package/web/assets/{railroadDiagram-MRQ6NCDL-CjyM79qk.js → railroadDiagram-MRQ6NCDL-DNTLRvF6.js} +1 -1
  48. package/web/assets/{requirementDiagram-Y7LWUY3S-BJVR4KSl.js → requirementDiagram-Y7LWUY3S-8OWE5U2v.js} +1 -1
  49. package/web/assets/{sankeyDiagram-WGJFYUXA-D0_hSNij.js → sankeyDiagram-WGJFYUXA-BuRgD8JC.js} +1 -1
  50. package/web/assets/{sequenceDiagram-5NDRBG5M-DnTdg9Z5.js → sequenceDiagram-5NDRBG5M-Dk98EWvB.js} +1 -1
  51. package/web/assets/{sizeCapture-INFHLROL-DpXFdfyw.js → sizeCapture-INFHLROL-CgCDFhLh.js} +1 -1
  52. package/web/assets/{stateDiagram-v2-FJ4FJNEA-h4W01T-f.js → stateDiagram-v2-FJ4FJNEA-oPZjdCYL.js} +1 -1
  53. package/web/assets/{swimlanes-UMQ2AFYF-DF1ydmKR.js → swimlanes-UMQ2AFYF-n24AiDnm.js} +1 -1
  54. package/web/assets/swimlanesDiagram-OMPLPG4O-B1c0Wqw8.js +8 -0
  55. package/web/assets/{timeline-definition-SEUHKTQE-DKK3MFBh.js → timeline-definition-SEUHKTQE-CbD3aP4-.js} +1 -1
  56. package/web/assets/{usecaseDiagram-AFA6YXN4-Da7KDGnI.js → usecaseDiagram-AFA6YXN4-bJHinCId.js} +1 -1
  57. package/web/assets/{vennDiagram-NNMJR3RB-DXmI4Avx.js → vennDiagram-NNMJR3RB-BO0UGuRE.js} +1 -1
  58. package/web/assets/{wardleyDiagram-S7YFUSEH-Cj0zPvDJ.js → wardleyDiagram-S7YFUSEH-C92NnP4P.js} +1 -1
  59. package/web/assets/{xychartDiagram-GGNKY7IX-CkEz0WjS.js → xychartDiagram-GGNKY7IX-Dmsz0oIz.js} +1 -1
  60. package/web/index.html +5 -5
  61. package/web/assets/index-D_oxh87y.js +0 -719
  62. package/web/assets/swimlanesDiagram-OMPLPG4O-BuXkTCUS.js +0 -8
package/host.js CHANGED
@@ -1,15 +1,13 @@
1
1
  // packages/harness/src/host.mjs
2
2
  import { randomUUID as randomUUID2 } from "node:crypto";
3
- import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
4
- import { isAbsolute as isAbsolute2, relative as relative2, sep as sep2 } from "node:path";
3
+ import { lstat as lstat3, realpath as realpath3 } from "node:fs/promises";
4
+ import { isAbsolute as isAbsolute2, relative as relative3, sep as sep4 } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
 
7
7
  // packages/core/dist/product.js
8
8
  var PRODUCT = {
9
9
  id: "inkmap-pro",
10
- entitlement: "inkmap.pro",
11
- /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
12
- adFeedUrl: ""
10
+ entitlement: "inkmap.pro"
13
11
  };
14
12
  var YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
15
13
  function billingFlowUrl(raw, origin, mode, legacy = false) {
@@ -57,56 +55,83 @@ function sanitizeViewState(raw) {
57
55
  import { execFileSync } from "node:child_process";
58
56
  import { link, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
59
57
  import { randomUUID } from "node:crypto";
60
- import { homedir } from "node:os";
61
- import { dirname, join } from "node:path";
58
+ import { homedir, tmpdir } from "node:os";
59
+ import { dirname, join, sep } from "node:path";
60
+
61
+ // packages/cli/dist/version.js
62
+ var INKMAP_VERSION = "0.3.11";
63
+
64
+ // packages/cli/dist/license.js
65
+ var ZH_LOCALE_RE = /^zh(?:[-_.]|$)/i;
66
+ var EN_LOCALE_RE = /^en(?:[-_.]|$)/i;
62
67
  var cachedOsLocale;
63
- function detectOsLocale() {
64
- const explicit = (process.env.INKMAP_LOCALE || "").trim();
65
- if (/^zh\b/i.test(explicit))
68
+ var WAIT_FAST_MS = 2500;
69
+ var WAIT_SLOW_MS = 3e4;
70
+ var WAIT_FAST_FOR_MS = 30 * 6e4;
71
+ var WAIT_MAX_MS = 3 * 24 * 60 * 6e4;
72
+ var MAX_WAITING = 5;
73
+ function isWaitingToken(value) {
74
+ const w = value;
75
+ return Boolean(w) && typeof w.origin === "string" && typeof w.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(w.token) && typeof w.email === "string" && typeof w.since === "number" && typeof w.fastUntil === "number";
76
+ }
77
+ var DOMESTIC_TIME_ZONE = /^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i;
78
+ function parseAppleLanguages(output) {
79
+ const match = /^\(\s*(?:"([^"]+)"|([^\s,)]+))/m.exec(output);
80
+ return match?.[1] ?? match?.[2] ?? "";
81
+ }
82
+ var posixLocale = (env) => (env.LC_ALL || env.LC_MESSAGES || env.LANG || "").trim();
83
+ function resolveOsLocale(probe) {
84
+ const explicit = (probe.env.INKMAP_LOCALE || "").trim();
85
+ if (ZH_LOCALE_RE.test(explicit))
66
86
  return "zh";
67
- if (/^en\b/i.test(explicit))
87
+ if (EN_LOCALE_RE.test(explicit))
68
88
  return "en";
69
- if (cachedOsLocale)
70
- return cachedOsLocale;
71
- let domestic = false;
72
- try {
73
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
74
- if (/^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i.test(tz)) {
75
- domestic = true;
89
+ if (DOMESTIC_TIME_ZONE.test(probe.timeZone))
90
+ return "zh";
91
+ let language = "";
92
+ if (probe.platform === "darwin") {
93
+ try {
94
+ language = parseAppleLanguages(probe.run("defaults", ["read", "-g", "AppleLanguages"]));
95
+ } catch {
96
+ language = posixLocale(probe.env);
76
97
  }
77
- } catch {
78
- }
79
- if (!domestic) {
80
- if (process.platform === "darwin") {
81
- try {
82
- const out = execFileSync("defaults", ["read", "-g", "AppleLanguages"], {
83
- encoding: "utf8",
84
- timeout: 800,
85
- stdio: ["ignore", "pipe", "ignore"]
86
- });
87
- const firstLang = /"([^"]+)"/.exec(out)?.[1] ?? "";
88
- if (/^zh\b/i.test(firstLang))
89
- domestic = true;
90
- } catch {
91
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
92
- if (/^zh\b/i.test(raw))
93
- domestic = true;
94
- }
95
- } else if (process.platform === "win32") {
96
- try {
97
- const loc = Intl.DateTimeFormat().resolvedOptions().locale || "";
98
- if (/^zh\b/i.test(loc))
99
- domestic = true;
100
- } catch {
101
- }
102
- } else {
103
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
104
- if (/^zh\b/i.test(raw))
105
- domestic = true;
98
+ } else if (probe.platform === "win32") {
99
+ try {
100
+ const output = probe.run("reg", ["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"]);
101
+ language = /LocaleName\s+REG_\w+\s+(\S+)/i.exec(output)?.[1] ?? "";
102
+ } catch {
106
103
  }
104
+ if (!language)
105
+ language = probe.intlLocale;
106
+ } else {
107
+ language = posixLocale(probe.env);
108
+ }
109
+ return ZH_LOCALE_RE.test(language) ? "zh" : "en";
110
+ }
111
+ function systemLocaleProbe() {
112
+ let timeZone = "";
113
+ let intlLocale = "";
114
+ try {
115
+ const options = Intl.DateTimeFormat().resolvedOptions();
116
+ timeZone = options.timeZone || "";
117
+ intlLocale = options.locale || "";
118
+ } catch {
107
119
  }
108
- cachedOsLocale = domestic ? "zh" : "en";
109
- return cachedOsLocale;
120
+ return {
121
+ platform: process.platform,
122
+ env: process.env,
123
+ timeZone,
124
+ intlLocale,
125
+ run: (command, args) => execFileSync(command, args, { encoding: "utf8", timeout: 800, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] })
126
+ };
127
+ }
128
+ function detectOsLocale() {
129
+ const explicit = (process.env.INKMAP_LOCALE || "").trim();
130
+ if (ZH_LOCALE_RE.test(explicit))
131
+ return "zh";
132
+ if (EN_LOCALE_RE.test(explicit))
133
+ return "en";
134
+ return cachedOsLocale ??= resolveOsLocale(systemLocaleProbe());
110
135
  }
111
136
  function billingOrigin(raw) {
112
137
  if (!raw)
@@ -117,7 +142,7 @@ function billingOrigin(raw) {
117
142
  }
118
143
  return url.origin;
119
144
  }
120
- function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "" } = {}) {
145
+ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "", waitPollMs = WAIT_FAST_MS } = {}) {
121
146
  const listeners = /* @__PURE__ */ new Set();
122
147
  let current = { pro: false };
123
148
  let trial;
@@ -129,6 +154,9 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
129
154
  let detectedHost = defaultHost;
130
155
  const pendingEvents = /* @__PURE__ */ new Map();
131
156
  let lastCheck = 0;
157
+ let fastPollUntil = 0;
158
+ const expectPurchase = () => void (fastPollUntil = Date.now() + 15 * 6e4);
159
+ let flowCreation;
132
160
  let disposed = false;
133
161
  let generation = 0;
134
162
  let connection;
@@ -136,12 +164,33 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
136
164
  let pendingWrite = Promise.resolve();
137
165
  let pendingCheckout;
138
166
  let cachedOrder;
139
- let magicPollTimer;
140
- let magicSession = 0;
141
- function stopMagicPoll() {
142
- ++magicSession;
143
- clearTimeout(magicPollTimer);
144
- magicPollTimer = void 0;
167
+ let waiting = [];
168
+ let waitTimer;
169
+ let waitRound = 0;
170
+ let lastSignIn;
171
+ const sessionRecord = (fields) => JSON.stringify({ ...fields, ...lastSignIn && { lastSignIn } });
172
+ const signedOutRecord = () => lastSignIn || waiting.length ? JSON.stringify({ ...lastSignIn && { lastSignIn }, ...waiting.length && { waiting } }) : void 0;
173
+ async function rememberSignIn(id) {
174
+ const clean = id.trim().slice(0, 254);
175
+ if (!clean || clean === lastSignIn)
176
+ return;
177
+ lastSignIn = clean;
178
+ current = { ...current, lastSignIn };
179
+ await writeSession(async () => {
180
+ let record = {};
181
+ try {
182
+ record = JSON.parse(await storage.read() || "{}");
183
+ } catch {
184
+ }
185
+ await storage.write(JSON.stringify({ ...record, lastSignIn }));
186
+ }).catch(() => {
187
+ });
188
+ }
189
+ function clearWaiting() {
190
+ waiting = [];
191
+ ++waitRound;
192
+ clearTimeout(waitTimer);
193
+ waitTimer = void 0;
145
194
  }
146
195
  function mergeCookies(existing, response) {
147
196
  const map = /* @__PURE__ */ new Map();
@@ -172,12 +221,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
172
221
  }
173
222
  return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
174
223
  }
175
- function clientLocale(hint) {
176
- const h = (hint || "").trim();
177
- if (/^zh\b/i.test(h))
178
- return "zh";
179
- if (/^en\b/i.test(h))
180
- return "en";
224
+ function clientLocale(_uiLocaleHint) {
181
225
  return detectOsLocale();
182
226
  }
183
227
  function writeSession(operation) {
@@ -209,7 +253,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
209
253
  if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
210
254
  throw new Error("Invalid Inkmap checkout response.");
211
255
  }
212
- return { origin, url, token: data.token, ...cookie && { cookie } };
256
+ return { origin, url, token: data.token, locale: loc, ...cookie && { cookie } };
213
257
  }
214
258
  function checkoutPost(checkoutUrl, action, origin, body, token, cookie, localeHint) {
215
259
  const loc = clientLocale(localeHint);
@@ -271,12 +315,26 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
271
315
  pro,
272
316
  ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
273
317
  ...connected && { connected: true },
274
- ...cleanAccount && { account: cleanAccount }
318
+ ...cleanAccount && { account: cleanAccount },
319
+ ...lastSignIn && { lastSignIn }
275
320
  };
276
321
  for (const listener of listeners)
277
322
  listener(current);
278
323
  }
279
324
  async function startTrial() {
325
+ try {
326
+ const record = JSON.parse(await storage.read() || "{}");
327
+ const remembered = record.lastSignIn;
328
+ if (typeof remembered === "string" && remembered.trim() && !lastSignIn) {
329
+ lastSignIn = remembered.trim().slice(0, 254);
330
+ current = { ...current, lastSignIn };
331
+ }
332
+ if (typeof record.token !== "string" && Array.isArray(record.waiting) && !waiting.length) {
333
+ waiting = record.waiting.filter(isWaitingToken).slice(-MAX_WAITING);
334
+ scheduleWait(waitPollMs);
335
+ }
336
+ } catch {
337
+ }
280
338
  const trialUntil = await localTrialDeadline().catch(() => void 0);
281
339
  if (disposed || trialUntil === void 0)
282
340
  return;
@@ -328,7 +386,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
328
386
  return await writeSession(async () => {
329
387
  if (version !== generation || disposed)
330
388
  return;
331
- await storage.write(void 0).catch(() => {
389
+ await storage.write(signedOutRecord()).catch(() => {
332
390
  });
333
391
  update(false);
334
392
  });
@@ -352,59 +410,195 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
352
410
  });
353
411
  return connection;
354
412
  }
355
- function startMagicPoll(origin, pendingToken) {
356
- stopMagicPoll();
357
- const id = magicSession;
358
- const deadline = Date.now() + 10 * 6e4;
359
- const poll = () => {
360
- if (disposed || id !== magicSession || Date.now() >= deadline)
413
+ async function mustPayFirst() {
414
+ if (!loginOnly)
415
+ return false;
416
+ await (trial ??= startTrial());
417
+ return current.trialUntil !== void 0 && current.trialUntil <= Date.now();
418
+ }
419
+ async function waitFor(origin, token, email) {
420
+ const now = Date.now();
421
+ const same = (other) => !other || !email || other.toLowerCase() === email.toLowerCase();
422
+ waiting = waiting.filter((w) => w.token !== token && same(w.email)).map((w) => ({ ...w, fastUntil: now + WAIT_FAST_FOR_MS }));
423
+ waiting.push({ origin, token, email, since: now, fastUntil: now + WAIT_FAST_FOR_MS });
424
+ waiting = waiting.slice(-MAX_WAITING);
425
+ scheduleWait(waitPollMs);
426
+ await writeSession(async () => {
427
+ let record = {};
428
+ try {
429
+ record = JSON.parse(await storage.read() || "{}");
430
+ } catch {
431
+ }
432
+ if (typeof record.token !== "string")
433
+ await storage.write(signedOutRecord());
434
+ }).catch(() => {
435
+ });
436
+ }
437
+ function scheduleWait(delay) {
438
+ clearTimeout(waitTimer);
439
+ if (disposed || !waiting.length)
440
+ return;
441
+ waitTimer = setTimeout(() => void checkWaiting(), delay);
442
+ waitTimer.unref();
443
+ }
444
+ async function checkWaiting() {
445
+ const round = ++waitRound;
446
+ const now = Date.now();
447
+ const before = waiting.length;
448
+ let origin;
449
+ try {
450
+ origin = billingOrigin(getOrigin());
451
+ } catch {
452
+ return scheduleWait(WAIT_SLOW_MS);
453
+ }
454
+ waiting = waiting.filter((w) => w.origin === origin && now - w.since < WAIT_MAX_MS);
455
+ for (const w of [...waiting]) {
456
+ let response;
457
+ try {
458
+ response = await entitlement(w.origin, w.token);
459
+ } catch {
460
+ continue;
461
+ }
462
+ if (disposed || round !== waitRound)
463
+ return;
464
+ if (response.status === 401) {
465
+ waiting = waiting.filter((other) => other !== w);
466
+ continue;
467
+ }
468
+ if (!response.ok)
469
+ continue;
470
+ const body = await response.json().catch(() => null);
471
+ if (disposed || round !== waitRound)
472
+ return;
473
+ if (body?.connected !== true || body.entitlement !== PRODUCT.entitlement)
474
+ continue;
475
+ if (body.active !== true && await mustPayFirst())
476
+ continue;
477
+ if (disposed || round !== waitRound)
361
478
  return;
362
- magicPollTimer = setTimeout(async () => {
363
- if (disposed || id !== magicSession)
479
+ await writeSession(async () => {
480
+ if (disposed || round !== waitRound || w.origin !== billingOrigin(getOrigin()))
364
481
  return;
482
+ clearWaiting();
483
+ await storage.write(sessionRecord({ origin: w.origin, token: w.token }));
484
+ ++generation;
485
+ activeOrigin = w.origin;
486
+ applyEntitlement(body);
487
+ schedule(body.active === true ? 6e4 : 2500);
488
+ });
489
+ return;
490
+ }
491
+ if (disposed || round !== waitRound)
492
+ return;
493
+ if (waiting.length !== before) {
494
+ await writeSession(async () => {
495
+ let record = {};
365
496
  try {
366
- const res = await entitlement(origin, pendingToken);
367
- if (disposed || id !== magicSession)
368
- return;
369
- if (res.status === 401) {
370
- stopMagicPoll();
371
- return;
372
- }
373
- if (res.ok) {
374
- const body = await res.json();
375
- if (body?.connected === true && body.entitlement === PRODUCT.entitlement) {
376
- stopMagicPoll();
377
- await writeSession(async () => {
378
- if (disposed || origin !== billingOrigin(getOrigin()))
379
- return;
380
- await storage.write(JSON.stringify({ origin, token: pendingToken }));
381
- ++generation;
382
- activeOrigin = origin;
383
- applyEntitlement(body);
384
- schedule(body.active === true ? 6e4 : 2500);
385
- });
386
- return;
387
- }
388
- }
497
+ record = JSON.parse(await storage.read() || "{}");
389
498
  } catch {
390
499
  }
391
- if (!disposed && id === magicSession && Date.now() < deadline)
392
- poll();
393
- }, 2e3);
394
- magicPollTimer.unref();
395
- };
396
- poll();
500
+ if (typeof record.token !== "string")
501
+ await storage.write(signedOutRecord());
502
+ }).catch(() => {
503
+ });
504
+ }
505
+ scheduleWait(waiting.some((w) => Date.now() < w.fastUntil) ? waitPollMs : WAIT_SLOW_MS);
506
+ }
507
+ async function parkUnpaidSession() {
508
+ if (current.pro || !current.connected || !await mustPayFirst())
509
+ return;
510
+ await writeSession(async () => {
511
+ if (current.pro || !current.connected)
512
+ return;
513
+ let record = {};
514
+ try {
515
+ record = JSON.parse(await storage.read() || "{}");
516
+ } catch {
517
+ }
518
+ if (typeof record.token !== "string" || typeof record.origin !== "string")
519
+ return;
520
+ const response = await entitlement(record.origin, record.token).catch(() => null);
521
+ if (!response?.ok)
522
+ return;
523
+ const latest = await response.json().catch(() => null);
524
+ if (!latest || latest.active === true || latest.connected !== true) {
525
+ if (latest)
526
+ applyEntitlement(latest);
527
+ return;
528
+ }
529
+ ++generation;
530
+ clearTimeout(timer);
531
+ lastCheck = 0;
532
+ const now = Date.now();
533
+ waiting = [
534
+ ...waiting.filter((w) => w.token !== record.token),
535
+ { origin: record.origin, token: record.token, email: lastSignIn ?? "", since: now, fastUntil: now + WAIT_FAST_FOR_MS }
536
+ ].slice(-MAX_WAITING);
537
+ await storage.write(signedOutRecord());
538
+ update(false);
539
+ });
540
+ scheduleWait(waitPollMs);
541
+ }
542
+ async function sendPendingTelemetry() {
543
+ if (disposed || !pendingEvents.size)
544
+ return;
545
+ let origin;
546
+ try {
547
+ origin = billingOrigin(getOrigin());
548
+ } catch {
549
+ return;
550
+ }
551
+ if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
552
+ if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
553
+ return;
554
+ const customHome = process.env.INKMAP_HOME || "";
555
+ const sysTmp = tmpdir();
556
+ if (customHome && (customHome === sysTmp || customHome.startsWith(sysTmp + sep) || customHome.startsWith("/tmp/") || customHome.startsWith("/private/tmp/") || customHome.includes("/var/folders/") || customHome.includes("inkmap-npm-isolated-") || customHome.includes("inkmap-antigravity-mcp-") || customHome.includes("inkmap-local-editor-") || customHome.includes("inkmap-harness-"))) {
557
+ return;
558
+ }
559
+ }
560
+ const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
561
+ if (disposed || !id || !pendingEvents.size)
562
+ return;
563
+ await (trial ??= startTrial());
564
+ const events = {};
565
+ for (const [k, v] of pendingEvents.entries())
566
+ events[k] = v;
567
+ pendingEvents.clear();
568
+ const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
569
+ const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
570
+ const hostName = detectedHost || inferNodeHost();
571
+ await fetch(origin + "/billing/v1/telemetry", {
572
+ method: "POST",
573
+ headers: { "content-type": "application/json" },
574
+ redirect: "error",
575
+ body: JSON.stringify({
576
+ product: PRODUCT.id,
577
+ installId: id,
578
+ host: hostName,
579
+ os,
580
+ version: INKMAP_VERSION,
581
+ locale: clientLocale(),
582
+ tier,
583
+ events
584
+ }),
585
+ signal: AbortSignal.timeout(5e3)
586
+ }).catch(() => {
587
+ });
397
588
  }
398
589
  return {
399
590
  async state() {
400
591
  await (trial ??= startTrial());
401
- if (Date.now() - lastCheck >= 4e3)
592
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
593
+ if (Date.now() - lastCheck >= interval)
402
594
  await refresh();
595
+ await parkUnpaidSession();
403
596
  return current;
404
597
  },
405
598
  async connect(mode, localeHint) {
406
599
  if (loginOnly && mode !== "restore")
407
600
  throw new Error("Only Yunfan account sign-in is available.");
601
+ expectPurchase();
408
602
  const origin = billingOrigin(getOrigin());
409
603
  const loc = clientLocale(localeHint);
410
604
  const version = generation;
@@ -446,7 +640,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
446
640
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
447
641
  throw new Error("The Yunfan account session changed. Please try again.");
448
642
  }
449
- await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
643
+ clearWaiting();
644
+ await storage.write(sessionRecord({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
450
645
  ++generation;
451
646
  lastCheck = 0;
452
647
  if (mode !== "buy" || !current.connected)
@@ -458,8 +653,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
458
653
  async orderPro(localeHint) {
459
654
  if (loginOnly)
460
655
  throw new Error("Only Yunfan account sign-in is available.");
656
+ expectPurchase();
461
657
  const origin = billingOrigin(getOrigin());
462
- if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
658
+ const loc = clientLocale(localeHint);
659
+ if (cachedOrder && cachedOrder.origin === origin && cachedOrder.locale === loc && Date.now() - cachedOrder.at < 8e3) {
463
660
  const hit = cachedOrder.result;
464
661
  cachedOrder = void 0;
465
662
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -485,7 +682,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
485
682
  await writeSession(async () => {
486
683
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
487
684
  return;
488
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
685
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
489
686
  if (persist) {
490
687
  ++generation;
491
688
  lastCheck = 0;
@@ -534,34 +731,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
534
731
  async sendPhoneCode(phone, localeHint) {
535
732
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254)
536
733
  return phoneFailure(400);
734
+ expectPurchase();
537
735
  const isEmail = phone.includes("@");
538
736
  const locale = clientLocale(localeHint);
539
737
  try {
540
738
  const origin = billingOrigin(getOrigin());
541
739
  if (!loginOnly) {
542
740
  try {
543
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
544
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
741
+ const newFlow = () => flowCreation ??= createCheckoutFlow(origin, void 0, void 0, locale).finally(() => {
742
+ flowCreation = void 0;
743
+ });
744
+ let flow = pendingCheckout;
745
+ if (!flow || flow.origin !== origin || flow.locale !== locale) {
746
+ flow = await newFlow();
747
+ pendingCheckout = flow;
545
748
  }
546
749
  const sendAction = isEmail ? "email/send" : "sms";
547
750
  const sendBody = isEmail ? { email: phone, locale } : { phone };
548
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
549
- if (smsRes.status === 410 || smsRes.status === 404) {
550
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
551
- smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
751
+ let smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
752
+ if (smsRes.status === 401 || smsRes.status === 403 || smsRes.status === 404 || smsRes.status === 410) {
753
+ flow = await newFlow();
754
+ pendingCheckout = flow;
755
+ smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
552
756
  }
553
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
554
- return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
757
+ flow.cookie = mergeCookies(flow.cookie, smsRes);
758
+ if (smsRes.status !== 204)
759
+ return phoneFailure(smsRes.status);
760
+ await rememberSignIn(phone);
761
+ return { ok: true, value: void 0 };
555
762
  } catch {
556
763
  pendingCheckout = void 0;
557
764
  }
558
765
  }
559
766
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
560
767
  if (response.status === 204) {
768
+ await rememberSignIn(phone);
561
769
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
562
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
563
- startMagicPoll(origin, pendingToken);
564
- }
770
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken))
771
+ await waitFor(origin, pendingToken, phone);
565
772
  return { ok: true, value: void 0 };
566
773
  }
567
774
  return phoneFailure(response.status);
@@ -569,41 +776,47 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
569
776
  return phoneFailure();
570
777
  }
571
778
  },
572
- async signInByPhone(phone, code) {
779
+ async signInByPhone(phone, code, localeHint) {
573
780
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code))
574
781
  return phoneFailure(400);
575
782
  const isEmail = phone.includes("@");
783
+ const locale = clientLocale(localeHint);
576
784
  const version = generation;
577
785
  try {
578
786
  const origin = billingOrigin(getOrigin());
579
787
  let token;
580
788
  let checkoutUrl;
581
789
  let cookie;
582
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
790
+ const flow = pendingCheckout;
791
+ if (!loginOnly && flow && flow.origin === origin) {
583
792
  const verifyAction = isEmail ? "email/verify" : "login";
584
793
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
585
- const loginRes = await checkoutPost(pendingCheckout.url, verifyAction, origin, verifyBody, pendingCheckout.token, pendingCheckout.cookie);
794
+ const loginRes = await checkoutPost(flow.url, verifyAction, origin, verifyBody, flow.token, flow.cookie, locale);
586
795
  if (!loginRes.ok) {
587
- if (loginRes.status === 410 || loginRes.status === 404)
588
- pendingCheckout = void 0;
796
+ if (loginRes.status === 401 || loginRes.status === 403 || loginRes.status === 404 || loginRes.status === 410) {
797
+ if (pendingCheckout === flow)
798
+ pendingCheckout = void 0;
799
+ }
589
800
  return phoneFailure(loginRes.status);
590
801
  }
591
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
592
- token = pendingCheckout.token;
593
- checkoutUrl = pendingCheckout.url;
594
- pendingCheckout = void 0;
595
- const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
802
+ cookie = mergeCookies(flow.cookie, loginRes);
803
+ token = flow.token;
804
+ checkoutUrl = flow.url;
805
+ if (pendingCheckout === flow)
806
+ pendingCheckout = void 0;
807
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie, locale).catch(() => null);
596
808
  if (orderRes?.ok) {
597
809
  cookie = mergeCookies(cookie, orderRes);
598
810
  const orderData = await orderRes.json().catch(() => null);
599
811
  if (orderData && typeof orderData === "object") {
600
812
  if (orderData.active === true) {
601
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
813
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
602
814
  } else if (typeof orderData.qr === "string" && orderData.qr) {
603
815
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
604
816
  cachedOrder = {
605
817
  at: Date.now(),
606
818
  origin,
819
+ locale,
607
820
  result: {
608
821
  status: "qr",
609
822
  qr,
@@ -612,12 +825,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
612
825
  }
613
826
  };
614
827
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
615
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
828
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
616
829
  }
617
830
  }
618
831
  }
619
832
  } else {
620
- const response = await phoneRequest(origin, "verify", phone, code);
833
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
621
834
  if (response.status !== 201)
622
835
  return phoneFailure(response.status);
623
836
  cookie = mergeCookies(void 0, response);
@@ -645,11 +858,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
645
858
  }
646
859
  if (cachedOrder?.result.status === "active")
647
860
  state.active = true;
861
+ if (!checkoutUrl && state.active !== true && await mustPayFirst()) {
862
+ await rememberSignIn(phone);
863
+ await waitFor(origin, token, phone);
864
+ return { ok: false, reason: "notPro" };
865
+ }
648
866
  return await writeSession(async () => {
649
867
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
650
868
  return phoneFailure();
651
- stopMagicPoll();
652
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
869
+ clearWaiting();
870
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
653
871
  ++generation;
654
872
  activeOrigin = origin;
655
873
  applyEntitlement(state);
@@ -663,12 +881,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
663
881
  }
664
882
  },
665
883
  async deactivate() {
666
- stopMagicPoll();
884
+ clearWaiting();
667
885
  pendingCheckout = void 0;
668
886
  cachedOrder = void 0;
669
887
  const saved = await writeSession(async () => {
670
888
  const previous = await storage.read();
671
- await storage.write(void 0);
889
+ await storage.write(signedOutRecord());
672
890
  ++generation;
673
891
  clearTimeout(timer);
674
892
  lastCheck = 0;
@@ -679,7 +897,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
679
897
  return;
680
898
  try {
681
899
  const { origin, token } = JSON.parse(saved);
682
- if (origin !== billingOrigin(getOrigin()))
900
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string")
683
901
  return;
684
902
  await fetch(origin + "/billing/v1/entitlement", {
685
903
  method: "DELETE",
@@ -710,58 +928,20 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
710
928
  return;
711
929
  telemetryTimer = setTimeout(() => {
712
930
  telemetryTimer = void 0;
713
- void (async () => {
714
- if (disposed || !pendingEvents.size)
715
- return;
716
- let origin;
717
- try {
718
- origin = billingOrigin(getOrigin());
719
- } catch {
720
- return;
721
- }
722
- if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
723
- if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
724
- return;
725
- const customHome = process.env.INKMAP_HOME || "";
726
- if (customHome && (customHome.startsWith("/tmp/") || customHome.startsWith("/private/tmp/") || customHome.includes("/var/folders/") || customHome.includes("inkmap-npm-isolated-") || customHome.includes("inkmap-antigravity-mcp-") || customHome.includes("inkmap-local-editor-") || customHome.includes("inkmap-harness-"))) {
727
- return;
728
- }
729
- }
730
- const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
731
- if (disposed || !id || !pendingEvents.size)
732
- return;
733
- await (trial ??= startTrial());
734
- const events = {};
735
- for (const [k, v] of pendingEvents.entries())
736
- events[k] = v;
737
- pendingEvents.clear();
738
- const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
739
- const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
740
- const hostName = detectedHost || inferNodeHost();
741
- await fetch(origin + "/billing/v1/telemetry", {
742
- method: "POST",
743
- headers: { "content-type": "application/json" },
744
- redirect: "error",
745
- body: JSON.stringify({
746
- product: PRODUCT.id,
747
- installId: id,
748
- host: hostName,
749
- os,
750
- version: "0.3.8",
751
- locale: clientLocale(),
752
- tier,
753
- events
754
- }),
755
- signal: AbortSignal.timeout(5e3)
756
- }).catch(() => {
757
- });
758
- })();
931
+ void sendPendingTelemetry();
759
932
  }, 800);
760
933
  telemetryTimer.unref();
761
934
  },
935
+ async flushTelemetry() {
936
+ if (telemetryTimer) {
937
+ clearTimeout(telemetryTimer);
938
+ telemetryTimer = void 0;
939
+ }
940
+ await sendPendingTelemetry();
941
+ },
762
942
  dispose() {
763
943
  disposed = true;
764
- stopMagicPoll();
944
+ clearWaiting();
765
945
  clearTimeout(trialTimer);
766
946
  clearTimeout(timer);
767
947
  clearTimeout(telemetryTimer);
@@ -781,35 +961,47 @@ function inferNodeHost() {
781
961
  return "cursor";
782
962
  if (app.includes("windsurf"))
783
963
  return "windsurf";
964
+ if (app.includes("trae"))
965
+ return "trae";
966
+ if (app.includes("qoder"))
967
+ return "qoder";
784
968
  return "vscode";
785
969
  }
786
970
  return "cli";
787
971
  }
788
- async function localInstallId() {
789
- const path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "install-id");
790
- let value;
972
+ async function atomicCreateIfMissing(path, initialContent) {
791
973
  try {
792
- value = (await readFile(path, "utf8")).trim();
974
+ return await readFile(path, "utf8");
793
975
  } catch (error) {
794
976
  if (error.code !== "ENOENT")
795
977
  throw error;
796
978
  await mkdir(dirname(path), { recursive: true, mode: 448 });
797
- const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
798
979
  const temporary = path + "." + randomUUID();
799
980
  try {
800
- await writeFile(temporary, generated, { mode: 384, flag: "wx" });
801
- await link(temporary, path).catch((err) => {
802
- if (err.code !== "EEXIST")
803
- throw err;
981
+ await writeFile(temporary, initialContent, { mode: 384, flag: "wx" });
982
+ await link(temporary, path).catch(async (err) => {
983
+ if (err.code === "EEXIST")
984
+ return;
985
+ if (err.code === "EPERM" || err.code === "ENOSYS" || err.code === "EXDEV") {
986
+ await rename(temporary, path);
987
+ return;
988
+ }
989
+ throw err;
804
990
  });
805
991
  } finally {
806
- await rm(temporary, { force: true });
992
+ await rm(temporary, { force: true }).catch(() => {
993
+ });
807
994
  }
808
- value = (await readFile(path, "utf8")).trim();
995
+ return await readFile(path, "utf8");
809
996
  }
997
+ }
998
+ async function localInstallId() {
999
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "install-id");
1000
+ const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
1001
+ const value = (await atomicCreateIfMissing(path, generated)).trim();
810
1002
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
811
1003
  }
812
- function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "billing-session")) {
1004
+ function fileSessionStorage(path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "billing-session")) {
813
1005
  return {
814
1006
  read: () => readFile(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
815
1007
  async write(token) {
@@ -827,40 +1019,26 @@ function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(
827
1019
  };
828
1020
  }
829
1021
  async function localTrialDeadline() {
830
- const path = join(homedir(), ".inkmap", "trial-start");
831
- const now = Date.now();
832
- let value;
833
- try {
834
- value = await readFile(path, "utf8");
835
- } catch (error) {
836
- if (error.code !== "ENOENT")
837
- throw error;
838
- await mkdir(dirname(path), { recursive: true, mode: 448 });
839
- const temporary = path + "." + randomUUID();
840
- try {
841
- await writeFile(temporary, String(now), { mode: 384, flag: "wx" });
842
- await link(temporary, path).catch((error2) => {
843
- if (error2.code !== "EEXIST")
844
- throw error2;
845
- });
846
- } finally {
847
- await rm(temporary, { force: true });
848
- }
849
- value = await readFile(path, "utf8");
850
- }
1022
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "trial-start");
1023
+ const value = await atomicCreateIfMissing(path, String(Date.now()));
851
1024
  const started = Number(value);
852
1025
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
853
1026
  }
854
- var AD_TTL = 6 * 60 * 60 * 1e3;
855
1027
 
856
1028
  // packages/cli/dist/server.js
857
1029
  import { spawn } from "node:child_process";
858
1030
  import { createHash, randomBytes } from "node:crypto";
859
1031
  import { watch } from "node:fs";
860
- import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, realpath, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
1032
+ import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, realpath as realpath2, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
861
1033
  import { createServer } from "node:http";
1034
+ import { homedir as homedir3 } from "node:os";
1035
+ import { basename as basename2, delimiter as delimiter2, dirname as dirname3, extname, join as join3, normalize, relative as relative2, resolve as resolve2, sep as sep3 } from "node:path";
1036
+
1037
+ // packages/cli/dist/workspace-fs.js
1038
+ import { lstat, readdir, readFile as readFile2, realpath } from "node:fs/promises";
862
1039
  import { homedir as homedir2 } from "node:os";
863
- import { basename, delimiter, dirname as dirname2, extname, isAbsolute, join as join2, normalize, relative, resolve, sep } from "node:path";
1040
+ import { basename, delimiter, dirname as dirname2, isAbsolute, join as join2, posix, relative, resolve, sep as sep2, win32 } from "node:path";
1041
+ var MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
864
1042
  var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
865
1043
  ".git",
866
1044
  ".hg",
@@ -883,15 +1061,22 @@ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
883
1061
  "coverage",
884
1062
  ".tmp"
885
1063
  ]);
886
- function insideRoot(root, target) {
1064
+ var MARKMAP_RE = /\.markmap\.md$/i;
1065
+ function insideOrEqual(root, target) {
887
1066
  if (root === target)
888
1067
  return true;
889
1068
  const rel = relative(root, target);
890
- return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep));
1069
+ return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep2));
1070
+ }
1071
+ function hasHiddenSegment(root, target) {
1072
+ const rel = relative(root, target);
1073
+ if (!rel || rel === ".")
1074
+ return false;
1075
+ return rel.split(sep2).some((part) => part.startsWith("."));
891
1076
  }
892
1077
  async function findProjectRoot(filePath) {
893
- let cur = dirname2(filePath);
894
1078
  const home = await realpath(homedir2()).catch(() => homedir2());
1079
+ let cur = dirname2(filePath);
895
1080
  while (cur && cur !== dirname2(cur) && cur !== home) {
896
1081
  try {
897
1082
  await lstat(join2(cur, ".git"));
@@ -902,7 +1087,7 @@ async function findProjectRoot(filePath) {
902
1087
  }
903
1088
  return dirname2(filePath);
904
1089
  }
905
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1090
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
906
1091
  const found = [];
907
1092
  async function walk(dir, depth) {
908
1093
  if (depth > maxDepth || found.length >= maxFiles)
@@ -924,12 +1109,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
924
1109
  await walk(full, depth + 1);
925
1110
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
926
1111
  try {
927
- const st = await lstat(full);
928
- if (st.isFile() && st.size <= 5 * 1024 * 1024) {
929
- const real = await realpath(full);
930
- if (real === full && insideRoot(rootDir, real))
931
- found.push(real);
932
- }
1112
+ const info = await lstat(full);
1113
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1114
+ continue;
1115
+ const real = await realpath(full);
1116
+ if (real === full && insideOrEqual(rootDir, real))
1117
+ found.push({ path: real, mtimeMs: info.mtimeMs });
933
1118
  } catch {
934
1119
  }
935
1120
  }
@@ -937,14 +1122,18 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
937
1122
  }
938
1123
  await walk(rootDir, 0);
939
1124
  found.sort((a, b) => {
940
- const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
941
- const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
942
- if (aM !== bM)
943
- return aM - bM;
944
- return a.localeCompare(b);
1125
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1126
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1127
+ if (am !== bm)
1128
+ return am - bm;
1129
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
1130
+ return b.mtimeMs - a.mtimeMs;
1131
+ return a.path.localeCompare(b.path);
945
1132
  });
946
1133
  return found;
947
1134
  }
1135
+
1136
+ // packages/cli/dist/server.js
948
1137
  var MAX_BODY = 20 * 1024 * 1024;
949
1138
  var TYPES = {
950
1139
  ".html": "text/html; charset=utf-8",
@@ -956,29 +1145,40 @@ var TYPES = {
956
1145
  ".jpeg": "image/jpeg",
957
1146
  ".gif": "image/gif",
958
1147
  ".webp": "image/webp",
1148
+ ".avif": "image/avif",
1149
+ ".bmp": "image/bmp",
1150
+ ".ico": "image/x-icon",
959
1151
  ".woff2": "font/woff2",
960
1152
  ".woff": "font/woff",
961
1153
  ".ttf": "font/ttf",
962
1154
  ".json": "application/json"
963
1155
  };
1156
+ var HttpError = class extends Error {
1157
+ status;
1158
+ constructor(status, message) {
1159
+ super(message);
1160
+ this.status = status;
1161
+ }
1162
+ };
1163
+ var LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
964
1164
  var hash = (s) => createHash("sha1").update(s).digest("hex");
965
1165
  function docName(path) {
966
- return basename(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1166
+ return basename2(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
967
1167
  }
968
1168
  function viewStateFile(key) {
969
- const base = process.env.INKMAP_HOME ?? join2(homedir2(), ".inkmap");
970
- return join2(base, "view-state", hash(key) + ".json");
1169
+ const base = process.env.INKMAP_HOME || join3(homedir3(), ".inkmap");
1170
+ return join3(base, "view-state", hash(key) + ".json");
971
1171
  }
972
1172
  async function readDiskViewState(key) {
973
1173
  try {
974
- return sanitizeViewState(JSON.parse(await readFile2(viewStateFile(key), "utf8")));
1174
+ return sanitizeViewState(JSON.parse(await readFile3(viewStateFile(key), "utf8")));
975
1175
  } catch {
976
1176
  return void 0;
977
1177
  }
978
1178
  }
979
1179
  async function writeDiskViewState(key, state) {
980
1180
  const target = viewStateFile(key);
981
- await mkdir2(dirname2(target), { recursive: true, mode: 448 });
1181
+ await mkdir2(dirname3(target), { recursive: true, mode: 448 });
982
1182
  const temp = `${target}.${process.pid}.${Date.now()}`;
983
1183
  try {
984
1184
  await writeFile2(temp, JSON.stringify(state), { mode: 384 });
@@ -990,24 +1190,26 @@ async function writeDiskViewState(key, state) {
990
1190
  }
991
1191
  async function fileSource(file, log = () => {
992
1192
  }) {
993
- const path = await realpath(resolve(file)).catch(() => resolve(file));
1193
+ const path = await realpath2(resolve2(file)).catch(() => resolve2(file));
994
1194
  if (!(await stat(path)).isFile())
995
1195
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
996
- const dir = dirname2(path);
1196
+ const dir = dirname3(path);
997
1197
  return {
998
1198
  name: docName(path),
999
1199
  key: path,
1000
1200
  dir,
1001
- read: () => readFile2(path, "utf8"),
1201
+ read: () => readFile3(path, "utf8"),
1002
1202
  async write(md) {
1003
1203
  await writeFile2(path, md, "utf8");
1004
1204
  log(`\u5DF2\u5199\u56DE ${path}`);
1005
1205
  },
1006
1206
  watch(onChange) {
1007
1207
  const watcher = watch(dir, (_, changed) => {
1008
- if (!changed || changed === basename(path))
1208
+ if (!changed || changed === basename2(path))
1009
1209
  onChange();
1010
1210
  });
1211
+ watcher.on("error", () => {
1212
+ });
1011
1213
  return () => watcher.close();
1012
1214
  },
1013
1215
  readView: () => readDiskViewState(path),
@@ -1015,8 +1217,15 @@ async function fileSource(file, log = () => {
1015
1217
  };
1016
1218
  }
1017
1219
  function within(root, rel) {
1018
- const base = root.endsWith(sep) ? root : root + sep;
1019
- const full = normalize(join2(root, decodeURIComponent(rel)));
1220
+ let decoded;
1221
+ try {
1222
+ decoded = decodeURIComponent(rel);
1223
+ } catch {
1224
+ return null;
1225
+ }
1226
+ const resolvedRoot = resolve2(root);
1227
+ const base = resolvedRoot.endsWith(sep3) ? resolvedRoot : resolvedRoot + sep3;
1228
+ const full = normalize(join3(resolvedRoot, decoded));
1020
1229
  return full.startsWith(base) ? full : null;
1021
1230
  }
1022
1231
  async function openBrowserWindow(url) {
@@ -1045,7 +1254,7 @@ async function openBrowserWindow(url) {
1045
1254
  await run("xdg-open", [url]);
1046
1255
  }
1047
1256
  async function serve({ source: initialSource, webRoot: webRoot2, port = 4377, host = "127.0.0.1", log = () => {
1048
- }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false, workspaceRoots = [] }) {
1257
+ }, license, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, ideWorkspace = false, workspaceRoots = [], confineToWorkspaceRoots = false, openSource = (path) => fileSource(path, log), allowPurchase = true }) {
1049
1258
  if (sidebar && host !== "127.0.0.1")
1050
1259
  throw new Error("The sidebar bridge requires loopback.");
1051
1260
  const prefix2 = sidebar ? `/s/${randomBytes(24).toString("hex")}/` : "/";
@@ -1056,7 +1265,9 @@ async function serve({ source: initialSource, webRoot: webRoot2, port = 4377, ho
1056
1265
  let version = hash(current);
1057
1266
  let viewState = await activeSource.readView?.();
1058
1267
  const clients = /* @__PURE__ */ new Set();
1059
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1268
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1269
+ const allowedHosts = /* @__PURE__ */ new Set();
1270
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1060
1271
  const docState = () => ({
1061
1272
  name: activeSource.name,
1062
1273
  md: current,
@@ -1091,36 +1302,36 @@ data: ${JSON.stringify(data)}
1091
1302
  broadcast();
1092
1303
  }
1093
1304
  let pending;
1094
- let unwatch = activeSource.watch(() => {
1305
+ const scheduleRefresh = () => {
1095
1306
  clearTimeout(pending);
1096
- pending = setTimeout(async () => {
1097
- void serialized(refresh).catch(() => {
1098
- });
1099
- }, 80);
1100
- });
1307
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1308
+ }), 80);
1309
+ };
1310
+ let unwatch = activeSource.watch(scheduleRefresh);
1311
+ const canonicalActiveKey = async () => activeSource.key ? await realpath2(activeSource.key).catch(() => activeSource.key) : void 0;
1101
1312
  async function collectWorkspaceFiles() {
1102
1313
  const roots = /* @__PURE__ */ new Map();
1103
- if (activeSource.key) {
1104
- const realKey = await realpath(activeSource.key).catch(() => activeSource.key);
1105
- const projRoot = await realpath(await findProjectRoot(realKey)).catch(() => dirname2(realKey));
1106
- roots.set(projRoot, { path: projRoot, name: basename(projRoot), active: true });
1314
+ if (activeSource.key && !confineToWorkspaceRoots) {
1315
+ const realKey = await realpath2(activeSource.key).catch(() => activeSource.key);
1316
+ const projRoot = await realpath2(await findProjectRoot(realKey)).catch(() => dirname3(realKey));
1317
+ roots.set(projRoot, { path: projRoot, name: basename2(projRoot), active: true });
1107
1318
  }
1108
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter)].filter(Boolean);
1319
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter2)].filter(Boolean);
1109
1320
  for (const raw of envRoots) {
1110
- const real = await realpath(resolve(raw)).catch(() => null);
1321
+ const real = await realpath2(resolve2(raw)).catch(() => null);
1111
1322
  if (real && !roots.has(real)) {
1112
- roots.set(real, { path: real, name: basename(real), active: roots.size === 0 });
1323
+ roots.set(real, { path: real, name: basename2(real), active: roots.size === 0 });
1113
1324
  }
1114
1325
  }
1115
1326
  const items = [];
1116
1327
  const seen = /* @__PURE__ */ new Set();
1117
1328
  for (const root of roots.values()) {
1118
- const files = await scanProjectMarkdownFiles(root.path);
1329
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1119
1330
  for (const f of files) {
1120
1331
  if (seen.has(f))
1121
1332
  continue;
1122
1333
  seen.add(f);
1123
- const rel = relative(root.path, f);
1334
+ const rel = relative2(root.path, f);
1124
1335
  items.push({
1125
1336
  path: f,
1126
1337
  label: `${root.name} / ${rel}`,
@@ -1128,43 +1339,52 @@ data: ${JSON.stringify(data)}
1128
1339
  });
1129
1340
  }
1130
1341
  }
1131
- if (activeSource.key && !seen.has(activeSource.key)) {
1342
+ const activeReal = await canonicalActiveKey();
1343
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1132
1344
  items.unshift({
1133
1345
  path: activeSource.key,
1134
- label: `${basename(activeSource.dir)} / ${basename(activeSource.key)}`,
1346
+ label: `${basename2(activeSource.dir)} / ${basename2(activeSource.key)}`,
1135
1347
  group: "active"
1136
1348
  });
1137
1349
  }
1138
1350
  return { roots: [...roots.values()], files: items };
1139
1351
  }
1140
- async function switchSourceToFile(candidatePath) {
1141
- if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1142
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1143
- }
1144
- const realTarget = await realpath(resolve(candidatePath));
1145
- const st = await lstat(realTarget);
1146
- if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1147
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1352
+ const zh = () => detectOsLocale() === "zh";
1353
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1354
+ const notMarkdown = () => new HttpError(400, zh() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1355
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath))
1356
+ throw notMarkdown();
1357
+ const resolvedCandidate = resolve2(candidatePath);
1358
+ const rawStat = await lstat2(resolvedCandidate).catch(() => null);
1359
+ const realTarget = await realpath2(resolvedCandidate).catch(() => null);
1360
+ const targetStat = realTarget ? await stat(realTarget).catch(() => null) : null;
1361
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1362
+ throw new HttpError(403, zh() ? "\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002" : "Choose a regular Markdown file up to 5 MiB.");
1148
1363
  }
1149
- const { roots } = await collectWorkspaceFiles();
1150
- if (roots.length > 0 && !roots.some((r) => insideRoot(r.path, realTarget))) {
1151
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
1364
+ if (!/\.md$/i.test(realTarget))
1365
+ throw notMarkdown();
1366
+ if (!trustCaller) {
1367
+ const { roots } = await collectWorkspaceFiles();
1368
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, realTarget));
1369
+ if (!matchedRoot) {
1370
+ throw new HttpError(403, zh() ? "\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002" : "This file is outside the current workspace.");
1371
+ }
1372
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1373
+ throw new HttpError(403, zh() ? "\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002" : "Files in hidden folders are not allowed.");
1374
+ }
1152
1375
  }
1153
- if (activeSource.key === realTarget)
1376
+ if (await canonicalActiveKey() === realTarget)
1154
1377
  return;
1378
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1379
+ const text = await next.read();
1380
+ const nextView = await next.readView?.();
1155
1381
  clearTimeout(pending);
1156
1382
  unwatch();
1157
- activeSource = await fileSource(realTarget, log);
1158
- current = await activeSource.read();
1159
- version = hash(current);
1160
- viewState = await activeSource.readView?.();
1161
- unwatch = activeSource.watch(() => {
1162
- clearTimeout(pending);
1163
- pending = setTimeout(async () => {
1164
- void serialized(refresh).catch(() => {
1165
- });
1166
- }, 80);
1167
- });
1383
+ activeSource = next;
1384
+ current = text;
1385
+ version = hash(text);
1386
+ viewState = nextView;
1387
+ unwatch = activeSource.watch(scheduleRefresh);
1168
1388
  broadcast();
1169
1389
  }
1170
1390
  const json2 = (res, status, body) => {
@@ -1177,7 +1397,7 @@ data: ${JSON.stringify(data)}
1177
1397
  req.on("data", (c) => {
1178
1398
  size += c.length;
1179
1399
  if (size > MAX_BODY) {
1180
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1400
+ fail(new HttpError(413, zh() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1181
1401
  req.destroy();
1182
1402
  } else
1183
1403
  chunks.push(c);
@@ -1192,13 +1412,20 @@ data: ${JSON.stringify(data)}
1192
1412
  const ext = extname(full).toLowerCase();
1193
1413
  if (ext === ".html") {
1194
1414
  const osLoc = detectOsLocale();
1195
- const htmlText = (await readFile2(full, "utf8")).replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1415
+ const htmlText = (await readFile3(full, "utf8")).replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1196
1416
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1197
1417
  res.end(htmlText, "utf8");
1198
1418
  return;
1199
1419
  }
1200
- const body = await readFile2(full);
1201
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1420
+ const body = await readFile3(full);
1421
+ const headers = {
1422
+ "content-type": TYPES[ext] ?? "application/octet-stream",
1423
+ "cache-control": sidebar ? "no-store" : "no-cache"
1424
+ };
1425
+ if (ext === ".svg") {
1426
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
1427
+ }
1428
+ res.writeHead(200, headers);
1202
1429
  res.end(body);
1203
1430
  } catch {
1204
1431
  json2(res, 404, { error: "not found" });
@@ -1207,18 +1434,27 @@ data: ${JSON.stringify(data)}
1207
1434
  const server = createServer(async (req, res) => {
1208
1435
  try {
1209
1436
  const url = new URL(req.url ?? "/", "http://localhost");
1437
+ const reqHost = req.headers.host ?? "";
1438
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1210
1439
  if (sidebar) {
1211
1440
  res.setHeader("Referrer-Policy", "no-referrer");
1212
1441
  res.setHeader("X-Content-Type-Options", "nosniff");
1213
1442
  res.setHeader("Cache-Control", "no-store");
1214
1443
  res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; base-uri 'none'; form-action 'none'; object-src 'none'");
1215
- if (req.headers.host !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix2))
1444
+ if (reqHost !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix2))
1216
1445
  return json2(res, 404, { error: "not found" });
1217
1446
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1218
1447
  return json2(res, 403, { error: "forbidden" });
1219
1448
  }
1220
1449
  url.pathname = "/" + url.pathname.slice(prefix2.length);
1450
+ } else if (!hostAllowed) {
1451
+ return json2(res, 403, { error: "forbidden" });
1221
1452
  }
1453
+ const sameOriginWrite = () => {
1454
+ const origin = req.headers.origin;
1455
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
1456
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
1457
+ };
1222
1458
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1223
1459
  res.writeHead(302, { Location: "/" + url.search });
1224
1460
  return res.end();
@@ -1242,6 +1478,8 @@ data: ${JSON.stringify(data)}
1242
1478
  });
1243
1479
  }
1244
1480
  if (url.pathname === "/api/view" && req.method === "PUT") {
1481
+ if (!sameOriginWrite())
1482
+ return json2(res, 403, { error: "forbidden" });
1245
1483
  const cleaned = sanitizeViewState(JSON.parse(await readBody2(req)));
1246
1484
  if (cleaned) {
1247
1485
  viewState = cleaned;
@@ -1251,9 +1489,11 @@ data: ${JSON.stringify(data)}
1251
1489
  return json2(res, 200, { ok: true });
1252
1490
  }
1253
1491
  if (url.pathname === "/api/doc" && req.method === "PUT") {
1492
+ if (!sameOriginWrite())
1493
+ return json2(res, 403, { error: "forbidden" });
1254
1494
  const { md, baseVersion } = JSON.parse(await readBody2(req));
1255
1495
  if (typeof md !== "string")
1256
- return json2(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1496
+ return json2(res, 400, { error: zh() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1257
1497
  if (!hasAccess(await license?.state() ?? { pro: false }))
1258
1498
  return json2(res, 403, { error: "Inkmap trial expired" });
1259
1499
  return await serialized(async () => {
@@ -1265,31 +1505,24 @@ data: ${JSON.stringify(data)}
1265
1505
  current = md;
1266
1506
  version = hash(md);
1267
1507
  license?.track?.("doc_edit");
1268
- if (sidebar)
1269
- broadcast();
1508
+ broadcast();
1270
1509
  }
1271
1510
  return json2(res, 200, { version });
1272
1511
  });
1273
1512
  }
1274
1513
  if (url.pathname === "/api/license" && req.method === "GET")
1275
1514
  return json2(res, 200, await license?.state() ?? { pro: false });
1276
- const sameOriginPost = () => {
1277
- const origin = req.headers.origin;
1278
- const reqHost = req.headers.host;
1279
- const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1280
- return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1281
- };
1282
1515
  if (url.pathname === "/api/open" && req.method === "POST") {
1283
- if (!sameOriginPost())
1516
+ if (!sameOriginWrite())
1284
1517
  return json2(res, 403, { error: "forbidden" });
1285
1518
  const { file } = JSON.parse(await readBody2(req));
1286
- await serialized(() => switchSourceToFile(String(file ?? "")));
1519
+ await serialized(() => switchSourceToFile(String(file ?? ""), false));
1287
1520
  license?.track?.("doc_open");
1288
1521
  const { files } = await collectWorkspaceFiles();
1289
1522
  return json2(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1290
1523
  }
1291
1524
  if (url.pathname === "/api/telemetry" && req.method === "POST") {
1292
- if (!sameOriginPost())
1525
+ if (!sameOriginWrite())
1293
1526
  return json2(res, 403, { error: "forbidden" });
1294
1527
  const { event } = JSON.parse(await readBody2(req));
1295
1528
  if (typeof event === "string" && event)
@@ -1297,45 +1530,43 @@ data: ${JSON.stringify(data)}
1297
1530
  return json2(res, 200, { ok: true });
1298
1531
  }
1299
1532
  if (url.pathname === "/api/open-browser" && req.method === "POST") {
1300
- if (!sameOriginPost())
1533
+ if (!sameOriginWrite())
1301
1534
  return json2(res, 403, { error: "forbidden" });
1302
1535
  if (license && !hasAccess(await license.state())) {
1303
1536
  return json2(res, 402, { error: detectOsLocale() === "zh" ? "\u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u5148\u89E3\u9501\u6216\u6062\u590D Pro\u3002" : "Trial expired. Unlock or restore Pro first." });
1304
1537
  }
1305
1538
  license?.track?.("feature_browser");
1306
1539
  if (!sidebar) {
1307
- const directUrl = `http://${host}:${bound}/`;
1540
+ const directUrl = `http://${urlHost}:${bound}/`;
1308
1541
  await openBrowserWindow(directUrl);
1309
1542
  return json2(res, 200, { ok: true, url: directUrl });
1310
1543
  }
1311
1544
  if (!browserCompanion) {
1312
- browserCompanion = (async () => {
1313
- const src = activeSource.key ? await fileSource(activeSource.key) : activeSource;
1314
- return serve({
1315
- source: src,
1316
- webRoot: webRoot2,
1317
- host: "127.0.0.1",
1318
- port: 0,
1319
- license,
1320
- ads,
1321
- sidebar: false,
1322
- loginOnly: false,
1323
- workspaceRoots
1324
- });
1325
- })();
1545
+ browserCompanion = serve({
1546
+ source: activeSource,
1547
+ webRoot: webRoot2,
1548
+ host: "127.0.0.1",
1549
+ port: 0,
1550
+ license,
1551
+ sidebar: false,
1552
+ workspaceRoots,
1553
+ confineToWorkspaceRoots,
1554
+ openSource,
1555
+ allowPurchase: canPurchase
1556
+ });
1326
1557
  browserCompanion.catch(() => {
1327
1558
  browserCompanion = null;
1328
1559
  });
1329
1560
  }
1330
1561
  const companion = await browserCompanion;
1331
1562
  if (activeSource.key)
1332
- await companion.switchToFile?.(activeSource.key).catch(() => {
1563
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1333
1564
  });
1334
1565
  await openBrowserWindow(companion.url);
1335
1566
  return json2(res, 200, { ok: true, url: companion.url });
1336
1567
  }
1337
1568
  if (url.pathname === "/api/checkout" && req.method === "POST") {
1338
- if (!sameOriginPost())
1569
+ if (!sameOriginWrite())
1339
1570
  return json2(res, 403, { error: "forbidden" });
1340
1571
  const { mode, locale } = JSON.parse(await readBody2(req));
1341
1572
  if (mode !== "buy" && mode !== "restore")
@@ -1347,7 +1578,7 @@ data: ${JSON.stringify(data)}
1347
1578
  return json2(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1348
1579
  }
1349
1580
  if (url.pathname === "/api/order-pro" && req.method === "POST") {
1350
- if (!sameOriginPost())
1581
+ if (!sameOriginWrite())
1351
1582
  return json2(res, 403, { error: "forbidden" });
1352
1583
  if (!canPurchase)
1353
1584
  return json2(res, 403, { error: "forbidden" });
@@ -1359,7 +1590,7 @@ data: ${JSON.stringify(data)}
1359
1590
  return json2(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1360
1591
  }
1361
1592
  if (url.pathname === "/api/phone-send" && req.method === "POST") {
1362
- if (!sameOriginPost())
1593
+ if (!sameOriginWrite())
1363
1594
  return json2(res, 403, { error: "forbidden" });
1364
1595
  if (!license || typeof license.sendPhoneCode !== "function")
1365
1596
  return json2(res, 501, { fallback: true });
@@ -1367,21 +1598,21 @@ data: ${JSON.stringify(data)}
1367
1598
  return json2(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1368
1599
  }
1369
1600
  if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1370
- if (!sameOriginPost())
1601
+ if (!sameOriginWrite())
1371
1602
  return json2(res, 403, { error: "forbidden" });
1372
1603
  if (!license || typeof license.signInByPhone !== "function")
1373
1604
  return json2(res, 501, { fallback: true });
1374
- const { phone, code } = JSON.parse(await readBody2(req));
1375
- return json2(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
1605
+ const { phone, code, locale } = JSON.parse(await readBody2(req));
1606
+ return json2(res, 200, {
1607
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
1608
+ });
1376
1609
  }
1377
1610
  if (url.pathname === "/api/signout" && req.method === "POST") {
1378
- if (!sameOriginPost())
1611
+ if (!sameOriginWrite())
1379
1612
  return json2(res, 403, { error: "forbidden" });
1380
1613
  await license?.deactivate();
1381
1614
  return json2(res, 200, await license?.state() ?? { pro: false });
1382
1615
  }
1383
- if (url.pathname === "/api/ads")
1384
- return json2(res, 200, sidebar ? [] : await ads?.() ?? []);
1385
1616
  if (url.pathname === "/api/events") {
1386
1617
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1387
1618
  res.write(": connected\n\n");
@@ -1393,17 +1624,21 @@ data: ${JSON.stringify(data)}
1393
1624
  return void res.writeHead(204).end();
1394
1625
  if (url.pathname.startsWith("/doc-assets/")) {
1395
1626
  let asset = within(activeSource.dir, url.pathname.slice("/doc-assets/".length));
1396
- if (sidebar && asset) {
1397
- const root = await realpath(activeSource.dir);
1398
- asset = await realpath(asset).catch(() => null);
1399
- if (asset && (!asset.startsWith(root + sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset)))
1627
+ if (asset) {
1628
+ const root = await realpath2(activeSource.dir).catch(() => null);
1629
+ asset = await realpath2(asset).catch(() => null);
1630
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
1631
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset))
1400
1632
  asset = null;
1401
1633
  }
1402
1634
  return sendFile(res, asset);
1403
1635
  }
1404
1636
  return sendFile(res, within(webRoot2, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1405
1637
  } catch (err) {
1406
- json2(res, 500, { error: err instanceof Error ? err.message : String(err) });
1638
+ if (res.headersSent)
1639
+ return void res.end();
1640
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
1641
+ json2(res, status, { error: err instanceof Error ? err.message : String(err) });
1407
1642
  }
1408
1643
  });
1409
1644
  const listen = (p) => new Promise((ok, fail) => {
@@ -1414,15 +1649,26 @@ data: ${JSON.stringify(data)}
1414
1649
  });
1415
1650
  });
1416
1651
  try {
1417
- bound = await listen(port);
1652
+ try {
1653
+ bound = await listen(port);
1654
+ } catch (err) {
1655
+ if (err.code !== "EADDRINUSE")
1656
+ throw err;
1657
+ bound = await listen(0);
1658
+ }
1418
1659
  } catch (err) {
1419
- if (err.code !== "EADDRINUSE")
1420
- throw err;
1421
- bound = await listen(0);
1660
+ clearTimeout(pending);
1661
+ unwatch();
1662
+ unlisten();
1663
+ throw err;
1422
1664
  }
1423
1665
  return {
1424
- url: `http://${host}:${bound}${prefix2}`,
1425
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1666
+ url: `http://${urlHost}:${bound}${prefix2}`,
1667
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
1668
+ allowHost: (extraHost) => {
1669
+ if (extraHost)
1670
+ allowedHosts.add(extraHost.toLowerCase());
1671
+ },
1426
1672
  close: () => new Promise((done) => {
1427
1673
  clearTimeout(pending);
1428
1674
  unwatch();
@@ -1473,18 +1719,33 @@ async function workspaceFile(ctx, address) {
1473
1719
  if (typeof hostPath !== "string") throw new FileUnavailable();
1474
1720
  const roundTrip = fs.processPathFromHostPath(hostPath);
1475
1721
  if (roundTrip === void 0 || (await fs.resolve(roundTrip)).targetKey !== target.targetKey) throw new FileUnavailable();
1476
- return realpath2(hostPath);
1722
+ return realpath3(hostPath);
1477
1723
  };
1478
1724
  const [root, path] = await Promise.all([local(header.cwd), local(file.path)]);
1479
- const child = relative2(root, path);
1480
- if (!child || isAbsolute2(child) || child === ".." || child.startsWith(".." + sep2) || !/\.md$/i.test(path)) {
1725
+ const child = relative3(root, path);
1726
+ if (!child || isAbsolute2(child) || child === ".." || child.startsWith(".." + sep4) || !/\.md$/i.test(path)) {
1481
1727
  throw new FileUnavailable();
1482
1728
  }
1483
1729
  return { root, path };
1484
1730
  }
1485
1731
  async function assertFile(path) {
1486
- const info = await lstat2(path);
1487
- if (!info.isFile() || info.size > maxBytes || await realpath2(path) !== path) throw new FileUnavailable();
1732
+ const info = await lstat3(path);
1733
+ if (!info.isFile() || info.size > maxBytes || await realpath3(path) !== path) throw new FileUnavailable();
1734
+ }
1735
+ async function confinedSource(path) {
1736
+ const source = await fileSource(path);
1737
+ return {
1738
+ ...source,
1739
+ read: async () => {
1740
+ await assertFile(path);
1741
+ return source.read();
1742
+ },
1743
+ write: async (md) => {
1744
+ if (Buffer.byteLength(md) > maxBytes) throw new FileUnavailable();
1745
+ await assertFile(path);
1746
+ return source.write(md);
1747
+ }
1748
+ };
1488
1749
  }
1489
1750
  function json(res, status, body) {
1490
1751
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
@@ -1504,8 +1765,11 @@ async function readBody(req) {
1504
1765
  return null;
1505
1766
  }
1506
1767
  }
1768
+ var LEASE_TIMEOUT_MS = 15 * 6e4;
1769
+ var LEASE_SWEEP_MS = 5 * 6e4;
1507
1770
  function apply(ctx) {
1508
- const license = licenseService(fileSessionStorage(), () => YUNFAN_BILLING_ORIGIN);
1771
+ const license = licenseService(fileSessionStorage(), () => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN, { host: "deepseek" });
1772
+ license.track?.("plugin_activate", 1, "deepseek");
1509
1773
  const editors = /* @__PURE__ */ new Map();
1510
1774
  const leases = /* @__PURE__ */ new Map();
1511
1775
  let disposed = false;
@@ -1514,6 +1778,18 @@ function apply(ctx) {
1514
1778
  return editor.server.then((server) => server.close(), () => {
1515
1779
  });
1516
1780
  }
1781
+ function releaseLease(id) {
1782
+ const lease = leases.get(id);
1783
+ if (!lease) return;
1784
+ leases.delete(id);
1785
+ const editor = editors.get(lease.path);
1786
+ if (editor && --editor.users === 0) return closeEditor(lease.path, editor);
1787
+ }
1788
+ const sweep = setInterval(() => {
1789
+ const cutoff = Date.now() - LEASE_TIMEOUT_MS;
1790
+ for (const [id, lease] of leases) if (lease.seen < cutoff) void releaseLease(id);
1791
+ }, LEASE_SWEEP_MS);
1792
+ sweep.unref?.();
1517
1793
  ctx.effect(() => {
1518
1794
  const unregister = ctx.webServer.register({
1519
1795
  kind: "exact",
@@ -1529,18 +1805,21 @@ function apply(ctx) {
1529
1805
  const body = await readBody(req).catch(() => null);
1530
1806
  if (!body || typeof body !== "object") return json(res, 400, {});
1531
1807
  if (req.method === "DELETE") {
1532
- const path = leases.get(body?.lease);
1533
- if (path === void 0) return json(res, 200, {});
1534
- leases.delete(body.lease);
1535
- const editor = editors.get(path);
1536
- if (editor && --editor.users === 0) await closeEditor(path, editor);
1808
+ await releaseLease(body?.lease);
1809
+ return json(res, 200, {});
1810
+ }
1811
+ if (body.action === "renew") {
1812
+ const lease = leases.get(body.lease);
1813
+ if (disposed || !lease) return json(res, 404, {});
1814
+ lease.seen = Date.now();
1537
1815
  return json(res, 200, {});
1538
1816
  }
1539
1817
  if (body.action === "sign-in" || body.action === "buy") {
1540
1818
  if (disposed || !leases.has(body.lease)) return json(res, 404, {});
1541
1819
  try {
1542
1820
  const mode = body.action === "buy" ? "buy" : "restore";
1543
- return json(res, 200, { url: await license.connect(mode) });
1821
+ const locale = typeof body.locale === "string" ? body.locale : void 0;
1822
+ return json(res, 200, { url: await license.connect(mode, locale) });
1544
1823
  } catch {
1545
1824
  return json(res, 502, {});
1546
1825
  }
@@ -1551,27 +1830,21 @@ function apply(ctx) {
1551
1830
  if (disposed) return json(res, 503, {});
1552
1831
  let editor = editors.get(path);
1553
1832
  if (!editor) {
1554
- const server2 = fileSource(path).then((source) => serve({
1555
- source: {
1556
- ...source,
1557
- workspaceRoot: root,
1558
- read: async () => {
1559
- await assertFile(path);
1560
- return source.read();
1561
- },
1562
- write: async (md) => {
1563
- if (Buffer.byteLength(md) > maxBytes) throw new FileUnavailable();
1564
- await assertFile(path);
1565
- return source.write(md);
1566
- }
1567
- },
1833
+ const server2 = confinedSource(path).then((source) => serve({
1834
+ source,
1568
1835
  webRoot,
1569
1836
  license,
1570
1837
  port: 0,
1571
1838
  sidebar: true,
1572
1839
  sidebarPurchase: true,
1573
1840
  sidebarAccountNavigation: true,
1574
- workspaceRoots: [root]
1841
+ // Stay inside the session's working directory, even when a .git folder sits above it.
1842
+ workspaceRoots: [root],
1843
+ confineToWorkspaceRoots: true,
1844
+ openSource: async (next) => {
1845
+ await assertFile(next);
1846
+ return confinedSource(next);
1847
+ }
1575
1848
  }));
1576
1849
  editor = { users: 0, server: server2 };
1577
1850
  editors.set(path, editor);
@@ -1579,11 +1852,20 @@ function apply(ctx) {
1579
1852
  if (editors.get(path)?.server === server2) editors.delete(path);
1580
1853
  });
1581
1854
  }
1582
- const server = await editor.server;
1583
- if (disposed) return json(res, 503, {});
1584
- const lease = randomUUID2();
1585
- leases.set(lease, path);
1586
1855
  editor.users++;
1856
+ let server;
1857
+ try {
1858
+ server = await editor.server;
1859
+ } catch (err) {
1860
+ if (--editor.users === 0) void closeEditor(path, editor);
1861
+ throw err;
1862
+ }
1863
+ if (disposed) {
1864
+ if (--editor.users === 0) void closeEditor(path, editor);
1865
+ return json(res, 503, {});
1866
+ }
1867
+ const lease = randomUUID2();
1868
+ leases.set(lease, { path, seen: Date.now() });
1587
1869
  return json(res, 200, { url: server.url, lease });
1588
1870
  } catch (error) {
1589
1871
  const unavailable = error instanceof FileUnavailable || ["ENOENT", "EACCES", "EPERM"].includes(error?.code);
@@ -1593,6 +1875,7 @@ function apply(ctx) {
1593
1875
  });
1594
1876
  return () => {
1595
1877
  disposed = true;
1878
+ clearInterval(sweep);
1596
1879
  unregister();
1597
1880
  license.dispose();
1598
1881
  leases.clear();