inkmap-mcp 0.3.10 → 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.
@@ -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,48 +410,134 @@ 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)
361
472
  return;
362
- magicPollTimer = setTimeout(async () => {
363
- if (disposed || id !== magicSession)
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)
478
+ return;
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);
397
541
  }
398
542
  async function sendPendingTelemetry() {
399
543
  if (disposed || !pendingEvents.size)
@@ -408,7 +552,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
408
552
  if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
409
553
  return;
410
554
  const customHome = process.env.INKMAP_HOME || "";
411
- 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-"))) {
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-"))) {
412
557
  return;
413
558
  }
414
559
  }
@@ -432,7 +577,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
432
577
  installId: id,
433
578
  host: hostName,
434
579
  os,
435
- version: "0.3.10",
580
+ version: INKMAP_VERSION,
436
581
  locale: clientLocale(),
437
582
  tier,
438
583
  events
@@ -444,13 +589,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
444
589
  return {
445
590
  async state() {
446
591
  await (trial ??= startTrial());
447
- if (Date.now() - lastCheck >= 4e3)
592
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
593
+ if (Date.now() - lastCheck >= interval)
448
594
  await refresh();
595
+ await parkUnpaidSession();
449
596
  return current;
450
597
  },
451
598
  async connect(mode, localeHint) {
452
599
  if (loginOnly && mode !== "restore")
453
600
  throw new Error("Only Yunfan account sign-in is available.");
601
+ expectPurchase();
454
602
  const origin = billingOrigin(getOrigin());
455
603
  const loc = clientLocale(localeHint);
456
604
  const version = generation;
@@ -492,7 +640,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
492
640
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
493
641
  throw new Error("The Yunfan account session changed. Please try again.");
494
642
  }
495
- 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 } }));
496
645
  ++generation;
497
646
  lastCheck = 0;
498
647
  if (mode !== "buy" || !current.connected)
@@ -504,8 +653,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
504
653
  async orderPro(localeHint) {
505
654
  if (loginOnly)
506
655
  throw new Error("Only Yunfan account sign-in is available.");
656
+ expectPurchase();
507
657
  const origin = billingOrigin(getOrigin());
508
- 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) {
509
660
  const hit = cachedOrder.result;
510
661
  cachedOrder = void 0;
511
662
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -531,7 +682,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
531
682
  await writeSession(async () => {
532
683
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
533
684
  return;
534
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
685
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
535
686
  if (persist) {
536
687
  ++generation;
537
688
  lastCheck = 0;
@@ -580,34 +731,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
580
731
  async sendPhoneCode(phone, localeHint) {
581
732
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254)
582
733
  return phoneFailure(400);
734
+ expectPurchase();
583
735
  const isEmail = phone.includes("@");
584
736
  const locale = clientLocale(localeHint);
585
737
  try {
586
738
  const origin = billingOrigin(getOrigin());
587
739
  if (!loginOnly) {
588
740
  try {
589
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
590
- 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;
591
748
  }
592
749
  const sendAction = isEmail ? "email/send" : "sms";
593
750
  const sendBody = isEmail ? { email: phone, locale } : { phone };
594
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
595
- if (smsRes.status === 410 || smsRes.status === 404) {
596
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
597
- 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);
598
756
  }
599
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
600
- 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 };
601
762
  } catch {
602
763
  pendingCheckout = void 0;
603
764
  }
604
765
  }
605
766
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
606
767
  if (response.status === 204) {
768
+ await rememberSignIn(phone);
607
769
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
608
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
609
- startMagicPoll(origin, pendingToken);
610
- }
770
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken))
771
+ await waitFor(origin, pendingToken, phone);
611
772
  return { ok: true, value: void 0 };
612
773
  }
613
774
  return phoneFailure(response.status);
@@ -615,41 +776,47 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
615
776
  return phoneFailure();
616
777
  }
617
778
  },
618
- async signInByPhone(phone, code) {
779
+ async signInByPhone(phone, code, localeHint) {
619
780
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code))
620
781
  return phoneFailure(400);
621
782
  const isEmail = phone.includes("@");
783
+ const locale = clientLocale(localeHint);
622
784
  const version = generation;
623
785
  try {
624
786
  const origin = billingOrigin(getOrigin());
625
787
  let token;
626
788
  let checkoutUrl;
627
789
  let cookie;
628
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
790
+ const flow = pendingCheckout;
791
+ if (!loginOnly && flow && flow.origin === origin) {
629
792
  const verifyAction = isEmail ? "email/verify" : "login";
630
793
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
631
- 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);
632
795
  if (!loginRes.ok) {
633
- if (loginRes.status === 410 || loginRes.status === 404)
634
- 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
+ }
635
800
  return phoneFailure(loginRes.status);
636
801
  }
637
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
638
- token = pendingCheckout.token;
639
- checkoutUrl = pendingCheckout.url;
640
- pendingCheckout = void 0;
641
- 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);
642
808
  if (orderRes?.ok) {
643
809
  cookie = mergeCookies(cookie, orderRes);
644
810
  const orderData = await orderRes.json().catch(() => null);
645
811
  if (orderData && typeof orderData === "object") {
646
812
  if (orderData.active === true) {
647
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
813
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
648
814
  } else if (typeof orderData.qr === "string" && orderData.qr) {
649
815
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
650
816
  cachedOrder = {
651
817
  at: Date.now(),
652
818
  origin,
819
+ locale,
653
820
  result: {
654
821
  status: "qr",
655
822
  qr,
@@ -658,12 +825,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
658
825
  }
659
826
  };
660
827
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
661
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
828
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
662
829
  }
663
830
  }
664
831
  }
665
832
  } else {
666
- const response = await phoneRequest(origin, "verify", phone, code);
833
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
667
834
  if (response.status !== 201)
668
835
  return phoneFailure(response.status);
669
836
  cookie = mergeCookies(void 0, response);
@@ -691,11 +858,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
691
858
  }
692
859
  if (cachedOrder?.result.status === "active")
693
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
+ }
694
866
  return await writeSession(async () => {
695
867
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
696
868
  return phoneFailure();
697
- stopMagicPoll();
698
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
869
+ clearWaiting();
870
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
699
871
  ++generation;
700
872
  activeOrigin = origin;
701
873
  applyEntitlement(state);
@@ -709,12 +881,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
709
881
  }
710
882
  },
711
883
  async deactivate() {
712
- stopMagicPoll();
884
+ clearWaiting();
713
885
  pendingCheckout = void 0;
714
886
  cachedOrder = void 0;
715
887
  const saved = await writeSession(async () => {
716
888
  const previous = await storage.read();
717
- await storage.write(void 0);
889
+ await storage.write(signedOutRecord());
718
890
  ++generation;
719
891
  clearTimeout(timer);
720
892
  lastCheck = 0;
@@ -725,7 +897,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
725
897
  return;
726
898
  try {
727
899
  const { origin, token } = JSON.parse(saved);
728
- if (origin !== billingOrigin(getOrigin()))
900
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string")
729
901
  return;
730
902
  await fetch(origin + "/billing/v1/entitlement", {
731
903
  method: "DELETE",
@@ -769,7 +941,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
769
941
  },
770
942
  dispose() {
771
943
  disposed = true;
772
- stopMagicPoll();
944
+ clearWaiting();
773
945
  clearTimeout(trialTimer);
774
946
  clearTimeout(timer);
775
947
  clearTimeout(telemetryTimer);
@@ -797,31 +969,39 @@ function inferNodeHost() {
797
969
  }
798
970
  return "cli";
799
971
  }
800
- async function localInstallId() {
801
- const path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "install-id");
802
- let value;
972
+ async function atomicCreateIfMissing(path, initialContent) {
803
973
  try {
804
- value = (await readFile(path, "utf8")).trim();
974
+ return await readFile(path, "utf8");
805
975
  } catch (error) {
806
976
  if (error.code !== "ENOENT")
807
977
  throw error;
808
978
  await mkdir(dirname(path), { recursive: true, mode: 448 });
809
- const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
810
979
  const temporary = path + "." + randomUUID();
811
980
  try {
812
- await writeFile(temporary, generated, { mode: 384, flag: "wx" });
813
- await link(temporary, path).catch((err) => {
814
- if (err.code !== "EEXIST")
815
- 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;
816
990
  });
817
991
  } finally {
818
- await rm(temporary, { force: true });
992
+ await rm(temporary, { force: true }).catch(() => {
993
+ });
819
994
  }
820
- value = (await readFile(path, "utf8")).trim();
995
+ return await readFile(path, "utf8");
821
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();
822
1002
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
823
1003
  }
824
- 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")) {
825
1005
  return {
826
1006
  read: () => readFile(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
827
1007
  async write(token) {
@@ -839,40 +1019,26 @@ function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(
839
1019
  };
840
1020
  }
841
1021
  async function localTrialDeadline() {
842
- const path = join(homedir(), ".inkmap", "trial-start");
843
- const now = Date.now();
844
- let value;
845
- try {
846
- value = await readFile(path, "utf8");
847
- } catch (error) {
848
- if (error.code !== "ENOENT")
849
- throw error;
850
- await mkdir(dirname(path), { recursive: true, mode: 448 });
851
- const temporary = path + "." + randomUUID();
852
- try {
853
- await writeFile(temporary, String(now), { mode: 384, flag: "wx" });
854
- await link(temporary, path).catch((error2) => {
855
- if (error2.code !== "EEXIST")
856
- throw error2;
857
- });
858
- } finally {
859
- await rm(temporary, { force: true });
860
- }
861
- value = await readFile(path, "utf8");
862
- }
1022
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "trial-start");
1023
+ const value = await atomicCreateIfMissing(path, String(Date.now()));
863
1024
  const started = Number(value);
864
1025
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
865
1026
  }
866
- var AD_TTL = 6 * 60 * 60 * 1e3;
867
1027
 
868
1028
  // packages/cli/dist/server.js
869
1029
  import { spawn } from "node:child_process";
870
1030
  import { createHash, randomBytes } from "node:crypto";
871
1031
  import { watch } from "node:fs";
872
- 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";
873
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";
874
1039
  import { homedir as homedir2 } from "node:os";
875
- 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;
876
1042
  var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
877
1043
  ".git",
878
1044
  ".hg",
@@ -895,15 +1061,22 @@ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
895
1061
  "coverage",
896
1062
  ".tmp"
897
1063
  ]);
898
- function insideRoot(root, target) {
1064
+ var MARKMAP_RE = /\.markmap\.md$/i;
1065
+ function insideOrEqual(root, target) {
899
1066
  if (root === target)
900
1067
  return true;
901
1068
  const rel = relative(root, target);
902
- 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("."));
903
1076
  }
904
1077
  async function findProjectRoot(filePath) {
905
- let cur = dirname2(filePath);
906
1078
  const home = await realpath(homedir2()).catch(() => homedir2());
1079
+ let cur = dirname2(filePath);
907
1080
  while (cur && cur !== dirname2(cur) && cur !== home) {
908
1081
  try {
909
1082
  await lstat(join2(cur, ".git"));
@@ -914,7 +1087,7 @@ async function findProjectRoot(filePath) {
914
1087
  }
915
1088
  return dirname2(filePath);
916
1089
  }
917
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1090
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
918
1091
  const found = [];
919
1092
  async function walk(dir, depth) {
920
1093
  if (depth > maxDepth || found.length >= maxFiles)
@@ -936,12 +1109,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
936
1109
  await walk(full, depth + 1);
937
1110
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
938
1111
  try {
939
- const st = await lstat(full);
940
- if (st.isFile() && st.size <= 5 * 1024 * 1024) {
941
- const real = await realpath(full);
942
- if (real === full && insideRoot(rootDir, real))
943
- found.push(real);
944
- }
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 });
945
1118
  } catch {
946
1119
  }
947
1120
  }
@@ -949,14 +1122,18 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
949
1122
  }
950
1123
  await walk(rootDir, 0);
951
1124
  found.sort((a, b) => {
952
- const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
953
- const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
954
- if (aM !== bM)
955
- return aM - bM;
956
- 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);
957
1132
  });
958
1133
  return found;
959
1134
  }
1135
+
1136
+ // packages/cli/dist/server.js
960
1137
  var MAX_BODY = 20 * 1024 * 1024;
961
1138
  var TYPES = {
962
1139
  ".html": "text/html; charset=utf-8",
@@ -968,29 +1145,40 @@ var TYPES = {
968
1145
  ".jpeg": "image/jpeg",
969
1146
  ".gif": "image/gif",
970
1147
  ".webp": "image/webp",
1148
+ ".avif": "image/avif",
1149
+ ".bmp": "image/bmp",
1150
+ ".ico": "image/x-icon",
971
1151
  ".woff2": "font/woff2",
972
1152
  ".woff": "font/woff",
973
1153
  ".ttf": "font/ttf",
974
1154
  ".json": "application/json"
975
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;
976
1164
  var hash = (s) => createHash("sha1").update(s).digest("hex");
977
1165
  function docName(path) {
978
- return basename(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1166
+ return basename2(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
979
1167
  }
980
1168
  function viewStateFile(key) {
981
- const base = process.env.INKMAP_HOME ?? join2(homedir2(), ".inkmap");
982
- 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");
983
1171
  }
984
1172
  async function readDiskViewState(key) {
985
1173
  try {
986
- return sanitizeViewState(JSON.parse(await readFile2(viewStateFile(key), "utf8")));
1174
+ return sanitizeViewState(JSON.parse(await readFile3(viewStateFile(key), "utf8")));
987
1175
  } catch {
988
1176
  return void 0;
989
1177
  }
990
1178
  }
991
1179
  async function writeDiskViewState(key, state) {
992
1180
  const target = viewStateFile(key);
993
- await mkdir2(dirname2(target), { recursive: true, mode: 448 });
1181
+ await mkdir2(dirname3(target), { recursive: true, mode: 448 });
994
1182
  const temp = `${target}.${process.pid}.${Date.now()}`;
995
1183
  try {
996
1184
  await writeFile2(temp, JSON.stringify(state), { mode: 384 });
@@ -1002,24 +1190,26 @@ async function writeDiskViewState(key, state) {
1002
1190
  }
1003
1191
  async function fileSource(file, log = () => {
1004
1192
  }) {
1005
- const path = await realpath(resolve(file)).catch(() => resolve(file));
1193
+ const path = await realpath2(resolve2(file)).catch(() => resolve2(file));
1006
1194
  if (!(await stat(path)).isFile())
1007
1195
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
1008
- const dir = dirname2(path);
1196
+ const dir = dirname3(path);
1009
1197
  return {
1010
1198
  name: docName(path),
1011
1199
  key: path,
1012
1200
  dir,
1013
- read: () => readFile2(path, "utf8"),
1201
+ read: () => readFile3(path, "utf8"),
1014
1202
  async write(md) {
1015
1203
  await writeFile2(path, md, "utf8");
1016
1204
  log(`\u5DF2\u5199\u56DE ${path}`);
1017
1205
  },
1018
1206
  watch(onChange) {
1019
1207
  const watcher = watch(dir, (_, changed) => {
1020
- if (!changed || changed === basename(path))
1208
+ if (!changed || changed === basename2(path))
1021
1209
  onChange();
1022
1210
  });
1211
+ watcher.on("error", () => {
1212
+ });
1023
1213
  return () => watcher.close();
1024
1214
  },
1025
1215
  readView: () => readDiskViewState(path),
@@ -1027,8 +1217,15 @@ async function fileSource(file, log = () => {
1027
1217
  };
1028
1218
  }
1029
1219
  function within(root, rel) {
1030
- const base = root.endsWith(sep) ? root : root + sep;
1031
- 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));
1032
1229
  return full.startsWith(base) ? full : null;
1033
1230
  }
1034
1231
  async function openBrowserWindow(url) {
@@ -1057,7 +1254,7 @@ async function openBrowserWindow(url) {
1057
1254
  await run("xdg-open", [url]);
1058
1255
  }
1059
1256
  async function serve({ source: initialSource, webRoot: webRoot2, port = 4377, host = "127.0.0.1", log = () => {
1060
- }, 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 }) {
1061
1258
  if (sidebar && host !== "127.0.0.1")
1062
1259
  throw new Error("The sidebar bridge requires loopback.");
1063
1260
  const prefix2 = sidebar ? `/s/${randomBytes(24).toString("hex")}/` : "/";
@@ -1068,7 +1265,9 @@ async function serve({ source: initialSource, webRoot: webRoot2, port = 4377, ho
1068
1265
  let version = hash(current);
1069
1266
  let viewState = await activeSource.readView?.();
1070
1267
  const clients = /* @__PURE__ */ new Set();
1071
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1268
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1269
+ const allowedHosts = /* @__PURE__ */ new Set();
1270
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1072
1271
  const docState = () => ({
1073
1272
  name: activeSource.name,
1074
1273
  md: current,
@@ -1103,36 +1302,36 @@ data: ${JSON.stringify(data)}
1103
1302
  broadcast();
1104
1303
  }
1105
1304
  let pending;
1106
- let unwatch = activeSource.watch(() => {
1305
+ const scheduleRefresh = () => {
1107
1306
  clearTimeout(pending);
1108
- pending = setTimeout(async () => {
1109
- void serialized(refresh).catch(() => {
1110
- });
1111
- }, 80);
1112
- });
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;
1113
1312
  async function collectWorkspaceFiles() {
1114
1313
  const roots = /* @__PURE__ */ new Map();
1115
- if (activeSource.key) {
1116
- const realKey = await realpath(activeSource.key).catch(() => activeSource.key);
1117
- const projRoot = await realpath(await findProjectRoot(realKey)).catch(() => dirname2(realKey));
1118
- 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 });
1119
1318
  }
1120
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter)].filter(Boolean);
1319
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter2)].filter(Boolean);
1121
1320
  for (const raw of envRoots) {
1122
- const real = await realpath(resolve(raw)).catch(() => null);
1321
+ const real = await realpath2(resolve2(raw)).catch(() => null);
1123
1322
  if (real && !roots.has(real)) {
1124
- 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 });
1125
1324
  }
1126
1325
  }
1127
1326
  const items = [];
1128
1327
  const seen = /* @__PURE__ */ new Set();
1129
1328
  for (const root of roots.values()) {
1130
- const files = await scanProjectMarkdownFiles(root.path);
1329
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1131
1330
  for (const f of files) {
1132
1331
  if (seen.has(f))
1133
1332
  continue;
1134
1333
  seen.add(f);
1135
- const rel = relative(root.path, f);
1334
+ const rel = relative2(root.path, f);
1136
1335
  items.push({
1137
1336
  path: f,
1138
1337
  label: `${root.name} / ${rel}`,
@@ -1140,43 +1339,52 @@ data: ${JSON.stringify(data)}
1140
1339
  });
1141
1340
  }
1142
1341
  }
1143
- if (activeSource.key && !seen.has(activeSource.key)) {
1342
+ const activeReal = await canonicalActiveKey();
1343
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1144
1344
  items.unshift({
1145
1345
  path: activeSource.key,
1146
- label: `${basename(activeSource.dir)} / ${basename(activeSource.key)}`,
1346
+ label: `${basename2(activeSource.dir)} / ${basename2(activeSource.key)}`,
1147
1347
  group: "active"
1148
1348
  });
1149
1349
  }
1150
1350
  return { roots: [...roots.values()], files: items };
1151
1351
  }
1152
- async function switchSourceToFile(candidatePath) {
1153
- if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1154
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \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.");
1155
1363
  }
1156
- const realTarget = await realpath(resolve(candidatePath));
1157
- const st = await lstat(realTarget);
1158
- if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1159
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1160
- }
1161
- const { roots } = await collectWorkspaceFiles();
1162
- if (roots.length > 0 && !roots.some((r) => insideRoot(r.path, realTarget))) {
1163
- 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
+ }
1164
1375
  }
1165
- if (activeSource.key === realTarget)
1376
+ if (await canonicalActiveKey() === realTarget)
1166
1377
  return;
1378
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1379
+ const text = await next.read();
1380
+ const nextView = await next.readView?.();
1167
1381
  clearTimeout(pending);
1168
1382
  unwatch();
1169
- activeSource = await fileSource(realTarget, log);
1170
- current = await activeSource.read();
1171
- version = hash(current);
1172
- viewState = await activeSource.readView?.();
1173
- unwatch = activeSource.watch(() => {
1174
- clearTimeout(pending);
1175
- pending = setTimeout(async () => {
1176
- void serialized(refresh).catch(() => {
1177
- });
1178
- }, 80);
1179
- });
1383
+ activeSource = next;
1384
+ current = text;
1385
+ version = hash(text);
1386
+ viewState = nextView;
1387
+ unwatch = activeSource.watch(scheduleRefresh);
1180
1388
  broadcast();
1181
1389
  }
1182
1390
  const json2 = (res, status, body) => {
@@ -1189,7 +1397,7 @@ data: ${JSON.stringify(data)}
1189
1397
  req.on("data", (c) => {
1190
1398
  size += c.length;
1191
1399
  if (size > MAX_BODY) {
1192
- 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."));
1193
1401
  req.destroy();
1194
1402
  } else
1195
1403
  chunks.push(c);
@@ -1204,13 +1412,20 @@ data: ${JSON.stringify(data)}
1204
1412
  const ext = extname(full).toLowerCase();
1205
1413
  if (ext === ".html") {
1206
1414
  const osLoc = detectOsLocale();
1207
- 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}">`);
1208
1416
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1209
1417
  res.end(htmlText, "utf8");
1210
1418
  return;
1211
1419
  }
1212
- const body = await readFile2(full);
1213
- 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);
1214
1429
  res.end(body);
1215
1430
  } catch {
1216
1431
  json2(res, 404, { error: "not found" });
@@ -1219,18 +1434,27 @@ data: ${JSON.stringify(data)}
1219
1434
  const server = createServer(async (req, res) => {
1220
1435
  try {
1221
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());
1222
1439
  if (sidebar) {
1223
1440
  res.setHeader("Referrer-Policy", "no-referrer");
1224
1441
  res.setHeader("X-Content-Type-Options", "nosniff");
1225
1442
  res.setHeader("Cache-Control", "no-store");
1226
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'");
1227
- 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))
1228
1445
  return json2(res, 404, { error: "not found" });
1229
1446
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1230
1447
  return json2(res, 403, { error: "forbidden" });
1231
1448
  }
1232
1449
  url.pathname = "/" + url.pathname.slice(prefix2.length);
1450
+ } else if (!hostAllowed) {
1451
+ return json2(res, 403, { error: "forbidden" });
1233
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
+ };
1234
1458
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1235
1459
  res.writeHead(302, { Location: "/" + url.search });
1236
1460
  return res.end();
@@ -1254,6 +1478,8 @@ data: ${JSON.stringify(data)}
1254
1478
  });
1255
1479
  }
1256
1480
  if (url.pathname === "/api/view" && req.method === "PUT") {
1481
+ if (!sameOriginWrite())
1482
+ return json2(res, 403, { error: "forbidden" });
1257
1483
  const cleaned = sanitizeViewState(JSON.parse(await readBody2(req)));
1258
1484
  if (cleaned) {
1259
1485
  viewState = cleaned;
@@ -1263,9 +1489,11 @@ data: ${JSON.stringify(data)}
1263
1489
  return json2(res, 200, { ok: true });
1264
1490
  }
1265
1491
  if (url.pathname === "/api/doc" && req.method === "PUT") {
1492
+ if (!sameOriginWrite())
1493
+ return json2(res, 403, { error: "forbidden" });
1266
1494
  const { md, baseVersion } = JSON.parse(await readBody2(req));
1267
1495
  if (typeof md !== "string")
1268
- 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." });
1269
1497
  if (!hasAccess(await license?.state() ?? { pro: false }))
1270
1498
  return json2(res, 403, { error: "Inkmap trial expired" });
1271
1499
  return await serialized(async () => {
@@ -1277,31 +1505,24 @@ data: ${JSON.stringify(data)}
1277
1505
  current = md;
1278
1506
  version = hash(md);
1279
1507
  license?.track?.("doc_edit");
1280
- if (sidebar)
1281
- broadcast();
1508
+ broadcast();
1282
1509
  }
1283
1510
  return json2(res, 200, { version });
1284
1511
  });
1285
1512
  }
1286
1513
  if (url.pathname === "/api/license" && req.method === "GET")
1287
1514
  return json2(res, 200, await license?.state() ?? { pro: false });
1288
- const sameOriginPost = () => {
1289
- const origin = req.headers.origin;
1290
- const reqHost = req.headers.host;
1291
- const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1292
- return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1293
- };
1294
1515
  if (url.pathname === "/api/open" && req.method === "POST") {
1295
- if (!sameOriginPost())
1516
+ if (!sameOriginWrite())
1296
1517
  return json2(res, 403, { error: "forbidden" });
1297
1518
  const { file } = JSON.parse(await readBody2(req));
1298
- await serialized(() => switchSourceToFile(String(file ?? "")));
1519
+ await serialized(() => switchSourceToFile(String(file ?? ""), false));
1299
1520
  license?.track?.("doc_open");
1300
1521
  const { files } = await collectWorkspaceFiles();
1301
1522
  return json2(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1302
1523
  }
1303
1524
  if (url.pathname === "/api/telemetry" && req.method === "POST") {
1304
- if (!sameOriginPost())
1525
+ if (!sameOriginWrite())
1305
1526
  return json2(res, 403, { error: "forbidden" });
1306
1527
  const { event } = JSON.parse(await readBody2(req));
1307
1528
  if (typeof event === "string" && event)
@@ -1309,45 +1530,43 @@ data: ${JSON.stringify(data)}
1309
1530
  return json2(res, 200, { ok: true });
1310
1531
  }
1311
1532
  if (url.pathname === "/api/open-browser" && req.method === "POST") {
1312
- if (!sameOriginPost())
1533
+ if (!sameOriginWrite())
1313
1534
  return json2(res, 403, { error: "forbidden" });
1314
1535
  if (license && !hasAccess(await license.state())) {
1315
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." });
1316
1537
  }
1317
1538
  license?.track?.("feature_browser");
1318
1539
  if (!sidebar) {
1319
- const directUrl = `http://${host}:${bound}/`;
1540
+ const directUrl = `http://${urlHost}:${bound}/`;
1320
1541
  await openBrowserWindow(directUrl);
1321
1542
  return json2(res, 200, { ok: true, url: directUrl });
1322
1543
  }
1323
1544
  if (!browserCompanion) {
1324
- browserCompanion = (async () => {
1325
- const src = activeSource.key ? await fileSource(activeSource.key) : activeSource;
1326
- return serve({
1327
- source: src,
1328
- webRoot: webRoot2,
1329
- host: "127.0.0.1",
1330
- port: 0,
1331
- license,
1332
- ads,
1333
- sidebar: false,
1334
- loginOnly: false,
1335
- workspaceRoots
1336
- });
1337
- })();
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
+ });
1338
1557
  browserCompanion.catch(() => {
1339
1558
  browserCompanion = null;
1340
1559
  });
1341
1560
  }
1342
1561
  const companion = await browserCompanion;
1343
1562
  if (activeSource.key)
1344
- await companion.switchToFile?.(activeSource.key).catch(() => {
1563
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1345
1564
  });
1346
1565
  await openBrowserWindow(companion.url);
1347
1566
  return json2(res, 200, { ok: true, url: companion.url });
1348
1567
  }
1349
1568
  if (url.pathname === "/api/checkout" && req.method === "POST") {
1350
- if (!sameOriginPost())
1569
+ if (!sameOriginWrite())
1351
1570
  return json2(res, 403, { error: "forbidden" });
1352
1571
  const { mode, locale } = JSON.parse(await readBody2(req));
1353
1572
  if (mode !== "buy" && mode !== "restore")
@@ -1359,7 +1578,7 @@ data: ${JSON.stringify(data)}
1359
1578
  return json2(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1360
1579
  }
1361
1580
  if (url.pathname === "/api/order-pro" && req.method === "POST") {
1362
- if (!sameOriginPost())
1581
+ if (!sameOriginWrite())
1363
1582
  return json2(res, 403, { error: "forbidden" });
1364
1583
  if (!canPurchase)
1365
1584
  return json2(res, 403, { error: "forbidden" });
@@ -1371,7 +1590,7 @@ data: ${JSON.stringify(data)}
1371
1590
  return json2(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1372
1591
  }
1373
1592
  if (url.pathname === "/api/phone-send" && req.method === "POST") {
1374
- if (!sameOriginPost())
1593
+ if (!sameOriginWrite())
1375
1594
  return json2(res, 403, { error: "forbidden" });
1376
1595
  if (!license || typeof license.sendPhoneCode !== "function")
1377
1596
  return json2(res, 501, { fallback: true });
@@ -1379,21 +1598,21 @@ data: ${JSON.stringify(data)}
1379
1598
  return json2(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1380
1599
  }
1381
1600
  if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1382
- if (!sameOriginPost())
1601
+ if (!sameOriginWrite())
1383
1602
  return json2(res, 403, { error: "forbidden" });
1384
1603
  if (!license || typeof license.signInByPhone !== "function")
1385
1604
  return json2(res, 501, { fallback: true });
1386
- const { phone, code } = JSON.parse(await readBody2(req));
1387
- 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
+ });
1388
1609
  }
1389
1610
  if (url.pathname === "/api/signout" && req.method === "POST") {
1390
- if (!sameOriginPost())
1611
+ if (!sameOriginWrite())
1391
1612
  return json2(res, 403, { error: "forbidden" });
1392
1613
  await license?.deactivate();
1393
1614
  return json2(res, 200, await license?.state() ?? { pro: false });
1394
1615
  }
1395
- if (url.pathname === "/api/ads")
1396
- return json2(res, 200, sidebar ? [] : await ads?.() ?? []);
1397
1616
  if (url.pathname === "/api/events") {
1398
1617
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1399
1618
  res.write(": connected\n\n");
@@ -1405,17 +1624,21 @@ data: ${JSON.stringify(data)}
1405
1624
  return void res.writeHead(204).end();
1406
1625
  if (url.pathname.startsWith("/doc-assets/")) {
1407
1626
  let asset = within(activeSource.dir, url.pathname.slice("/doc-assets/".length));
1408
- if (sidebar && asset) {
1409
- const root = await realpath(activeSource.dir);
1410
- asset = await realpath(asset).catch(() => null);
1411
- 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))
1412
1632
  asset = null;
1413
1633
  }
1414
1634
  return sendFile(res, asset);
1415
1635
  }
1416
1636
  return sendFile(res, within(webRoot2, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1417
1637
  } catch (err) {
1418
- 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) });
1419
1642
  }
1420
1643
  });
1421
1644
  const listen = (p) => new Promise((ok, fail) => {
@@ -1426,15 +1649,26 @@ data: ${JSON.stringify(data)}
1426
1649
  });
1427
1650
  });
1428
1651
  try {
1429
- 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
+ }
1430
1659
  } catch (err) {
1431
- if (err.code !== "EADDRINUSE")
1432
- throw err;
1433
- bound = await listen(0);
1660
+ clearTimeout(pending);
1661
+ unwatch();
1662
+ unlisten();
1663
+ throw err;
1434
1664
  }
1435
1665
  return {
1436
- url: `http://${host}:${bound}${prefix2}`,
1437
- 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
+ },
1438
1672
  close: () => new Promise((done) => {
1439
1673
  clearTimeout(pending);
1440
1674
  unwatch();
@@ -1485,18 +1719,33 @@ async function workspaceFile(ctx, address) {
1485
1719
  if (typeof hostPath !== "string") throw new FileUnavailable();
1486
1720
  const roundTrip = fs.processPathFromHostPath(hostPath);
1487
1721
  if (roundTrip === void 0 || (await fs.resolve(roundTrip)).targetKey !== target.targetKey) throw new FileUnavailable();
1488
- return realpath2(hostPath);
1722
+ return realpath3(hostPath);
1489
1723
  };
1490
1724
  const [root, path] = await Promise.all([local(header.cwd), local(file.path)]);
1491
- const child = relative2(root, path);
1492
- 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)) {
1493
1727
  throw new FileUnavailable();
1494
1728
  }
1495
1729
  return { root, path };
1496
1730
  }
1497
1731
  async function assertFile(path) {
1498
- const info = await lstat2(path);
1499
- 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
+ };
1500
1749
  }
1501
1750
  function json(res, status, body) {
1502
1751
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
@@ -1516,8 +1765,10 @@ async function readBody(req) {
1516
1765
  return null;
1517
1766
  }
1518
1767
  }
1768
+ var LEASE_TIMEOUT_MS = 15 * 6e4;
1769
+ var LEASE_SWEEP_MS = 5 * 6e4;
1519
1770
  function apply(ctx) {
1520
- const license = licenseService(fileSessionStorage(), () => YUNFAN_BILLING_ORIGIN, { host: "deepseek" });
1771
+ const license = licenseService(fileSessionStorage(), () => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN, { host: "deepseek" });
1521
1772
  license.track?.("plugin_activate", 1, "deepseek");
1522
1773
  const editors = /* @__PURE__ */ new Map();
1523
1774
  const leases = /* @__PURE__ */ new Map();
@@ -1527,6 +1778,18 @@ function apply(ctx) {
1527
1778
  return editor.server.then((server) => server.close(), () => {
1528
1779
  });
1529
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?.();
1530
1793
  ctx.effect(() => {
1531
1794
  const unregister = ctx.webServer.register({
1532
1795
  kind: "exact",
@@ -1542,18 +1805,21 @@ function apply(ctx) {
1542
1805
  const body = await readBody(req).catch(() => null);
1543
1806
  if (!body || typeof body !== "object") return json(res, 400, {});
1544
1807
  if (req.method === "DELETE") {
1545
- const path = leases.get(body?.lease);
1546
- if (path === void 0) return json(res, 200, {});
1547
- leases.delete(body.lease);
1548
- const editor = editors.get(path);
1549
- 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();
1550
1815
  return json(res, 200, {});
1551
1816
  }
1552
1817
  if (body.action === "sign-in" || body.action === "buy") {
1553
1818
  if (disposed || !leases.has(body.lease)) return json(res, 404, {});
1554
1819
  try {
1555
1820
  const mode = body.action === "buy" ? "buy" : "restore";
1556
- 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) });
1557
1823
  } catch {
1558
1824
  return json(res, 502, {});
1559
1825
  }
@@ -1564,27 +1830,21 @@ function apply(ctx) {
1564
1830
  if (disposed) return json(res, 503, {});
1565
1831
  let editor = editors.get(path);
1566
1832
  if (!editor) {
1567
- const server2 = fileSource(path).then((source) => serve({
1568
- source: {
1569
- ...source,
1570
- workspaceRoot: root,
1571
- read: async () => {
1572
- await assertFile(path);
1573
- return source.read();
1574
- },
1575
- write: async (md) => {
1576
- if (Buffer.byteLength(md) > maxBytes) throw new FileUnavailable();
1577
- await assertFile(path);
1578
- return source.write(md);
1579
- }
1580
- },
1833
+ const server2 = confinedSource(path).then((source) => serve({
1834
+ source,
1581
1835
  webRoot,
1582
1836
  license,
1583
1837
  port: 0,
1584
1838
  sidebar: true,
1585
1839
  sidebarPurchase: true,
1586
1840
  sidebarAccountNavigation: true,
1587
- 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
+ }
1588
1848
  }));
1589
1849
  editor = { users: 0, server: server2 };
1590
1850
  editors.set(path, editor);
@@ -1592,11 +1852,20 @@ function apply(ctx) {
1592
1852
  if (editors.get(path)?.server === server2) editors.delete(path);
1593
1853
  });
1594
1854
  }
1595
- const server = await editor.server;
1596
- if (disposed) return json(res, 503, {});
1597
- const lease = randomUUID2();
1598
- leases.set(lease, path);
1599
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() });
1600
1869
  return json(res, 200, { url: server.url, lease });
1601
1870
  } catch (error) {
1602
1871
  const unavailable = error instanceof FileUnavailable || ["ENOENT", "EACCES", "EPERM"].includes(error?.code);
@@ -1606,6 +1875,7 @@ function apply(ctx) {
1606
1875
  });
1607
1876
  return () => {
1608
1877
  disposed = true;
1878
+ clearInterval(sweep);
1609
1879
  unregister();
1610
1880
  license.dispose();
1611
1881
  leases.clear();