inkmap-mcp 0.3.10 → 0.3.13

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.
@@ -38,9 +38,7 @@ module.exports = __toCommonJS(extension_exports);
38
38
  // packages/core/dist/product.js
39
39
  var PRODUCT = {
40
40
  id: "inkmap-pro",
41
- entitlement: "inkmap.pro",
42
- /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
43
- adFeedUrl: ""
41
+ entitlement: "inkmap.pro"
44
42
  };
45
43
  var YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
46
44
  function billingFlowUrl(raw, origin, mode, legacy = false) {
@@ -58,24 +56,6 @@ var TRIAL_MS = 7 * DAY_MS;
58
56
  function hasAccess(state, now = Date.now()) {
59
57
  return state.pro || (state.trialUntil ?? 0) > now;
60
58
  }
61
- function sanitizeAds(input) {
62
- if (!Array.isArray(input))
63
- return [];
64
- const str = (v, max) => typeof v === "string" && v.trim() ? v.trim().slice(0, max) : void 0;
65
- const out = [];
66
- for (const raw of input.slice(0, 20)) {
67
- const r = raw;
68
- const id = str(r?.id, 64);
69
- const title = str(r?.title, 60);
70
- const text = str(r?.text, 140);
71
- const url = str(r?.url, 500);
72
- if (!id || !title || !text || !url || !/^https:\/\//.test(url))
73
- continue;
74
- const locale = r.locale === "zh" || r.locale === "en" ? r.locale : void 0;
75
- out.push({ id, title, text, url, cta: str(r.cta, 20), locale });
76
- }
77
- return out;
78
- }
79
59
 
80
60
  // packages/core/dist/index.js
81
61
  function sanitizeViewState(raw) {
@@ -105,10 +85,23 @@ function sanitizeViewState(raw) {
105
85
  // packages/vscode/src/extension.ts
106
86
  var import_node_child_process4 = require("node:child_process");
107
87
  var import_node_fs2 = require("node:fs");
108
- var import_promises4 = require("node:fs/promises");
88
+ var import_promises5 = require("node:fs/promises");
89
+ var import_node_os4 = require("node:os");
90
+ var import_node_path4 = require("node:path");
91
+ var vscode5 = __toESM(require("vscode"));
92
+
93
+ // packages/vscode/src/browser.ts
94
+ var import_node_child_process3 = require("node:child_process");
95
+ var vscode2 = __toESM(require("vscode"));
96
+
97
+ // packages/cli/src/server.ts
98
+ var import_node_child_process2 = require("node:child_process");
99
+ var import_node_crypto2 = require("node:crypto");
100
+ var import_node_fs = require("node:fs");
101
+ var import_promises3 = require("node:fs/promises");
102
+ var import_node_http = require("node:http");
109
103
  var import_node_os3 = require("node:os");
110
104
  var import_node_path3 = require("node:path");
111
- var vscode5 = __toESM(require("vscode"));
112
105
 
113
106
  // packages/cli/src/license.ts
114
107
  var import_node_child_process = require("node:child_process");
@@ -116,47 +109,75 @@ var import_promises = require("node:fs/promises");
116
109
  var import_node_crypto = require("node:crypto");
117
110
  var import_node_os = require("node:os");
118
111
  var import_node_path = require("node:path");
112
+
113
+ // packages/cli/src/version.ts
114
+ var INKMAP_VERSION = "0.3.13";
115
+
116
+ // packages/cli/src/license.ts
117
+ var ZH_LOCALE_RE = /^zh(?:[-_.]|$)/i;
118
+ var EN_LOCALE_RE = /^en(?:[-_.]|$)/i;
119
119
  var cachedOsLocale;
120
- function detectOsLocale() {
121
- const explicit = (process.env.INKMAP_LOCALE || "").trim();
122
- if (/^zh\b/i.test(explicit)) return "zh";
123
- if (/^en\b/i.test(explicit)) return "en";
124
- if (cachedOsLocale) return cachedOsLocale;
125
- let domestic = false;
126
- try {
127
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
128
- if (/^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i.test(tz)) {
129
- domestic = true;
120
+ var WAIT_FAST_MS = 2500;
121
+ var WAIT_SLOW_MS = 3e4;
122
+ var WAIT_FAST_FOR_MS = 30 * 6e4;
123
+ var WAIT_MAX_MS = 3 * 24 * 60 * 6e4;
124
+ var MAX_WAITING = 5;
125
+ function isWaitingToken(value) {
126
+ const w = value;
127
+ 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";
128
+ }
129
+ var DOMESTIC_TIME_ZONE = /^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i;
130
+ function parseAppleLanguages(output) {
131
+ const match = /^\(\s*(?:"([^"]+)"|([^\s,)]+))/m.exec(output);
132
+ return match?.[1] ?? match?.[2] ?? "";
133
+ }
134
+ var posixLocale = (env5) => (env5.LC_ALL || env5.LC_MESSAGES || env5.LANG || "").trim();
135
+ function resolveOsLocale(probe) {
136
+ const explicit = (probe.env.INKMAP_LOCALE || "").trim();
137
+ if (ZH_LOCALE_RE.test(explicit)) return "zh";
138
+ if (EN_LOCALE_RE.test(explicit)) return "en";
139
+ if (DOMESTIC_TIME_ZONE.test(probe.timeZone)) return "zh";
140
+ let language = "";
141
+ if (probe.platform === "darwin") {
142
+ try {
143
+ language = parseAppleLanguages(probe.run("defaults", ["read", "-g", "AppleLanguages"]));
144
+ } catch {
145
+ language = posixLocale(probe.env);
130
146
  }
131
- } catch {
132
- }
133
- if (!domestic) {
134
- if (process.platform === "darwin") {
135
- try {
136
- const out = (0, import_node_child_process.execFileSync)("defaults", ["read", "-g", "AppleLanguages"], {
137
- encoding: "utf8",
138
- timeout: 800,
139
- stdio: ["ignore", "pipe", "ignore"]
140
- });
141
- const firstLang = /"([^"]+)"/.exec(out)?.[1] ?? "";
142
- if (/^zh\b/i.test(firstLang)) domestic = true;
143
- } catch {
144
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
145
- if (/^zh\b/i.test(raw)) domestic = true;
146
- }
147
- } else if (process.platform === "win32") {
148
- try {
149
- const loc = Intl.DateTimeFormat().resolvedOptions().locale || "";
150
- if (/^zh\b/i.test(loc)) domestic = true;
151
- } catch {
152
- }
153
- } else {
154
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
155
- if (/^zh\b/i.test(raw)) domestic = true;
147
+ } else if (probe.platform === "win32") {
148
+ try {
149
+ const output = probe.run("reg", ["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"]);
150
+ language = /LocaleName\s+REG_\w+\s+(\S+)/i.exec(output)?.[1] ?? "";
151
+ } catch {
156
152
  }
153
+ if (!language) language = probe.intlLocale;
154
+ } else {
155
+ language = posixLocale(probe.env);
156
+ }
157
+ return ZH_LOCALE_RE.test(language) ? "zh" : "en";
158
+ }
159
+ function systemLocaleProbe() {
160
+ let timeZone = "";
161
+ let intlLocale = "";
162
+ try {
163
+ const options = Intl.DateTimeFormat().resolvedOptions();
164
+ timeZone = options.timeZone || "";
165
+ intlLocale = options.locale || "";
166
+ } catch {
157
167
  }
158
- cachedOsLocale = domestic ? "zh" : "en";
159
- return cachedOsLocale;
168
+ return {
169
+ platform: process.platform,
170
+ env: process.env,
171
+ timeZone,
172
+ intlLocale,
173
+ run: (command, args) => (0, import_node_child_process.execFileSync)(command, args, { encoding: "utf8", timeout: 800, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] })
174
+ };
175
+ }
176
+ function detectOsLocale() {
177
+ const explicit = (process.env.INKMAP_LOCALE || "").trim();
178
+ if (ZH_LOCALE_RE.test(explicit)) return "zh";
179
+ if (EN_LOCALE_RE.test(explicit)) return "en";
180
+ return cachedOsLocale ??= resolveOsLocale(systemLocaleProbe());
160
181
  }
161
182
  function billingOrigin(raw) {
162
183
  if (!raw) throw new Error("Inkmap checkout is not configured.");
@@ -166,7 +187,7 @@ function billingOrigin(raw) {
166
187
  }
167
188
  return url.origin;
168
189
  }
169
- function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "" } = {}) {
190
+ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "", waitPollMs = WAIT_FAST_MS } = {}) {
170
191
  const listeners = /* @__PURE__ */ new Set();
171
192
  let current = { pro: false };
172
193
  let trial;
@@ -178,6 +199,9 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
178
199
  let detectedHost = defaultHost;
179
200
  const pendingEvents = /* @__PURE__ */ new Map();
180
201
  let lastCheck = 0;
202
+ let fastPollUntil = 0;
203
+ const expectPurchase = () => void (fastPollUntil = Date.now() + 15 * 6e4);
204
+ let flowCreation;
181
205
  let disposed = false;
182
206
  let generation = 0;
183
207
  let connection;
@@ -185,12 +209,32 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
185
209
  let pendingWrite = Promise.resolve();
186
210
  let pendingCheckout;
187
211
  let cachedOrder;
188
- let magicPollTimer;
189
- let magicSession = 0;
190
- function stopMagicPoll() {
191
- ++magicSession;
192
- clearTimeout(magicPollTimer);
193
- magicPollTimer = void 0;
212
+ let waiting = [];
213
+ let waitTimer;
214
+ let waitRound = 0;
215
+ let lastSignIn;
216
+ const sessionRecord = (fields) => JSON.stringify({ ...fields, ...lastSignIn && { lastSignIn } });
217
+ const signedOutRecord = () => lastSignIn || waiting.length ? JSON.stringify({ ...lastSignIn && { lastSignIn }, ...waiting.length && { waiting } }) : void 0;
218
+ async function rememberSignIn(id) {
219
+ const clean = id.trim().slice(0, 254);
220
+ if (!clean || clean === lastSignIn) return;
221
+ lastSignIn = clean;
222
+ current = { ...current, lastSignIn };
223
+ await writeSession(async () => {
224
+ let record = {};
225
+ try {
226
+ record = JSON.parse(await storage.read() || "{}");
227
+ } catch {
228
+ }
229
+ await storage.write(JSON.stringify({ ...record, lastSignIn }));
230
+ }).catch(() => {
231
+ });
232
+ }
233
+ function clearWaiting() {
234
+ waiting = [];
235
+ ++waitRound;
236
+ clearTimeout(waitTimer);
237
+ waitTimer = void 0;
194
238
  }
195
239
  function mergeCookies(existing, response) {
196
240
  const map = /* @__PURE__ */ new Map();
@@ -219,10 +263,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
219
263
  }
220
264
  return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
221
265
  }
222
- function clientLocale(hint) {
223
- const h = (hint || "").trim();
224
- if (/^zh\b/i.test(h)) return "zh";
225
- if (/^en\b/i.test(h)) return "en";
266
+ function clientLocale(_uiLocaleHint) {
226
267
  return detectOsLocale();
227
268
  }
228
269
  function writeSession(operation) {
@@ -253,7 +294,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
253
294
  if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
254
295
  throw new Error("Invalid Inkmap checkout response.");
255
296
  }
256
- return { origin, url, token: data.token, ...cookie && { cookie } };
297
+ return { origin, url, token: data.token, locale: loc, ...cookie && { cookie } };
257
298
  }
258
299
  function checkoutPost(checkoutUrl, action, origin, body, token, cookie, localeHint) {
259
300
  const loc = clientLocale(localeHint);
@@ -312,11 +353,25 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
312
353
  pro,
313
354
  ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
314
355
  ...connected && { connected: true },
315
- ...cleanAccount && { account: cleanAccount }
356
+ ...cleanAccount && { account: cleanAccount },
357
+ ...lastSignIn && { lastSignIn }
316
358
  };
317
359
  for (const listener of listeners) listener(current);
318
360
  }
319
361
  async function startTrial() {
362
+ try {
363
+ const record = JSON.parse(await storage.read() || "{}");
364
+ const remembered = record.lastSignIn;
365
+ if (typeof remembered === "string" && remembered.trim() && !lastSignIn) {
366
+ lastSignIn = remembered.trim().slice(0, 254);
367
+ current = { ...current, lastSignIn };
368
+ }
369
+ if (typeof record.token !== "string" && Array.isArray(record.waiting) && !waiting.length) {
370
+ waiting = record.waiting.filter(isWaitingToken).slice(-MAX_WAITING);
371
+ scheduleWait(waitPollMs);
372
+ }
373
+ } catch {
374
+ }
320
375
  const trialUntil = await localTrialDeadline().catch(() => void 0);
321
376
  if (disposed || trialUntil === void 0) return;
322
377
  current = { ...current, trialUntil };
@@ -359,7 +414,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
359
414
  token = void 0;
360
415
  return await writeSession(async () => {
361
416
  if (version !== generation || disposed) return;
362
- await storage.write(void 0).catch(() => {
417
+ await storage.write(signedOutRecord()).catch(() => {
363
418
  });
364
419
  update(false);
365
420
  });
@@ -379,43 +434,117 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
379
434
  });
380
435
  return connection;
381
436
  }
382
- function startMagicPoll(origin, pendingToken) {
383
- stopMagicPoll();
384
- const id = magicSession;
385
- const deadline = Date.now() + 10 * 6e4;
386
- const poll = () => {
387
- if (disposed || id !== magicSession || Date.now() >= deadline) return;
388
- magicPollTimer = setTimeout(async () => {
389
- if (disposed || id !== magicSession) return;
437
+ async function mustPayFirst() {
438
+ if (!loginOnly) return false;
439
+ await (trial ??= startTrial());
440
+ return current.trialUntil !== void 0 && current.trialUntil <= Date.now();
441
+ }
442
+ async function waitFor(origin, token, email) {
443
+ const now = Date.now();
444
+ const same = (other) => !other || !email || other.toLowerCase() === email.toLowerCase();
445
+ waiting = waiting.filter((w) => w.token !== token && same(w.email)).map((w) => ({ ...w, fastUntil: now + WAIT_FAST_FOR_MS }));
446
+ waiting.push({ origin, token, email, since: now, fastUntil: now + WAIT_FAST_FOR_MS });
447
+ waiting = waiting.slice(-MAX_WAITING);
448
+ scheduleWait(waitPollMs);
449
+ await writeSession(async () => {
450
+ let record = {};
451
+ try {
452
+ record = JSON.parse(await storage.read() || "{}");
453
+ } catch {
454
+ }
455
+ if (typeof record.token !== "string") await storage.write(signedOutRecord());
456
+ }).catch(() => {
457
+ });
458
+ }
459
+ function scheduleWait(delay) {
460
+ clearTimeout(waitTimer);
461
+ if (disposed || !waiting.length) return;
462
+ waitTimer = setTimeout(() => void checkWaiting(), delay);
463
+ waitTimer.unref();
464
+ }
465
+ async function checkWaiting() {
466
+ const round = ++waitRound;
467
+ const now = Date.now();
468
+ const before = waiting.length;
469
+ let origin;
470
+ try {
471
+ origin = billingOrigin(getOrigin());
472
+ } catch {
473
+ return scheduleWait(WAIT_SLOW_MS);
474
+ }
475
+ waiting = waiting.filter((w) => w.origin === origin && now - w.since < WAIT_MAX_MS);
476
+ for (const w of [...waiting]) {
477
+ let response;
478
+ try {
479
+ response = await entitlement(w.origin, w.token);
480
+ } catch {
481
+ continue;
482
+ }
483
+ if (disposed || round !== waitRound) return;
484
+ if (response.status === 401) {
485
+ waiting = waiting.filter((other) => other !== w);
486
+ continue;
487
+ }
488
+ if (!response.ok) continue;
489
+ const body = await response.json().catch(() => null);
490
+ if (disposed || round !== waitRound) return;
491
+ if (body?.connected !== true || body.entitlement !== PRODUCT.entitlement) continue;
492
+ if (body.active !== true && await mustPayFirst()) continue;
493
+ if (disposed || round !== waitRound) return;
494
+ await writeSession(async () => {
495
+ if (disposed || round !== waitRound || w.origin !== billingOrigin(getOrigin())) return;
496
+ clearWaiting();
497
+ await storage.write(sessionRecord({ origin: w.origin, token: w.token }));
498
+ ++generation;
499
+ activeOrigin = w.origin;
500
+ applyEntitlement(body);
501
+ schedule(body.active === true ? 6e4 : 2500);
502
+ });
503
+ return;
504
+ }
505
+ if (disposed || round !== waitRound) return;
506
+ if (waiting.length !== before) {
507
+ await writeSession(async () => {
508
+ let record = {};
390
509
  try {
391
- const res = await entitlement(origin, pendingToken);
392
- if (disposed || id !== magicSession) return;
393
- if (res.status === 401) {
394
- stopMagicPoll();
395
- return;
396
- }
397
- if (res.ok) {
398
- const body = await res.json();
399
- if (body?.connected === true && body.entitlement === PRODUCT.entitlement) {
400
- stopMagicPoll();
401
- await writeSession(async () => {
402
- if (disposed || origin !== billingOrigin(getOrigin())) return;
403
- await storage.write(JSON.stringify({ origin, token: pendingToken }));
404
- ++generation;
405
- activeOrigin = origin;
406
- applyEntitlement(body);
407
- schedule(body.active === true ? 6e4 : 2500);
408
- });
409
- return;
410
- }
411
- }
510
+ record = JSON.parse(await storage.read() || "{}");
412
511
  } catch {
413
512
  }
414
- if (!disposed && id === magicSession && Date.now() < deadline) poll();
415
- }, 2e3);
416
- magicPollTimer.unref();
417
- };
418
- poll();
513
+ if (typeof record.token !== "string") await storage.write(signedOutRecord());
514
+ }).catch(() => {
515
+ });
516
+ }
517
+ scheduleWait(waiting.some((w) => Date.now() < w.fastUntil) ? waitPollMs : WAIT_SLOW_MS);
518
+ }
519
+ async function parkUnpaidSession() {
520
+ if (current.pro || !current.connected || !await mustPayFirst()) return;
521
+ await writeSession(async () => {
522
+ if (current.pro || !current.connected) return;
523
+ let record = {};
524
+ try {
525
+ record = JSON.parse(await storage.read() || "{}");
526
+ } catch {
527
+ }
528
+ if (typeof record.token !== "string" || typeof record.origin !== "string") return;
529
+ const response = await entitlement(record.origin, record.token).catch(() => null);
530
+ if (!response?.ok) return;
531
+ const latest = await response.json().catch(() => null);
532
+ if (!latest || latest.active === true || latest.connected !== true) {
533
+ if (latest) applyEntitlement(latest);
534
+ return;
535
+ }
536
+ ++generation;
537
+ clearTimeout(timer);
538
+ lastCheck = 0;
539
+ const now = Date.now();
540
+ waiting = [
541
+ ...waiting.filter((w) => w.token !== record.token),
542
+ { origin: record.origin, token: record.token, email: lastSignIn ?? "", since: now, fastUntil: now + WAIT_FAST_FOR_MS }
543
+ ].slice(-MAX_WAITING);
544
+ await storage.write(signedOutRecord());
545
+ update(false);
546
+ });
547
+ scheduleWait(waitPollMs);
419
548
  }
420
549
  async function sendPendingTelemetry() {
421
550
  if (disposed || !pendingEvents.size) return;
@@ -428,7 +557,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
428
557
  if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
429
558
  if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT) return;
430
559
  const customHome = process.env.INKMAP_HOME || "";
431
- 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-"))) {
560
+ const sysTmp = (0, import_node_os.tmpdir)();
561
+ if (customHome && (customHome === sysTmp || customHome.startsWith(sysTmp + import_node_path.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-"))) {
432
562
  return;
433
563
  }
434
564
  }
@@ -450,7 +580,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
450
580
  installId: id,
451
581
  host: hostName,
452
582
  os,
453
- version: "0.3.10",
583
+ version: INKMAP_VERSION,
454
584
  locale: clientLocale(),
455
585
  tier,
456
586
  events
@@ -462,11 +592,14 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
462
592
  return {
463
593
  async state() {
464
594
  await (trial ??= startTrial());
465
- if (Date.now() - lastCheck >= 4e3) await refresh();
595
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
596
+ if (Date.now() - lastCheck >= interval) await refresh();
597
+ await parkUnpaidSession();
466
598
  return current;
467
599
  },
468
600
  async connect(mode, localeHint) {
469
601
  if (loginOnly && mode !== "restore") throw new Error("Only Yunfan account sign-in is available.");
602
+ expectPurchase();
470
603
  const origin = billingOrigin(getOrigin());
471
604
  const loc = clientLocale(localeHint);
472
605
  const version = generation;
@@ -506,7 +639,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
506
639
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
507
640
  throw new Error("The Yunfan account session changed. Please try again.");
508
641
  }
509
- await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
642
+ clearWaiting();
643
+ await storage.write(sessionRecord({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
510
644
  ++generation;
511
645
  lastCheck = 0;
512
646
  if (mode !== "buy" || !current.connected) update(false);
@@ -516,8 +650,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
516
650
  },
517
651
  async orderPro(localeHint) {
518
652
  if (loginOnly) throw new Error("Only Yunfan account sign-in is available.");
653
+ expectPurchase();
519
654
  const origin = billingOrigin(getOrigin());
520
- if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
655
+ const loc = clientLocale(localeHint);
656
+ if (cachedOrder && cachedOrder.origin === origin && cachedOrder.locale === loc && Date.now() - cachedOrder.at < 8e3) {
521
657
  const hit = cachedOrder.result;
522
658
  cachedOrder = void 0;
523
659
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -539,7 +675,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
539
675
  if (persist || nextCookie !== cookie) {
540
676
  await writeSession(async () => {
541
677
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) return;
542
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
678
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
543
679
  if (persist) {
544
680
  ++generation;
545
681
  lastCheck = 0;
@@ -583,34 +719,42 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
583
719
  },
584
720
  async sendPhoneCode(phone, localeHint) {
585
721
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254) return phoneFailure(400);
722
+ expectPurchase();
586
723
  const isEmail = phone.includes("@");
587
724
  const locale = clientLocale(localeHint);
588
725
  try {
589
726
  const origin = billingOrigin(getOrigin());
590
727
  if (!loginOnly) {
591
728
  try {
592
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
593
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
729
+ const newFlow = () => flowCreation ??= createCheckoutFlow(origin, void 0, void 0, locale).finally(() => {
730
+ flowCreation = void 0;
731
+ });
732
+ let flow = pendingCheckout;
733
+ if (!flow || flow.origin !== origin || flow.locale !== locale) {
734
+ flow = await newFlow();
735
+ pendingCheckout = flow;
594
736
  }
595
737
  const sendAction = isEmail ? "email/send" : "sms";
596
738
  const sendBody = isEmail ? { email: phone, locale } : { phone };
597
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
598
- if (smsRes.status === 410 || smsRes.status === 404) {
599
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
600
- smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
739
+ let smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
740
+ if (smsRes.status === 401 || smsRes.status === 403 || smsRes.status === 404 || smsRes.status === 410) {
741
+ flow = await newFlow();
742
+ pendingCheckout = flow;
743
+ smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
601
744
  }
602
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
603
- return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
745
+ flow.cookie = mergeCookies(flow.cookie, smsRes);
746
+ if (smsRes.status !== 204) return phoneFailure(smsRes.status);
747
+ await rememberSignIn(phone);
748
+ return { ok: true, value: void 0 };
604
749
  } catch {
605
750
  pendingCheckout = void 0;
606
751
  }
607
752
  }
608
753
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
609
754
  if (response.status === 204) {
755
+ await rememberSignIn(phone);
610
756
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
611
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
612
- startMagicPoll(origin, pendingToken);
613
- }
757
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) await waitFor(origin, pendingToken, phone);
614
758
  return { ok: true, value: void 0 };
615
759
  }
616
760
  return phoneFailure(response.status);
@@ -618,39 +762,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
618
762
  return phoneFailure();
619
763
  }
620
764
  },
621
- async signInByPhone(phone, code) {
765
+ async signInByPhone(phone, code, localeHint) {
622
766
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code)) return phoneFailure(400);
623
767
  const isEmail = phone.includes("@");
768
+ const locale = clientLocale(localeHint);
624
769
  const version = generation;
625
770
  try {
626
771
  const origin = billingOrigin(getOrigin());
627
772
  let token;
628
773
  let checkoutUrl;
629
774
  let cookie;
630
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
775
+ const flow = pendingCheckout;
776
+ if (!loginOnly && flow && flow.origin === origin) {
631
777
  const verifyAction = isEmail ? "email/verify" : "login";
632
778
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
633
- const loginRes = await checkoutPost(pendingCheckout.url, verifyAction, origin, verifyBody, pendingCheckout.token, pendingCheckout.cookie);
779
+ const loginRes = await checkoutPost(flow.url, verifyAction, origin, verifyBody, flow.token, flow.cookie, locale);
634
780
  if (!loginRes.ok) {
635
- if (loginRes.status === 410 || loginRes.status === 404) pendingCheckout = void 0;
781
+ if (loginRes.status === 401 || loginRes.status === 403 || loginRes.status === 404 || loginRes.status === 410) {
782
+ if (pendingCheckout === flow) pendingCheckout = void 0;
783
+ }
636
784
  return phoneFailure(loginRes.status);
637
785
  }
638
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
639
- token = pendingCheckout.token;
640
- checkoutUrl = pendingCheckout.url;
641
- pendingCheckout = void 0;
642
- const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
786
+ cookie = mergeCookies(flow.cookie, loginRes);
787
+ token = flow.token;
788
+ checkoutUrl = flow.url;
789
+ if (pendingCheckout === flow) pendingCheckout = void 0;
790
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie, locale).catch(() => null);
643
791
  if (orderRes?.ok) {
644
792
  cookie = mergeCookies(cookie, orderRes);
645
793
  const orderData = await orderRes.json().catch(() => null);
646
794
  if (orderData && typeof orderData === "object") {
647
795
  if (orderData.active === true) {
648
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
796
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
649
797
  } else if (typeof orderData.qr === "string" && orderData.qr) {
650
798
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
651
799
  cachedOrder = {
652
800
  at: Date.now(),
653
801
  origin,
802
+ locale,
654
803
  result: {
655
804
  status: "qr",
656
805
  qr,
@@ -659,12 +808,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
659
808
  }
660
809
  };
661
810
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
662
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
811
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
663
812
  }
664
813
  }
665
814
  }
666
815
  } else {
667
- const response = await phoneRequest(origin, "verify", phone, code);
816
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
668
817
  if (response.status !== 201) return phoneFailure(response.status);
669
818
  cookie = mergeCookies(void 0, response);
670
819
  const body = await response.json();
@@ -687,10 +836,15 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
687
836
  return phoneFailure();
688
837
  }
689
838
  if (cachedOrder?.result.status === "active") state.active = true;
839
+ if (!checkoutUrl && state.active !== true && await mustPayFirst()) {
840
+ await rememberSignIn(phone);
841
+ await waitFor(origin, token, phone);
842
+ return { ok: false, reason: "notPro" };
843
+ }
690
844
  return await writeSession(async () => {
691
845
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) return phoneFailure();
692
- stopMagicPoll();
693
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
846
+ clearWaiting();
847
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
694
848
  ++generation;
695
849
  activeOrigin = origin;
696
850
  applyEntitlement(state);
@@ -703,12 +857,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
703
857
  }
704
858
  },
705
859
  async deactivate() {
706
- stopMagicPoll();
860
+ clearWaiting();
707
861
  pendingCheckout = void 0;
708
862
  cachedOrder = void 0;
709
863
  const saved = await writeSession(async () => {
710
864
  const previous = await storage.read();
711
- await storage.write(void 0);
865
+ await storage.write(signedOutRecord());
712
866
  ++generation;
713
867
  clearTimeout(timer);
714
868
  lastCheck = 0;
@@ -718,7 +872,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
718
872
  if (!saved) return;
719
873
  try {
720
874
  const { origin, token } = JSON.parse(saved);
721
- if (origin !== billingOrigin(getOrigin())) return;
875
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string") return;
722
876
  await fetch(origin + "/billing/v1/entitlement", {
723
877
  method: "DELETE",
724
878
  headers: { authorization: "Bearer " + token },
@@ -735,7 +889,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
735
889
  track(event, count = 1, hostHint) {
736
890
  if (disposed || !event || typeof event !== "string" || count <= 0) return;
737
891
  if (hostHint) detectedHost = hostHint;
738
- if (!sentAppOpen) {
892
+ if (!sentAppOpen && !PASSIVE_TELEMETRY_EVENTS.has(event)) {
739
893
  sentAppOpen = true;
740
894
  pendingEvents.set("app_open", (pendingEvents.get("app_open") ?? 0) + 1);
741
895
  }
@@ -758,7 +912,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
758
912
  },
759
913
  dispose() {
760
914
  disposed = true;
761
- stopMagicPoll();
915
+ clearWaiting();
762
916
  clearTimeout(trialTimer);
763
917
  clearTimeout(timer);
764
918
  clearTimeout(telemetryTimer);
@@ -767,6 +921,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
767
921
  }
768
922
  };
769
923
  }
924
+ var PASSIVE_TELEMETRY_EVENTS = /* @__PURE__ */ new Set(["plugin_activate", "plugin_install", "onboarding_view"]);
770
925
  function inferNodeHost() {
771
926
  if (process.env.INKMAP_HOST) return process.env.INKMAP_HOST;
772
927
  if (process.env.ANTIGRAVITY_CONFIG_DIR) return "antigravity";
@@ -780,81 +935,48 @@ function inferNodeHost() {
780
935
  }
781
936
  return "cli";
782
937
  }
783
- async function localInstallId() {
784
- const path2 = (0, import_node_path.join)(process.env.INKMAP_HOME ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "install-id");
785
- let value;
938
+ async function atomicCreateIfMissing(path2, initialContent) {
786
939
  try {
787
- value = (await (0, import_promises.readFile)(path2, "utf8")).trim();
940
+ return await (0, import_promises.readFile)(path2, "utf8");
788
941
  } catch (error) {
789
942
  if (error.code !== "ENOENT") throw error;
790
943
  await (0, import_promises.mkdir)((0, import_node_path.dirname)(path2), { recursive: true, mode: 448 });
791
- const generated = "inst_" + (0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 24);
792
944
  const temporary = path2 + "." + (0, import_node_crypto.randomUUID)();
793
945
  try {
794
- await (0, import_promises.writeFile)(temporary, generated, { mode: 384, flag: "wx" });
795
- await (0, import_promises.link)(temporary, path2).catch((err) => {
796
- if (err.code !== "EEXIST") throw err;
946
+ await (0, import_promises.writeFile)(temporary, initialContent, { mode: 384, flag: "wx" });
947
+ await (0, import_promises.link)(temporary, path2).catch(async (err) => {
948
+ if (err.code === "EEXIST") return;
949
+ if (err.code === "EPERM" || err.code === "ENOSYS" || err.code === "EXDEV") {
950
+ await (0, import_promises.rename)(temporary, path2);
951
+ return;
952
+ }
953
+ throw err;
797
954
  });
798
955
  } finally {
799
- await (0, import_promises.rm)(temporary, { force: true });
956
+ await (0, import_promises.rm)(temporary, { force: true }).catch(() => {
957
+ });
800
958
  }
801
- value = (await (0, import_promises.readFile)(path2, "utf8")).trim();
959
+ return await (0, import_promises.readFile)(path2, "utf8");
802
960
  }
961
+ }
962
+ async function localInstallId() {
963
+ const path2 = (0, import_node_path.join)(process.env.INKMAP_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "install-id");
964
+ const generated = "inst_" + (0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 24);
965
+ const value = (await atomicCreateIfMissing(path2, generated)).trim();
803
966
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
804
967
  }
805
968
  async function localTrialDeadline() {
806
- const path2 = (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap", "trial-start");
807
- const now = Date.now();
808
- let value;
809
- try {
810
- value = await (0, import_promises.readFile)(path2, "utf8");
811
- } catch (error) {
812
- if (error.code !== "ENOENT") throw error;
813
- await (0, import_promises.mkdir)((0, import_node_path.dirname)(path2), { recursive: true, mode: 448 });
814
- const temporary = path2 + "." + (0, import_node_crypto.randomUUID)();
815
- try {
816
- await (0, import_promises.writeFile)(temporary, String(now), { mode: 384, flag: "wx" });
817
- await (0, import_promises.link)(temporary, path2).catch((error2) => {
818
- if (error2.code !== "EEXIST") throw error2;
819
- });
820
- } finally {
821
- await (0, import_promises.rm)(temporary, { force: true });
822
- }
823
- value = await (0, import_promises.readFile)(path2, "utf8");
824
- }
969
+ const path2 = (0, import_node_path.join)(process.env.INKMAP_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "trial-start");
970
+ const value = await atomicCreateIfMissing(path2, String(Date.now()));
825
971
  const started = Number(value);
826
972
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
827
973
  }
828
- var AD_TTL = 6 * 60 * 60 * 1e3;
829
- function adFeed(url) {
830
- let cache;
831
- return async () => {
832
- if (!url) return [];
833
- if (cache && Date.now() - cache.at < AD_TTL) return cache.ads;
834
- try {
835
- const res = await fetch(url, { signal: AbortSignal.timeout(5e3), headers: { accept: "application/json" } });
836
- const ads = res.ok ? sanitizeAds(await res.json()) : [];
837
- cache = { at: Date.now(), ads };
838
- return ads;
839
- } catch {
840
- cache = { at: Date.now(), ads: [] };
841
- return [];
842
- }
843
- };
844
- }
845
974
 
846
- // packages/vscode/src/browser.ts
847
- var import_node_child_process3 = require("node:child_process");
848
- var vscode2 = __toESM(require("vscode"));
849
-
850
- // packages/cli/src/server.ts
851
- var import_node_child_process2 = require("node:child_process");
852
- var import_node_crypto2 = require("node:crypto");
853
- var import_node_fs = require("node:fs");
975
+ // packages/cli/src/workspace-fs.ts
854
976
  var import_promises2 = require("node:fs/promises");
855
- var import_node_http = require("node:http");
856
977
  var import_node_os2 = require("node:os");
857
978
  var import_node_path2 = require("node:path");
979
+ var MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
858
980
  var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
859
981
  ".git",
860
982
  ".hg",
@@ -877,14 +999,20 @@ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
877
999
  "coverage",
878
1000
  ".tmp"
879
1001
  ]);
880
- function insideRoot(root, target) {
1002
+ var MARKMAP_RE = /\.markmap\.md$/i;
1003
+ function insideOrEqual(root, target) {
881
1004
  if (root === target) return true;
882
1005
  const rel = (0, import_node_path2.relative)(root, target);
883
1006
  return Boolean(rel && !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path2.sep));
884
1007
  }
1008
+ function hasHiddenSegment(root, target) {
1009
+ const rel = (0, import_node_path2.relative)(root, target);
1010
+ if (!rel || rel === ".") return false;
1011
+ return rel.split(import_node_path2.sep).some((part) => part.startsWith("."));
1012
+ }
885
1013
  async function findProjectRoot(filePath) {
886
- let cur = (0, import_node_path2.dirname)(filePath);
887
1014
  const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1015
+ let cur = (0, import_node_path2.dirname)(filePath);
888
1016
  while (cur && cur !== (0, import_node_path2.dirname)(cur) && cur !== home) {
889
1017
  try {
890
1018
  await (0, import_promises2.lstat)((0, import_node_path2.join)(cur, ".git"));
@@ -895,7 +1023,7 @@ async function findProjectRoot(filePath) {
895
1023
  }
896
1024
  return (0, import_node_path2.dirname)(filePath);
897
1025
  }
898
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1026
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
899
1027
  const found = [];
900
1028
  async function walk(dir, depth) {
901
1029
  if (depth > maxDepth || found.length >= maxFiles) return;
@@ -913,11 +1041,10 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
913
1041
  if (!SKIP_SCAN_DIRS.has(entry.name)) await walk(full, depth + 1);
914
1042
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
915
1043
  try {
916
- const st = await (0, import_promises2.lstat)(full);
917
- if (st.isFile() && st.size <= 5 * 1024 * 1024) {
918
- const real = await (0, import_promises2.realpath)(full);
919
- if (real === full && insideRoot(rootDir, real)) found.push(real);
920
- }
1044
+ const info = await (0, import_promises2.lstat)(full);
1045
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES) continue;
1046
+ const real = await (0, import_promises2.realpath)(full);
1047
+ if (real === full && insideOrEqual(rootDir, real)) found.push({ path: real, mtimeMs: info.mtimeMs });
921
1048
  } catch {
922
1049
  }
923
1050
  }
@@ -925,13 +1052,16 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
925
1052
  }
926
1053
  await walk(rootDir, 0);
927
1054
  found.sort((a, b) => {
928
- const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
929
- const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
930
- if (aM !== bM) return aM - bM;
931
- return a.localeCompare(b);
1055
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1056
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1057
+ if (am !== bm) return am - bm;
1058
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3) return b.mtimeMs - a.mtimeMs;
1059
+ return a.path.localeCompare(b.path);
932
1060
  });
933
1061
  return found;
934
1062
  }
1063
+
1064
+ // packages/cli/src/server.ts
935
1065
  var MAX_BODY = 20 * 1024 * 1024;
936
1066
  var TYPES = {
937
1067
  ".html": "text/html; charset=utf-8",
@@ -943,55 +1073,67 @@ var TYPES = {
943
1073
  ".jpeg": "image/jpeg",
944
1074
  ".gif": "image/gif",
945
1075
  ".webp": "image/webp",
1076
+ ".avif": "image/avif",
1077
+ ".bmp": "image/bmp",
1078
+ ".ico": "image/x-icon",
946
1079
  ".woff2": "font/woff2",
947
1080
  ".woff": "font/woff",
948
1081
  ".ttf": "font/ttf",
949
1082
  ".json": "application/json"
950
1083
  };
1084
+ var HttpError = class extends Error {
1085
+ constructor(status, message) {
1086
+ super(message);
1087
+ this.status = status;
1088
+ }
1089
+ };
1090
+ var LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
951
1091
  var hash = (s) => (0, import_node_crypto2.createHash)("sha1").update(s).digest("hex");
952
1092
  function docName(path2) {
953
- return (0, import_node_path2.basename)(path2).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1093
+ return (0, import_node_path3.basename)(path2).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
954
1094
  }
955
1095
  function viewStateFile(key) {
956
- const base = process.env.INKMAP_HOME ?? (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap");
957
- return (0, import_node_path2.join)(base, "view-state", hash(key) + ".json");
1096
+ const base = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1097
+ return (0, import_node_path3.join)(base, "view-state", hash(key) + ".json");
958
1098
  }
959
1099
  async function readDiskViewState(key) {
960
1100
  try {
961
- return sanitizeViewState(JSON.parse(await (0, import_promises2.readFile)(viewStateFile(key), "utf8")));
1101
+ return sanitizeViewState(JSON.parse(await (0, import_promises3.readFile)(viewStateFile(key), "utf8")));
962
1102
  } catch {
963
1103
  return void 0;
964
1104
  }
965
1105
  }
966
1106
  async function writeDiskViewState(key, state) {
967
1107
  const target = viewStateFile(key);
968
- await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(target), { recursive: true, mode: 448 });
1108
+ await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(target), { recursive: true, mode: 448 });
969
1109
  const temp = `${target}.${process.pid}.${Date.now()}`;
970
1110
  try {
971
- await (0, import_promises2.writeFile)(temp, JSON.stringify(state), { mode: 384 });
972
- await (0, import_promises2.rename)(temp, target);
1111
+ await (0, import_promises3.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1112
+ await (0, import_promises3.rename)(temp, target);
973
1113
  } finally {
974
- await (0, import_promises2.rm)(temp, { force: true }).catch(() => {
1114
+ await (0, import_promises3.rm)(temp, { force: true }).catch(() => {
975
1115
  });
976
1116
  }
977
1117
  }
978
1118
  async function fileSource(file, log = () => {
979
1119
  }) {
980
- const path2 = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(file)).catch(() => (0, import_node_path2.resolve)(file));
981
- if (!(await (0, import_promises2.stat)(path2)).isFile()) throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path2}`);
982
- const dir = (0, import_node_path2.dirname)(path2);
1120
+ const path2 = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(file)).catch(() => (0, import_node_path3.resolve)(file));
1121
+ if (!(await (0, import_promises3.stat)(path2)).isFile()) throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path2}`);
1122
+ const dir = (0, import_node_path3.dirname)(path2);
983
1123
  return {
984
1124
  name: docName(path2),
985
1125
  key: path2,
986
1126
  dir,
987
- read: () => (0, import_promises2.readFile)(path2, "utf8"),
1127
+ read: () => (0, import_promises3.readFile)(path2, "utf8"),
988
1128
  async write(md) {
989
- await (0, import_promises2.writeFile)(path2, md, "utf8");
1129
+ await (0, import_promises3.writeFile)(path2, md, "utf8");
990
1130
  log(`\u5DF2\u5199\u56DE ${path2}`);
991
1131
  },
992
1132
  watch(onChange) {
993
1133
  const watcher = (0, import_node_fs.watch)(dir, (_, changed) => {
994
- if (!changed || changed === (0, import_node_path2.basename)(path2)) onChange();
1134
+ if (!changed || changed === (0, import_node_path3.basename)(path2)) onChange();
1135
+ });
1136
+ watcher.on("error", () => {
995
1137
  });
996
1138
  return () => watcher.close();
997
1139
  },
@@ -1000,8 +1142,15 @@ async function fileSource(file, log = () => {
1000
1142
  };
1001
1143
  }
1002
1144
  function within(root, rel) {
1003
- const base = root.endsWith(import_node_path2.sep) ? root : root + import_node_path2.sep;
1004
- const full = (0, import_node_path2.normalize)((0, import_node_path2.join)(root, decodeURIComponent(rel)));
1145
+ let decoded;
1146
+ try {
1147
+ decoded = decodeURIComponent(rel);
1148
+ } catch {
1149
+ return null;
1150
+ }
1151
+ const resolvedRoot = (0, import_node_path3.resolve)(root);
1152
+ const base = resolvedRoot.endsWith(import_node_path3.sep) ? resolvedRoot : resolvedRoot + import_node_path3.sep;
1153
+ const full = (0, import_node_path3.normalize)((0, import_node_path3.join)(resolvedRoot, decoded));
1005
1154
  return full.startsWith(base) ? full : null;
1006
1155
  }
1007
1156
  async function openBrowserWindow(url) {
@@ -1025,8 +1174,23 @@ async function openBrowserWindow(url) {
1025
1174
  if (await run("google-chrome", [url])) return;
1026
1175
  await run("xdg-open", [url]);
1027
1176
  }
1028
- async function serve({ source: initialSource, webRoot, port = 4377, host = "127.0.0.1", log = () => {
1029
- }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false, workspaceRoots = [] }) {
1177
+ async function serve({
1178
+ source: initialSource,
1179
+ webRoot,
1180
+ port = 4377,
1181
+ host = "127.0.0.1",
1182
+ log = () => {
1183
+ },
1184
+ license,
1185
+ sidebar = false,
1186
+ sidebarPurchase = false,
1187
+ sidebarAccountNavigation = false,
1188
+ ideWorkspace = false,
1189
+ workspaceRoots = [],
1190
+ confineToWorkspaceRoots = false,
1191
+ openSource = (path2) => fileSource(path2, log),
1192
+ allowPurchase = true
1193
+ }) {
1030
1194
  if (sidebar && host !== "127.0.0.1") throw new Error("The sidebar bridge requires loopback.");
1031
1195
  const prefix = sidebar ? `/s/${(0, import_node_crypto2.randomBytes)(24).toString("hex")}/` : "/";
1032
1196
  let activeSource = initialSource;
@@ -1036,7 +1200,9 @@ async function serve({ source: initialSource, webRoot, port = 4377, host = "127.
1036
1200
  let version = hash(current);
1037
1201
  let viewState = await activeSource.readView?.();
1038
1202
  const clients = /* @__PURE__ */ new Set();
1039
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1203
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1204
+ const allowedHosts = /* @__PURE__ */ new Set();
1205
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1040
1206
  const docState = () => ({
1041
1207
  name: activeSource.name,
1042
1208
  md: current,
@@ -1069,35 +1235,35 @@ data: ${JSON.stringify(data)}
1069
1235
  broadcast();
1070
1236
  }
1071
1237
  let pending;
1072
- let unwatch = activeSource.watch(() => {
1238
+ const scheduleRefresh = () => {
1073
1239
  clearTimeout(pending);
1074
- pending = setTimeout(async () => {
1075
- void serialized(refresh).catch(() => {
1076
- });
1077
- }, 80);
1078
- });
1240
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1241
+ }), 80);
1242
+ };
1243
+ let unwatch = activeSource.watch(scheduleRefresh);
1244
+ const canonicalActiveKey = async () => activeSource.key ? await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key) : void 0;
1079
1245
  async function collectWorkspaceFiles() {
1080
1246
  const roots = /* @__PURE__ */ new Map();
1081
- if (activeSource.key) {
1082
- const realKey = await (0, import_promises2.realpath)(activeSource.key).catch(() => activeSource.key);
1083
- const projRoot = await (0, import_promises2.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path2.dirname)(realKey));
1084
- roots.set(projRoot, { path: projRoot, name: (0, import_node_path2.basename)(projRoot), active: true });
1247
+ if (activeSource.key && !confineToWorkspaceRoots) {
1248
+ const realKey = await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key);
1249
+ const projRoot = await (0, import_promises3.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path3.dirname)(realKey));
1250
+ roots.set(projRoot, { path: projRoot, name: (0, import_node_path3.basename)(projRoot), active: true });
1085
1251
  }
1086
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter)].filter(Boolean);
1252
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path3.delimiter)].filter(Boolean);
1087
1253
  for (const raw of envRoots) {
1088
- const real = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(raw)).catch(() => null);
1254
+ const real = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(raw)).catch(() => null);
1089
1255
  if (real && !roots.has(real)) {
1090
- roots.set(real, { path: real, name: (0, import_node_path2.basename)(real), active: roots.size === 0 });
1256
+ roots.set(real, { path: real, name: (0, import_node_path3.basename)(real), active: roots.size === 0 });
1091
1257
  }
1092
1258
  }
1093
1259
  const items = [];
1094
1260
  const seen = /* @__PURE__ */ new Set();
1095
1261
  for (const root of roots.values()) {
1096
- const files = await scanProjectMarkdownFiles(root.path);
1262
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1097
1263
  for (const f of files) {
1098
1264
  if (seen.has(f)) continue;
1099
1265
  seen.add(f);
1100
- const rel = (0, import_node_path2.relative)(root.path, f);
1266
+ const rel = (0, import_node_path3.relative)(root.path, f);
1101
1267
  items.push({
1102
1268
  path: f,
1103
1269
  label: `${root.name} / ${rel}`,
@@ -1105,42 +1271,49 @@ data: ${JSON.stringify(data)}
1105
1271
  });
1106
1272
  }
1107
1273
  }
1108
- if (activeSource.key && !seen.has(activeSource.key)) {
1274
+ const activeReal = await canonicalActiveKey();
1275
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1109
1276
  items.unshift({
1110
1277
  path: activeSource.key,
1111
- label: `${(0, import_node_path2.basename)(activeSource.dir)} / ${(0, import_node_path2.basename)(activeSource.key)}`,
1278
+ label: `${(0, import_node_path3.basename)(activeSource.dir)} / ${(0, import_node_path3.basename)(activeSource.key)}`,
1112
1279
  group: "active"
1113
1280
  });
1114
1281
  }
1115
1282
  return { roots: [...roots.values()], files: items };
1116
1283
  }
1117
- async function switchSourceToFile(candidatePath) {
1118
- if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1119
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1284
+ const zh2 = () => detectOsLocale() === "zh";
1285
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1286
+ const notMarkdown = () => new HttpError(400, zh2() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1287
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) throw notMarkdown();
1288
+ const resolvedCandidate = (0, import_node_path3.resolve)(candidatePath);
1289
+ const rawStat = await (0, import_promises3.lstat)(resolvedCandidate).catch(() => null);
1290
+ const realTarget = await (0, import_promises3.realpath)(resolvedCandidate).catch(() => null);
1291
+ const targetStat = realTarget ? await (0, import_promises3.stat)(realTarget).catch(() => null) : null;
1292
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1293
+ throw new HttpError(403, zh2() ? "\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002" : "Choose a regular Markdown file up to 5 MiB.");
1120
1294
  }
1121
- const realTarget = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(candidatePath));
1122
- const st = await (0, import_promises2.lstat)(realTarget);
1123
- if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1124
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1125
- }
1126
- const { roots } = await collectWorkspaceFiles();
1127
- if (roots.length > 0 && !roots.some((r) => insideRoot(r.path, realTarget))) {
1128
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
1295
+ if (!/\.md$/i.test(realTarget)) throw notMarkdown();
1296
+ if (!trustCaller) {
1297
+ const { roots } = await collectWorkspaceFiles();
1298
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, realTarget));
1299
+ if (!matchedRoot) {
1300
+ throw new HttpError(403, zh2() ? "\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002" : "This file is outside the current workspace.");
1301
+ }
1302
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1303
+ throw new HttpError(403, zh2() ? "\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002" : "Files in hidden folders are not allowed.");
1304
+ }
1129
1305
  }
1130
- if (activeSource.key === realTarget) return;
1306
+ if (await canonicalActiveKey() === realTarget) return;
1307
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1308
+ const text = await next.read();
1309
+ const nextView = await next.readView?.();
1131
1310
  clearTimeout(pending);
1132
1311
  unwatch();
1133
- activeSource = await fileSource(realTarget, log);
1134
- current = await activeSource.read();
1135
- version = hash(current);
1136
- viewState = await activeSource.readView?.();
1137
- unwatch = activeSource.watch(() => {
1138
- clearTimeout(pending);
1139
- pending = setTimeout(async () => {
1140
- void serialized(refresh).catch(() => {
1141
- });
1142
- }, 80);
1143
- });
1312
+ activeSource = next;
1313
+ current = text;
1314
+ version = hash(text);
1315
+ viewState = nextView;
1316
+ unwatch = activeSource.watch(scheduleRefresh);
1144
1317
  broadcast();
1145
1318
  }
1146
1319
  const json = (res, status, body) => {
@@ -1153,7 +1326,7 @@ data: ${JSON.stringify(data)}
1153
1326
  req.on("data", (c) => {
1154
1327
  size += c.length;
1155
1328
  if (size > MAX_BODY) {
1156
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1329
+ fail(new HttpError(413, zh2() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1157
1330
  req.destroy();
1158
1331
  } else chunks.push(c);
1159
1332
  });
@@ -1163,19 +1336,26 @@ data: ${JSON.stringify(data)}
1163
1336
  const sendFile = async (res, full) => {
1164
1337
  if (!full) return json(res, 403, { error: "forbidden" });
1165
1338
  try {
1166
- const ext = (0, import_node_path2.extname)(full).toLowerCase();
1339
+ const ext = (0, import_node_path3.extname)(full).toLowerCase();
1167
1340
  if (ext === ".html") {
1168
1341
  const osLoc = detectOsLocale();
1169
- const htmlText = (await (0, import_promises2.readFile)(full, "utf8")).replace(
1342
+ const htmlText = (await (0, import_promises3.readFile)(full, "utf8")).replace(
1170
1343
  /<html\b([^>]*)>/i,
1171
- `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`
1344
+ () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`
1172
1345
  );
1173
1346
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1174
1347
  res.end(htmlText, "utf8");
1175
1348
  return;
1176
1349
  }
1177
- const body = await (0, import_promises2.readFile)(full);
1178
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1350
+ const body = await (0, import_promises3.readFile)(full);
1351
+ const headers = {
1352
+ "content-type": TYPES[ext] ?? "application/octet-stream",
1353
+ "cache-control": sidebar ? "no-store" : "no-cache"
1354
+ };
1355
+ if (ext === ".svg") {
1356
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
1357
+ }
1358
+ res.writeHead(200, headers);
1179
1359
  res.end(body);
1180
1360
  } catch {
1181
1361
  json(res, 404, { error: "not found" });
@@ -1184,17 +1364,26 @@ data: ${JSON.stringify(data)}
1184
1364
  const server = (0, import_node_http.createServer)(async (req, res) => {
1185
1365
  try {
1186
1366
  const url = new URL(req.url ?? "/", "http://localhost");
1367
+ const reqHost = req.headers.host ?? "";
1368
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1187
1369
  if (sidebar) {
1188
1370
  res.setHeader("Referrer-Policy", "no-referrer");
1189
1371
  res.setHeader("X-Content-Type-Options", "nosniff");
1190
1372
  res.setHeader("Cache-Control", "no-store");
1191
1373
  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'");
1192
- if (req.headers.host !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix)) return json(res, 404, { error: "not found" });
1374
+ if (reqHost !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix)) return json(res, 404, { error: "not found" });
1193
1375
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1194
1376
  return json(res, 403, { error: "forbidden" });
1195
1377
  }
1196
1378
  url.pathname = "/" + url.pathname.slice(prefix.length);
1379
+ } else if (!hostAllowed) {
1380
+ return json(res, 403, { error: "forbidden" });
1197
1381
  }
1382
+ const sameOriginWrite = () => {
1383
+ const origin = req.headers.origin;
1384
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
1385
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
1386
+ };
1198
1387
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1199
1388
  res.writeHead(302, { Location: "/" + url.search });
1200
1389
  return res.end();
@@ -1217,6 +1406,7 @@ data: ${JSON.stringify(data)}
1217
1406
  });
1218
1407
  }
1219
1408
  if (url.pathname === "/api/view" && req.method === "PUT") {
1409
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1220
1410
  const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1221
1411
  if (cleaned) {
1222
1412
  viewState = cleaned;
@@ -1226,8 +1416,9 @@ data: ${JSON.stringify(data)}
1226
1416
  return json(res, 200, { ok: true });
1227
1417
  }
1228
1418
  if (url.pathname === "/api/doc" && req.method === "PUT") {
1419
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1229
1420
  const { md, baseVersion } = JSON.parse(await readBody(req));
1230
- if (typeof md !== "string") return json(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1421
+ if (typeof md !== "string") return json(res, 400, { error: zh2() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1231
1422
  if (!hasAccess(await license?.state() ?? { pro: false })) return json(res, 403, { error: "Inkmap trial expired" });
1232
1423
  return await serialized(async () => {
1233
1424
  await refresh();
@@ -1237,70 +1428,62 @@ data: ${JSON.stringify(data)}
1237
1428
  current = md;
1238
1429
  version = hash(md);
1239
1430
  license?.track?.("doc_edit");
1240
- if (sidebar) broadcast();
1431
+ broadcast();
1241
1432
  }
1242
1433
  return json(res, 200, { version });
1243
1434
  });
1244
1435
  }
1245
1436
  if (url.pathname === "/api/license" && req.method === "GET") return json(res, 200, await license?.state() ?? { pro: false });
1246
- const sameOriginPost = () => {
1247
- const origin = req.headers.origin;
1248
- const reqHost = req.headers.host;
1249
- const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1250
- return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1251
- };
1252
1437
  if (url.pathname === "/api/open" && req.method === "POST") {
1253
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1438
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1254
1439
  const { file } = JSON.parse(await readBody(req));
1255
- await serialized(() => switchSourceToFile(String(file ?? "")));
1440
+ await serialized(() => switchSourceToFile(String(file ?? ""), false));
1256
1441
  license?.track?.("doc_open");
1257
1442
  const { files } = await collectWorkspaceFiles();
1258
1443
  return json(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1259
1444
  }
1260
1445
  if (url.pathname === "/api/telemetry" && req.method === "POST") {
1261
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1446
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1262
1447
  const { event } = JSON.parse(await readBody(req));
1263
1448
  if (typeof event === "string" && event) license?.track?.(event);
1264
1449
  return json(res, 200, { ok: true });
1265
1450
  }
1266
1451
  if (url.pathname === "/api/open-browser" && req.method === "POST") {
1267
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1452
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1268
1453
  if (license && !hasAccess(await license.state())) {
1269
1454
  return json(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." });
1270
1455
  }
1271
1456
  license?.track?.("feature_browser");
1272
1457
  if (!sidebar) {
1273
- const directUrl = `http://${host}:${bound}/`;
1458
+ const directUrl = `http://${urlHost}:${bound}/`;
1274
1459
  await openBrowserWindow(directUrl);
1275
1460
  return json(res, 200, { ok: true, url: directUrl });
1276
1461
  }
1277
1462
  if (!browserCompanion) {
1278
- browserCompanion = (async () => {
1279
- const src = activeSource.key ? await fileSource(activeSource.key) : activeSource;
1280
- return serve({
1281
- source: src,
1282
- webRoot,
1283
- host: "127.0.0.1",
1284
- port: 0,
1285
- license,
1286
- ads,
1287
- sidebar: false,
1288
- loginOnly: false,
1289
- workspaceRoots
1290
- });
1291
- })();
1463
+ browserCompanion = serve({
1464
+ source: activeSource,
1465
+ webRoot,
1466
+ host: "127.0.0.1",
1467
+ port: 0,
1468
+ license,
1469
+ sidebar: false,
1470
+ workspaceRoots,
1471
+ confineToWorkspaceRoots,
1472
+ openSource,
1473
+ allowPurchase: canPurchase
1474
+ });
1292
1475
  browserCompanion.catch(() => {
1293
1476
  browserCompanion = null;
1294
1477
  });
1295
1478
  }
1296
1479
  const companion = await browserCompanion;
1297
- if (activeSource.key) await companion.switchToFile?.(activeSource.key).catch(() => {
1480
+ if (activeSource.key) await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1298
1481
  });
1299
1482
  await openBrowserWindow(companion.url);
1300
1483
  return json(res, 200, { ok: true, url: companion.url });
1301
1484
  }
1302
1485
  if (url.pathname === "/api/checkout" && req.method === "POST") {
1303
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1486
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1304
1487
  const { mode, locale } = JSON.parse(await readBody(req));
1305
1488
  if (mode !== "buy" && mode !== "restore") return json(res, 400, { error: "invalid checkout mode" });
1306
1489
  if (!canPurchase && mode === "buy") return json(res, 403, { error: "forbidden" });
@@ -1308,7 +1491,7 @@ data: ${JSON.stringify(data)}
1308
1491
  return json(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1309
1492
  }
1310
1493
  if (url.pathname === "/api/order-pro" && req.method === "POST") {
1311
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1494
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1312
1495
  if (!canPurchase) return json(res, 403, { error: "forbidden" });
1313
1496
  if (!license) return json(res, 503, { error: "Inkmap checkout is unavailable." });
1314
1497
  if (typeof license.orderPro !== "function") return json(res, 501, { fallback: true });
@@ -1316,23 +1499,24 @@ data: ${JSON.stringify(data)}
1316
1499
  return json(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1317
1500
  }
1318
1501
  if (url.pathname === "/api/phone-send" && req.method === "POST") {
1319
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1502
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1320
1503
  if (!license || typeof license.sendPhoneCode !== "function") return json(res, 501, { fallback: true });
1321
1504
  const { phone, locale } = JSON.parse(await readBody(req));
1322
1505
  return json(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1323
1506
  }
1324
1507
  if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1325
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1508
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1326
1509
  if (!license || typeof license.signInByPhone !== "function") return json(res, 501, { fallback: true });
1327
- const { phone, code } = JSON.parse(await readBody(req));
1328
- return json(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
1510
+ const { phone, code, locale } = JSON.parse(await readBody(req));
1511
+ return json(res, 200, {
1512
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
1513
+ });
1329
1514
  }
1330
1515
  if (url.pathname === "/api/signout" && req.method === "POST") {
1331
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1516
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1332
1517
  await license?.deactivate();
1333
1518
  return json(res, 200, await license?.state() ?? { pro: false });
1334
1519
  }
1335
- if (url.pathname === "/api/ads") return json(res, 200, sidebar ? [] : await ads?.() ?? []);
1336
1520
  if (url.pathname === "/api/events") {
1337
1521
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1338
1522
  res.write(": connected\n\n");
@@ -1343,16 +1527,19 @@ data: ${JSON.stringify(data)}
1343
1527
  if (url.pathname === "/favicon.ico") return void res.writeHead(204).end();
1344
1528
  if (url.pathname.startsWith("/doc-assets/")) {
1345
1529
  let asset = within(activeSource.dir, url.pathname.slice("/doc-assets/".length));
1346
- if (sidebar && asset) {
1347
- const root = await (0, import_promises2.realpath)(activeSource.dir);
1348
- asset = await (0, import_promises2.realpath)(asset).catch(() => null);
1349
- if (asset && (!asset.startsWith(root + import_node_path2.sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset))) asset = null;
1530
+ if (asset) {
1531
+ const root = await (0, import_promises3.realpath)(activeSource.dir).catch(() => null);
1532
+ asset = await (0, import_promises3.realpath)(asset).catch(() => null);
1533
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
1534
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset)) asset = null;
1350
1535
  }
1351
1536
  return sendFile(res, asset);
1352
1537
  }
1353
1538
  return sendFile(res, within(webRoot, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1354
1539
  } catch (err) {
1355
- json(res, 500, { error: err instanceof Error ? err.message : String(err) });
1540
+ if (res.headersSent) return void res.end();
1541
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
1542
+ json(res, status, { error: err instanceof Error ? err.message : String(err) });
1356
1543
  }
1357
1544
  });
1358
1545
  const listen = (p) => new Promise((ok, fail) => {
@@ -1363,14 +1550,24 @@ data: ${JSON.stringify(data)}
1363
1550
  });
1364
1551
  });
1365
1552
  try {
1366
- bound = await listen(port);
1553
+ try {
1554
+ bound = await listen(port);
1555
+ } catch (err) {
1556
+ if (err.code !== "EADDRINUSE") throw err;
1557
+ bound = await listen(0);
1558
+ }
1367
1559
  } catch (err) {
1368
- if (err.code !== "EADDRINUSE") throw err;
1369
- bound = await listen(0);
1560
+ clearTimeout(pending);
1561
+ unwatch();
1562
+ unlisten();
1563
+ throw err;
1370
1564
  }
1371
1565
  return {
1372
- url: `http://${host}:${bound}${prefix}`,
1373
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1566
+ url: `http://${urlHost}:${bound}${prefix}`,
1567
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
1568
+ allowHost: (extraHost) => {
1569
+ if (extraHost) allowedHosts.add(extraHost.toLowerCase());
1570
+ },
1374
1571
  close: () => new Promise((done) => {
1375
1572
  clearTimeout(pending);
1376
1573
  unwatch();
@@ -1478,21 +1675,45 @@ var zh = {
1478
1675
  copyLink: "\u590D\u5236\u94FE\u63A5",
1479
1676
  browserFailed: "\u65E0\u6CD5\u5728\u6D4F\u89C8\u5668\u6253\u5F00\u601D\u7EF4\u5BFC\u56FE\uFF1A{error}",
1480
1677
  readOnly: "\u6587\u6863\u65E0\u6CD5\u4FEE\u6539\uFF08\u53EF\u80FD\u662F\u53EA\u8BFB\u6587\u4EF6\uFF09",
1481
- buyPro: "\u8D2D\u4E70 Pro",
1482
- signIn: "\u767B\u5F55",
1483
- switchAccount: "\u5207\u6362\u8D26\u53F7",
1484
- proActiveDetail: "\u7EC8\u8EAB\u4F1A\u5458\u6743\u76CA\u5DF2\u5F00\u901A\u3002",
1485
- accountLine: "\u5F53\u524D\u8D26\u53F7\uFF1A{account}",
1486
- accountConnected: "\u5F53\u524D\u8D26\u53F7\uFF1A\u5DF2\u767B\u5F55",
1487
1678
  trialExpired: "7 \u5929\u8BD5\u7528\u5DF2\u7ED3\u675F\u3002\u8BF7\u8D2D\u4E70 Pro\uFF0C\u6216\u767B\u5F55\u5DF2\u8D2D\u4E70 Pro \u7684\u8D26\u53F7\u3002",
1488
- checkoutHint: "\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u64CD\u4F5C\uFF0C\u5DF2\u6709 Pro \u6743\u76CA\u4F1A\u81EA\u52A8\u540C\u6B65\u3002",
1489
1679
  checkoutFailed: "\u65E0\u6CD5\u6253\u5F00\u8D2D\u4E70\u9875\u9762\u3002",
1490
- removed: "\u5DF2\u9000\u51FA\u767B\u5F55\u3002",
1491
- removeConfirm: "\u9000\u51FA\u5F53\u524D\u8D26\u53F7\uFF1F\u4E0B\u6B21\u767B\u5F55\u65F6\u4F1A\u81EA\u52A8\u540C\u6B65 Pro \u6743\u76CA\u3002",
1492
- remove: "\u9000\u51FA\u767B\u5F55",
1493
1680
  saveExport: "\u5BFC\u51FA",
1494
1681
  onboardingTip: "\u{1F4A1} Inkmap \u601D\u7EF4\u5BFC\u56FE\u5DF2\u5C31\u7EEA\uFF1A\u70B9\u51FB\u5373\u53EF\u5728\u53F3\u4FA7\u5E76\u6392\u6253\u5F00\u53EF\u53CC\u5411\u7F16\u8F91\u7684\u8111\u56FE\u4E0E\u6D41\u7A0B\u56FE",
1495
- onboardingAction: "\u7ACB\u5373\u6253\u5F00\u601D\u7EF4\u5BFC\u56FE"
1682
+ onboardingAction: "\u7ACB\u5373\u6253\u5F00\u601D\u7EF4\u5BFC\u56FE",
1683
+ welcomeTip: "\u{1F4A1} Inkmap \u601D\u7EF4\u5BFC\u56FE\u5DF2\u5B89\u88C5\uFF1A\u4E00\u952E\u6253\u5F00\u793A\u4F8B\u8111\u56FE\u4F53\u9A8C\u53CC\u5411\u7F16\u8F91\uFF0C\u6216\u5728\u4EFB\u610F .md \u6587\u4EF6\u70B9\u51FB\u53F3\u4E0B\u89D2\u300C\u601D\u7EF4\u5BFC\u56FE\u300D",
1684
+ welcomeAction: "\u6253\u5F00\u793A\u4F8B\u5BFC\u56FE",
1685
+ statusBarLabel: "$(type-hierarchy) \u601D\u7EF4\u5BFC\u56FE",
1686
+ statusBarTooltip: "\u7528 Inkmap \u5728\u4FA7\u8FB9\u6253\u5F00\u5F53\u524D Markdown \u7684\u53EF\u7F16\u8F91\u601D\u7EF4\u5BFC\u56FE",
1687
+ codeLensOpen: "\u21C4 \u7528 Inkmap \u601D\u7EF4\u5BFC\u56FE\u6253\u5F00",
1688
+ codeLensOpenTooltip: "\u5728\u53F3\u4FA7\u5E76\u6392\u6253\u5F00\u5F53\u524D Markdown \u7684\u53CC\u5411\u53EF\u7F16\u8F91\u601D\u7EF4\u5BFC\u56FE",
1689
+ codeLensBrowser: "\u6D4F\u89C8\u5668\u5168\u5C4F\u6253\u5F00",
1690
+ codeLensBrowserTooltip: "\u5728\u72EC\u7ACB\u6D4F\u89C8\u5668\u7A97\u53E3\u5168\u5C4F\u6253\u5F00\u5F53\u524D\u5BFC\u56FE\uFF0C\u5B9E\u65F6\u53CC\u5411\u540C\u6B65\u56DE\u539F\u6587\u4EF6",
1691
+ welcomeDoc: `# Inkmap \u601D\u7EF4\u5BFC\u56FE\u5FEB\u901F\u4E0A\u624B
1692
+
1693
+ - \u2728 \u53CC\u5411\u5B9E\u65F6\u540C\u6B65
1694
+ - \u53CC\u51FB\u4EFB\u610F\u8282\u70B9\u76F4\u63A5\u7F16\u8F91\uFF0C\u81EA\u52A8\u5199\u56DE Markdown \u6E90\u6587\u4EF6
1695
+ - \u9009\u4E2D\u8282\u70B9\u6309 \`Tab\` \u6DFB\u52A0\u5B50\u8282\u70B9\uFF0C\u6309 \`Enter\` \u6DFB\u52A0\u540C\u7EA7\u8282\u70B9
1696
+ - \u{1F9ED} \u5E38\u7528\u5165\u53E3
1697
+ - \u7F16\u8F91\u4EFB\u610F \`.md\` \u6587\u4EF6\u65F6\uFF0C\u70B9\u51FB\u53F3\u4E0B\u89D2\u72B6\u6001\u680F **\u601D\u7EF4\u5BFC\u56FE** \u6309\u94AE
1698
+ - \u6216\u70B9\u51FB\u7F16\u8F91\u5668\u53F3\u4E0A\u89D2\u5BFC\u56FE\u56FE\u6807\uFF0C\u5728\u4FA7\u8FB9\u5E76\u6392\u9884\u89C8\u4E0E\u7F16\u8F91
1699
+ - \u{1F4CA} \u539F\u751F Mermaid \u6D41\u7A0B\u56FE
1700
+ \`\`\`mermaid
1701
+ graph LR
1702
+ A[Markdown \u6587\u6863] --> B[Inkmap \u601D\u7EF4\u5BFC\u56FE]
1703
+ B --> C[\u53CC\u5411\u7F16\u8F91 & \u5BFC\u51FA PNG/SVG/HTML]
1704
+ \`\`\`
1705
+ - \u{1F4D0} LaTeX \u516C\u5F0F\u652F\u6301
1706
+ - \u8D28\u80FD\u65B9\u7A0B\uFF1A$E = mc^2$
1707
+ `,
1708
+ harnessOffer: "\u68C0\u6D4B\u5230 DeepSeek Harness\u3002\u8981\u628A Inkmap \u601D\u7EF4\u5BFC\u56FE\u63D2\u4EF6\u5B89\u88C5\u5230 DeepSeek Harness \u5417\uFF1F\u8FD9\u4F1A\u5728\u5B83\u7684\u684C\u9762\u914D\u7F6E\u4E2D\u52A0\u5165 Inkmap \u63D2\u4EF6\u7D22\u5F15\u5E76\u5B89\u88C5\u63D2\u4EF6\u3002",
1709
+ harnessInstall: "\u5B89\u88C5",
1710
+ harnessNoThanks: "\u4E0D\u7528\u4E86",
1711
+ harnessInstalling: "\u6B63\u5728\u628A Inkmap \u5B89\u88C5\u5230 DeepSeek Harness\u2026",
1712
+ harnessInstalled: "\u5DF2\u628A Inkmap \u5B89\u88C5\u5230 DeepSeek Harness\uFF0C\u91CD\u542F DeepSeek Harness \u540E\u5373\u53EF\u4F7F\u7528\u3002",
1713
+ harnessConfigured: "\u5DF2\u5728 DeepSeek Harness \u4E2D\u52A0\u5165 Inkmap \u63D2\u4EF6\u7D22\u5F15\uFF1B\u672A\u627E\u5230 dsh \u547D\u4EE4\uFF0C\u8BF7\u5728 DeepSeek Harness \u7684\u300C\u63D2\u4EF6\u300D\u9875\u5B89\u88C5 Inkmap\u3002",
1714
+ harnessAlready: "DeepSeek Harness \u4E2D\u5DF2\u5B89\u88C5 Inkmap\u3002",
1715
+ harnessNotFound: "\u672A\u627E\u5230 DeepSeek Harness \u684C\u9762\u7248\u3002",
1716
+ harnessFailed: "\u5B89\u88C5\u5230 DeepSeek Harness \u5931\u8D25\uFF1A{error}"
1496
1717
  };
1497
1718
  var en = {
1498
1719
  openMarkdownFirst: "Open a Markdown file first",
@@ -1500,21 +1721,45 @@ var en = {
1500
1721
  copyLink: "Copy link",
1501
1722
  browserFailed: "Could not open the mind map in the browser: {error}",
1502
1723
  readOnly: "The document cannot be modified (it may be read-only)",
1503
- buyPro: "Buy Pro",
1504
- signIn: "Sign In",
1505
- switchAccount: "Switch Account",
1506
- proActiveDetail: "Lifetime Pro membership is active.",
1507
- accountLine: "Account: {account}",
1508
- accountConnected: "Account: Signed in",
1509
1724
  trialExpired: "Your 7-day trial has ended. Buy Pro or sign in to an account that has Pro.",
1510
- checkoutHint: "Continue in your browser. Any existing Pro access will sync automatically.",
1511
1725
  checkoutFailed: "Could not open checkout.",
1512
- removed: "Signed out.",
1513
- removeConfirm: "Sign out? Your Pro access will sync the next time you sign in.",
1514
- remove: "Sign Out",
1515
1726
  saveExport: "Export",
1516
1727
  onboardingTip: "\u{1F4A1} Inkmap is ready: Open this Markdown file side-by-side as an interactive two-way mind map",
1517
- onboardingAction: "Open Mind Map"
1728
+ onboardingAction: "Open Mind Map",
1729
+ welcomeTip: "\u{1F4A1} Inkmap Mind Map is installed: Try the interactive welcome mind map, or click \u201CMind Map\u201D in the status bar on any .md file",
1730
+ welcomeAction: "Open Demo Mind Map",
1731
+ statusBarLabel: "$(type-hierarchy) Mind Map",
1732
+ statusBarTooltip: "Open this Markdown file side-by-side in Inkmap Mind Map",
1733
+ codeLensOpen: "\u21C4 Open as Inkmap Mind Map",
1734
+ codeLensOpenTooltip: "Open this Markdown file side-by-side as a two-way editable mind map",
1735
+ codeLensBrowser: "Open in Browser",
1736
+ codeLensBrowserTooltip: "Open full-screen in browser with live two-way file sync",
1737
+ welcomeDoc: `# Welcome to Inkmap Mind Map
1738
+
1739
+ - \u2728 Two-Way Markdown Sync
1740
+ - Double-click any node to edit \u2014 changes write directly back to Markdown
1741
+ - Press \`Tab\` to add a child node, \`Enter\` to add a sibling node
1742
+ - \u{1F9ED} Quick Entry Points
1743
+ - Click **Mind Map** in the bottom-right status bar on any \`.md\` file
1744
+ - Or click the Inkmap icon in the editor title bar to open side-by-side
1745
+ - \u{1F4CA} Native Mermaid Diagrams
1746
+ \`\`\`mermaid
1747
+ graph LR
1748
+ A[Markdown File] --> B[Inkmap Mind Map]
1749
+ B --> C[Two-Way Edit & Export PNG/SVG/HTML]
1750
+ \`\`\`
1751
+ - \u{1F4D0} LaTeX Math
1752
+ - Mass\u2013energy equivalence: $E = mc^2$
1753
+ `,
1754
+ harnessOffer: "DeepSeek Harness is installed. Add the Inkmap mind map plugin to it? This adds the Inkmap plugin index to its desktop profile and installs the plugin.",
1755
+ harnessInstall: "Install",
1756
+ harnessNoThanks: "No thanks",
1757
+ harnessInstalling: "Installing Inkmap in DeepSeek Harness\u2026",
1758
+ harnessInstalled: "Inkmap was installed in DeepSeek Harness. Restart DeepSeek Harness to use it.",
1759
+ harnessConfigured: "The Inkmap plugin index was added to DeepSeek Harness, but the dsh command was not found. Install Inkmap from the Plugins page in DeepSeek Harness.",
1760
+ harnessAlready: "Inkmap is already installed in DeepSeek Harness.",
1761
+ harnessNotFound: "DeepSeek Harness desktop was not found.",
1762
+ harnessFailed: "Could not install Inkmap in DeepSeek Harness: {error}"
1518
1763
  };
1519
1764
  var isChinese = () => detectOsLocale() === "zh";
1520
1765
  function t(key, vars = {}) {
@@ -1524,30 +1769,37 @@ function t(key, vars = {}) {
1524
1769
  // packages/vscode/src/browser.ts
1525
1770
  var VIEW_STATE_PREFIX = "inkmap.viewState:";
1526
1771
  var BrowserServers = class {
1527
- constructor(context, webRoot, log, license, ads) {
1772
+ constructor(context, webRoot, log, license) {
1528
1773
  this.context = context;
1529
1774
  this.webRoot = webRoot;
1530
1775
  this.log = log;
1531
1776
  this.license = license;
1532
- this.ads = ads;
1533
1777
  }
1534
1778
  servers = /* @__PURE__ */ new Map();
1535
1779
  async open(uri) {
1536
1780
  const key = uri.toString();
1537
1781
  let served = this.servers.get(key);
1538
1782
  if (!served) {
1783
+ const workspaceRoots = (vscode2.workspace.workspaceFolders ?? []).filter((f) => f.uri.scheme === "file").map((f) => f.uri.fsPath);
1539
1784
  served = serve({
1540
1785
  source: documentSource(uri, this.context),
1541
1786
  webRoot: this.webRoot,
1542
1787
  port: 0,
1543
1788
  log: (msg) => this.log.appendLine(`[${docName2(uri)}] ${msg}`),
1544
1789
  license: this.license,
1545
- ads: this.ads
1790
+ workspaceRoots,
1791
+ // Files picked in the browser tree still go through VS Code's document model (dirty buffers, save hooks).
1792
+ openSource: async (path2) => documentSource(vscode2.Uri.file(path2), this.context)
1546
1793
  });
1547
1794
  this.servers.set(key, served);
1548
1795
  served.catch(() => this.servers.delete(key));
1549
1796
  }
1550
- const { url } = await served;
1797
+ const server = await served;
1798
+ if (uri.scheme === "file") await server.switchToFile?.(uri.fsPath, { trustCaller: true }).catch(() => {
1799
+ });
1800
+ const external = await vscode2.env.asExternalUri(vscode2.Uri.parse(server.url));
1801
+ if (external.authority && external.authority.toLowerCase() !== new URL(server.url).host) server.allowHost(external.authority);
1802
+ const url = external.toString(true);
1551
1803
  this.log.appendLine(`[${docName2(uri)}] ${url}`);
1552
1804
  await openUrl(url);
1553
1805
  return url;
@@ -1563,6 +1815,7 @@ function documentSource(uri, context) {
1563
1815
  const viewKey = VIEW_STATE_PREFIX + uri.toString();
1564
1816
  return {
1565
1817
  name: docName2(uri),
1818
+ ...uri.scheme === "file" && { key: uri.fsPath },
1566
1819
  dir: docDir(uri)?.fsPath ?? "",
1567
1820
  read: async () => (await document()).getText(),
1568
1821
  async write(md) {
@@ -1616,12 +1869,12 @@ async function openCheckout(license, mode, localeHint) {
1616
1869
 
1617
1870
  // packages/vscode/src/mindmapEditor.ts
1618
1871
  var import_node_crypto3 = require("node:crypto");
1619
- var import_promises3 = require("node:fs/promises");
1872
+ var import_promises4 = require("node:fs/promises");
1620
1873
  var vscode4 = __toESM(require("vscode"));
1621
1874
 
1622
1875
  // packages/vscode/src/html.ts
1623
1876
  function webviewHtml(html, { webBase, assetBase, cspSource, nonce, locale }) {
1624
- const osLoc = locale === "auto" ? "" : /^zh\b/i.test(locale) ? "zh" : "en";
1877
+ const osLoc = locale === "auto" ? "" : /^zh(?:[-_.]|$)/i.test(locale) ? "zh" : "en";
1625
1878
  const csp = [
1626
1879
  "default-src 'none'",
1627
1880
  `img-src ${cspSource} https: data: blob:`,
@@ -1632,7 +1885,7 @@ function webviewHtml(html, { webBase, assetBase, cspSource, nonce, locale }) {
1632
1885
  ].join("; ");
1633
1886
  const head = `<meta http-equiv="Content-Security-Policy" content="${csp}">
1634
1887
  <script nonce="${nonce}">window.INKMAP_ASSET_BASE = ${JSON.stringify(assetBase)}; window.INKMAP_LOCALE = ${JSON.stringify(osLoc || locale)};</script>`;
1635
- return html.replace(/<html\b([^>]*)>/i, osLoc ? `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">` : "<html$1>").replace(/ crossorigin/g, "").replace(/(src|href)="\.\/assets\//g, `$1="${webBase}/assets/`).replace(/(src|href)="\.\/(app\.(?:js|css))"/g, `$1="${webBase}/$2"`).replace(/<script /g, `<script nonce="${nonce}" `).replace("<head>", `<head>
1888
+ return html.replace(/<html\b([^>]*)>/i, (_m, attrs) => osLoc ? `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">` : `<html${attrs}>`).replace(/ crossorigin/g, "").replace(/(src|href)="\.\/assets\//g, (_m, attr) => `${attr}="${webBase}/assets/`).replace(/(src|href)="\.\/(app\.(?:js|css))"/g, (_m, attr, file) => `${attr}="${webBase}/${file}"`).replace(/<script /g, () => `<script nonce="${nonce}" `).replace("<head>", () => `<head>
1636
1889
  ${head}`);
1637
1890
  }
1638
1891
 
@@ -1641,28 +1894,42 @@ var VIEW_STATE_PREFIX2 = "inkmap.viewState:";
1641
1894
  var CHANGE_DELAY = 120;
1642
1895
  var REVEAL_DELAY = 150;
1643
1896
  var MindmapEditorProvider = class {
1644
- constructor(context, license, ads) {
1897
+ constructor(context, license) {
1645
1898
  this.context = context;
1646
1899
  this.license = license;
1647
- this.ads = ads;
1648
1900
  }
1649
1901
  static viewType = "inkmap.mindmap";
1650
1902
  panels = /* @__PURE__ */ new Set();
1903
+ readyPanels = /* @__PURE__ */ new WeakSet();
1904
+ panelDocuments = /* @__PURE__ */ new WeakMap();
1905
+ /** An account dialog requested for a document whose editor is still opening; expires so it never pops up later. */
1906
+ pendingAccount;
1651
1907
  /** The chat shortcut was pressed: the focused mind map says what is selected. Anywhere else it just opens the chat. */
1652
1908
  requestChat() {
1653
1909
  const panel = [...this.panels].find((p) => p.active);
1654
1910
  return panel ? panel.webview.postMessage({ type: "requestChat" }) : openChat();
1655
1911
  }
1656
- /** Opens the inline Category 1 account & payment panel directly inside the active Inkmap editor tab. */
1657
- openAccount() {
1658
- const panel = [...this.panels].find((p) => p.active) ?? [...this.panels].find((p) => p.visible);
1659
- if (!panel) return false;
1660
- void panel.webview.postMessage({ type: "openAccount" });
1912
+ /**
1913
+ * Opens the inline Category 1 account & payment panel: in the editor for `document` when given (waiting for it to
1914
+ * finish loading), otherwise in the active or visible Inkmap editor tab.
1915
+ */
1916
+ openAccount(document) {
1917
+ const panels = [...this.panels];
1918
+ const target = document?.toString();
1919
+ const panel = target ? panels.find((p) => this.panelDocuments.get(p) === target) : panels.find((p) => p.active) ?? panels.find((p) => p.visible);
1920
+ if (panel && this.readyPanels.has(panel)) {
1921
+ void panel.webview.postMessage({ type: "openAccount" });
1922
+ return true;
1923
+ }
1924
+ const uri = target ?? (panel && this.panelDocuments.get(panel));
1925
+ if (!uri) return false;
1926
+ this.pendingAccount = { uri, until: Date.now() + 1e4 };
1661
1927
  return true;
1662
1928
  }
1663
1929
  async resolveCustomTextEditor(document, panel) {
1664
1930
  const webview = panel.webview;
1665
1931
  this.panels.add(panel);
1932
+ this.panelDocuments.set(panel, document.uri.toString());
1666
1933
  const webRoot = vscode4.Uri.joinPath(this.context.extensionUri, "dist", "web");
1667
1934
  const assets = docDir(document.uri);
1668
1935
  webview.options = {
@@ -1714,6 +1981,7 @@ var MindmapEditorProvider = class {
1714
1981
  revealTimer = setTimeout(() => post({ type: "reveal", line: e.selections[0].active.line }), REVEAL_DELAY);
1715
1982
  }),
1716
1983
  webview.onDidReceiveMessage(async (msg) => {
1984
+ if (msg.type === "mapMarkdownChange") return;
1717
1985
  const accountAction = msg.type === "checkout" || msg.type === "orderPro" || msg.type === "openExternal" || msg.type === "signOut" || msg.type === "sendPhoneCode" || msg.type === "signInByPhone" || msg.type === "openInBrowser" || msg.type === "telemetry";
1718
1986
  if (!accountAction && msg.type !== "ready" && msg.type !== "viewState" && msg.type !== "select" && !hasAccess(await this.license.state())) {
1719
1987
  if ("id" in msg) return post({ type: "error", id: msg.id, message: t("trialExpired") });
@@ -1721,10 +1989,17 @@ var MindmapEditorProvider = class {
1721
1989
  }
1722
1990
  switch (msg.type) {
1723
1991
  case "ready": {
1992
+ this.readyPanels.add(panel);
1724
1993
  void this.context.globalState?.update("inkmap.hasOpenedMap", true);
1725
1994
  this.license.track?.("doc_open");
1726
- const [license, ads] = await Promise.all([this.license.state(), this.ads()]);
1727
- return post({ type: "doc", doc: state(), license, ads, chat: await chatAvailable() });
1995
+ const [license, chat] = await Promise.all([this.license.state(), chatAvailable()]);
1996
+ await post({ type: "doc", doc: state(), license, chat });
1997
+ const pending = this.pendingAccount;
1998
+ if (pending?.uri === document.uri.toString()) {
1999
+ this.pendingAccount = void 0;
2000
+ if (Date.now() < pending.until) await post({ type: "openAccount" });
2001
+ }
2002
+ return;
1728
2003
  }
1729
2004
  case "openInBrowser":
1730
2005
  return vscode4.commands.executeCommand("inkmap.openInBrowser", document.uri);
@@ -1806,7 +2081,7 @@ var MindmapEditorProvider = class {
1806
2081
  case "sendPhoneCode":
1807
2082
  return post({ type: "phoneCodeSent", id: msg.id, result: await this.license.sendPhoneCode(msg.phone, msg.locale) });
1808
2083
  case "signInByPhone":
1809
- return post({ type: "phoneSignIn", id: msg.id, result: await this.license.signInByPhone(msg.phone, msg.code) });
2084
+ return post({ type: "phoneSignIn", id: msg.id, result: await this.license.signInByPhone(msg.phone, msg.code, msg.locale) });
1810
2085
  case "saveFile":
1811
2086
  return post({ type: "fileSaved", id: msg.id, saved: await saveDataUrl(msg.name, msg.dataUrl, assets) });
1812
2087
  }
@@ -1831,11 +2106,11 @@ async function saveDataUrl(name, dataUrl, dir) {
1831
2106
  });
1832
2107
  if (!target) return false;
1833
2108
  const body = match[2] ? Buffer.from(match[3], "base64") : Buffer.from(decodeURIComponent(match[3]), "utf8");
1834
- await (0, import_promises3.writeFile)(target.fsPath, body);
2109
+ await vscode4.workspace.fs.writeFile(target, body);
1835
2110
  return true;
1836
2111
  }
1837
2112
  async function editorHtml(webview, webRoot, assets) {
1838
- return webviewHtml(await (0, import_promises3.readFile)(vscode4.Uri.joinPath(webRoot, "index.html").fsPath, "utf8"), {
2113
+ return webviewHtml(await (0, import_promises4.readFile)(vscode4.Uri.joinPath(webRoot, "index.html").fsPath, "utf8"), {
1839
2114
  webBase: webview.asWebviewUri(webRoot).toString(),
1840
2115
  assetBase: assets ? webview.asWebviewUri(assets).toString() + "/" : "",
1841
2116
  cspSource: webview.cspSource,
@@ -1845,16 +2120,16 @@ async function editorHtml(webview, webRoot, assets) {
1845
2120
  }
1846
2121
 
1847
2122
  // packages/vscode/src/extension.ts
1848
- function insideOrEqual(root, target) {
2123
+ function insideOrEqual2(root, target) {
1849
2124
  if (root === target) return true;
1850
- const rel = (0, import_node_path3.relative)(root, target);
1851
- return Boolean(rel && !(0, import_node_path3.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path3.sep));
2125
+ const rel = (0, import_node_path4.relative)(root, target);
2126
+ return Boolean(rel && !(0, import_node_path4.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path4.sep));
1852
2127
  }
1853
2128
  function resolveEditorUri(filePath) {
1854
2129
  for (const folder of vscode5.workspace.workspaceFolders ?? []) {
1855
2130
  const folderPath = folder.uri.fsPath || folder.uri.path;
1856
- if (folderPath && insideOrEqual(folderPath, filePath)) {
1857
- const rel = (0, import_node_path3.relative)(folderPath, filePath).split(import_node_path3.sep).join("/");
2131
+ if (folderPath && insideOrEqual2(folderPath, filePath)) {
2132
+ const rel = (0, import_node_path4.relative)(folderPath, filePath).split(import_node_path4.sep).join("/");
1858
2133
  return rel ? vscode5.Uri.joinPath(folder.uri, rel) : folder.uri;
1859
2134
  }
1860
2135
  }
@@ -1872,7 +2147,7 @@ function findColumnForFile(fileUri) {
1872
2147
  if (input?.uri && (input.uri.fsPath === targetFs || input.uri.path === targetFs)) {
1873
2148
  return group.viewColumn;
1874
2149
  }
1875
- if (tab.label && targetFs.endsWith(import_node_path3.sep + tab.label.replace(/^Preview\s+/i, ""))) {
2150
+ if (tab.label && targetFs.endsWith(import_node_path4.sep + tab.label.replace(/^Preview\s+/i, ""))) {
1876
2151
  return group.viewColumn;
1877
2152
  }
1878
2153
  }
@@ -1908,30 +2183,15 @@ async function openFileInEditorPane(filePath) {
1908
2183
  });
1909
2184
  }
1910
2185
  function startMcpTargetBridge() {
1911
- const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1912
- const targetPath = (0, import_node_path3.join)(inkmapDir, "antigravity-target.json");
1913
- const ackPath = (0, import_node_path3.join)(inkmapDir, "antigravity-target-ack.json");
1914
- const statusPath = (0, import_node_path3.join)(inkmapDir, "vscode-bridge-status.json");
2186
+ const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".inkmap");
2187
+ const targetPath = (0, import_node_path4.join)(inkmapDir, "antigravity-target.json");
2188
+ const ackPath = (0, import_node_path4.join)(inkmapDir, "antigravity-target-ack.json");
1915
2189
  let lastSeq = Date.now() - 1e4;
1916
2190
  let debounceTimer;
1917
2191
  let disposed = false;
1918
- const writeBridgeStatus = async () => {
1919
- try {
1920
- if (!(0, import_node_fs2.existsSync)(inkmapDir)) (0, import_node_fs2.mkdirSync)(inkmapDir, { recursive: true, mode: 448 });
1921
- await (0, import_promises4.writeFile)(statusPath, JSON.stringify({
1922
- pid: process.pid,
1923
- activatedAt: Date.now(),
1924
- appName: vscode5.env.appName,
1925
- remoteName: vscode5.env.remoteName,
1926
- focused: vscode5.window.state.focused,
1927
- folders: (vscode5.workspace.workspaceFolders ?? []).map((f) => f.uri.toString())
1928
- }, null, 2), { mode: 384 });
1929
- } catch {
1930
- }
1931
- };
1932
2192
  const syncInitialSeq = async () => {
1933
2193
  try {
1934
- const raw = JSON.parse(await (0, import_promises4.readFile)(targetPath, "utf8"));
2194
+ const raw = JSON.parse(await (0, import_promises5.readFile)(targetPath, "utf8"));
1935
2195
  if (typeof raw?.seq === "number" && raw.seq < Date.now() - 8e3) {
1936
2196
  lastSeq = raw.seq;
1937
2197
  }
@@ -1939,34 +2199,55 @@ function startMcpTargetBridge() {
1939
2199
  }
1940
2200
  await checkTarget();
1941
2201
  };
2202
+ const alreadyAcked = async (seq) => {
2203
+ try {
2204
+ const ack = JSON.parse(await (0, import_promises5.readFile)(ackPath, "utf8"));
2205
+ return Boolean(ack && ack.ok === true && Number(ack.seq) >= seq);
2206
+ } catch {
2207
+ return false;
2208
+ }
2209
+ };
1942
2210
  const checkTarget = async () => {
1943
2211
  if (disposed) return;
2212
+ let claimedSeq = 0;
1944
2213
  try {
1945
- const raw = JSON.parse(await (0, import_promises4.readFile)(targetPath, "utf8"));
2214
+ const raw = JSON.parse(await (0, import_promises5.readFile)(targetPath, "utf8"));
1946
2215
  if (!raw || raw.openInEditorPane !== true) return;
1947
2216
  const seq = Number(raw.seq) || 0;
1948
- if (seq <= lastSeq || typeof raw.file !== "string") return;
1949
- const realTarget = await (0, import_promises4.realpath)(raw.file).catch(() => raw.file);
2217
+ if (seq <= lastSeq || typeof raw.file !== "string" || !/\.md$/i.test(raw.file)) return;
2218
+ if (await alreadyAcked(seq)) {
2219
+ lastSeq = seq;
2220
+ return;
2221
+ }
2222
+ const info = await (0, import_promises5.lstat)(raw.file).catch(() => null);
2223
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > 5 * 1024 * 1024) return;
2224
+ const realTarget = await (0, import_promises5.realpath)(raw.file).catch(() => raw.file);
2225
+ if (!/\.md$/i.test(realTarget)) return;
1950
2226
  const folders = vscode5.workspace.workspaceFolders ?? [];
1951
- let matchesWindow = false;
2227
+ let matchesFolder = false;
1952
2228
  for (const folder of folders) {
1953
2229
  const folderPath = folder.uri.fsPath || folder.uri.path;
1954
2230
  if (!folderPath) continue;
1955
- const realFolder = await (0, import_promises4.realpath)(folderPath).catch(() => folderPath);
1956
- if (insideOrEqual(realFolder, realTarget)) {
1957
- matchesWindow = true;
2231
+ const realFolder = await (0, import_promises5.realpath)(folderPath).catch(() => folderPath);
2232
+ if (insideOrEqual2(realFolder, realTarget)) {
2233
+ matchesFolder = true;
1958
2234
  break;
1959
2235
  }
1960
2236
  }
1961
- if (!matchesWindow && vscode5.window.state.focused) {
1962
- matchesWindow = true;
2237
+ if (!matchesFolder) {
2238
+ if (!vscode5.window.state.focused) return;
2239
+ await new Promise((r) => setTimeout(r, 70));
2240
+ if (disposed || await alreadyAcked(seq)) {
2241
+ lastSeq = seq;
2242
+ return;
2243
+ }
1963
2244
  }
1964
- if (!matchesWindow) return;
1965
2245
  lastSeq = seq;
2246
+ claimedSeq = seq;
1966
2247
  const editorUrl = localEditorUrl(raw.editorUrl);
1967
2248
  if (editorUrl) await openUrlInEditorPane(editorUrl);
1968
2249
  else await openFileInEditorPane(realTarget);
1969
- await (0, import_promises4.writeFile)(ackPath, JSON.stringify({
2250
+ await (0, import_promises5.writeFile)(ackPath, JSON.stringify({
1970
2251
  seq,
1971
2252
  file: realTarget,
1972
2253
  ok: true,
@@ -1974,8 +2255,9 @@ function startMcpTargetBridge() {
1974
2255
  }, null, 2), { mode: 384 }).catch(() => {
1975
2256
  });
1976
2257
  } catch (err) {
1977
- await (0, import_promises4.writeFile)(ackPath, JSON.stringify({
1978
- seq: lastSeq,
2258
+ if (!claimedSeq) return;
2259
+ await (0, import_promises5.writeFile)(ackPath, JSON.stringify({
2260
+ seq: claimedSeq,
1979
2261
  ok: false,
1980
2262
  error: String(err instanceof Error ? err.message : err),
1981
2263
  handledAt: Date.now()
@@ -1983,7 +2265,6 @@ function startMcpTargetBridge() {
1983
2265
  });
1984
2266
  }
1985
2267
  };
1986
- void writeBridgeStatus();
1987
2268
  void syncInitialSeq();
1988
2269
  try {
1989
2270
  if (!(0, import_node_fs2.existsSync)(inkmapDir)) (0, import_node_fs2.mkdirSync)(inkmapDir, { recursive: true, mode: 448 });
@@ -1994,6 +2275,8 @@ function startMcpTargetBridge() {
1994
2275
  void checkTarget();
1995
2276
  }, 60);
1996
2277
  });
2278
+ watcher.on("error", () => {
2279
+ });
1997
2280
  const pollFallback = setInterval(() => {
1998
2281
  void checkTarget();
1999
2282
  }, 1200);
@@ -2011,57 +2294,115 @@ function startMcpTargetBridge() {
2011
2294
  } };
2012
2295
  }
2013
2296
  }
2014
- async function syncDeepSeekHarnessIfInstalled() {
2297
+ var HARNESS_INDEX_URL = "https://zhiyuanv.com/dsh-index.json";
2298
+ var HARNESS_MARKET_BUNDLE = "@deepseek-ai/dsh-experimental-plugin-market-bundle";
2299
+ var HARNESS_PROMPTED = "inkmap.deepseekHarnessPrompted";
2300
+ var harnessProfileDir = () => (0, import_node_path4.join)(process.env.DSH_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".dsh"), "profiles", "desktop");
2301
+ async function readHarnessProfile(dir) {
2302
+ const patchPath = (0, import_node_path4.join)(dir, "cordis.patch.yml");
2303
+ const patch = (0, import_node_fs2.existsSync)(patchPath) ? await (0, import_promises5.readFile)(patchPath, "utf8").catch(() => "") : "";
2304
+ let pkg;
2015
2305
  try {
2016
- const dshHome = process.env.DSH_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".dsh");
2017
- const profileDir = (0, import_node_path3.join)(dshHome, "profiles", "desktop");
2018
- if (!(0, import_node_fs2.existsSync)(profileDir)) return;
2019
- const indexUrl = "https://zhiyuanv.com/dsh-index.json";
2020
- const patchPath = (0, import_node_path3.join)(profileDir, "cordis.patch.yml");
2021
- const existingPatch = (0, import_node_fs2.existsSync)(patchPath) ? await (0, import_promises4.readFile)(patchPath, "utf8").catch(() => "") : "";
2022
- if (!existingPatch.includes(indexUrl)) {
2023
- const snippet = `
2024
- - id: plugin-market
2306
+ pkg = JSON.parse(await (0, import_promises5.readFile)((0, import_node_path4.join)(dir, "package.json"), "utf8"));
2307
+ } catch {
2308
+ }
2309
+ const bundles = pkg?.dsh?.profile?.bundles;
2310
+ return {
2311
+ dir,
2312
+ patch,
2313
+ pkg,
2314
+ needsIndex: !patch.includes(HARNESS_INDEX_URL) && !/^\s*-\s*id:\s*plugin-market\b/m.test(patch),
2315
+ needsBundle: Array.isArray(bundles) && !bundles.includes(HARNESS_MARKET_BUNDLE),
2316
+ needsPlugin: Boolean(pkg) && !pkg?.dependencies?.["dsh-inkmap"]
2317
+ };
2318
+ }
2319
+ var harnessSetUp = (profile) => !profile.needsIndex && !profile.needsBundle && !profile.needsPlugin;
2320
+ function harnessCli() {
2321
+ return [
2322
+ process.platform === "darwin" ? "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh" : "",
2323
+ process.platform === "darwin" ? (0, import_node_path4.join)((0, import_node_os4.homedir)(), "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh") : "",
2324
+ process.platform === "win32" ? (0, import_node_path4.join)(process.env.LOCALAPPDATA || (0, import_node_path4.join)((0, import_node_os4.homedir)(), "AppData", "Local"), "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd") : ""
2325
+ ].find((candidate) => candidate && (0, import_node_fs2.existsSync)(candidate));
2326
+ }
2327
+ function runHarnessCli(cli, args) {
2328
+ return new Promise((resolve3, reject) => {
2329
+ const q = (s) => `"${s.replace(/"/g, '""').replace(/%/g, '"^%"')}"`;
2330
+ const child = process.platform === "win32" && !cli.toLowerCase().endsWith(".exe") ? (0, import_node_child_process4.spawn)("cmd.exe", ["/d", "/s", "/c", `"${[cli, ...args].map(q).join(" ")}"`], {
2331
+ stdio: "ignore",
2332
+ windowsVerbatimArguments: true,
2333
+ windowsHide: true
2334
+ }) : (0, import_node_child_process4.spawn)(cli, args, { stdio: "ignore" });
2335
+ const timer = setTimeout(() => {
2336
+ child.kill();
2337
+ reject(new Error("dsh did not finish in time"));
2338
+ }, 18e4);
2339
+ child.on("error", (err) => {
2340
+ clearTimeout(timer);
2341
+ reject(err);
2342
+ });
2343
+ child.on("exit", (code) => {
2344
+ clearTimeout(timer);
2345
+ if (code === 0) resolve3();
2346
+ else reject(new Error(`dsh exited with code ${code}`));
2347
+ });
2348
+ });
2349
+ }
2350
+ async function installIntoHarness(profile) {
2351
+ if (profile.needsIndex) {
2352
+ const snippet = `- id: plugin-market
2025
2353
  name: "@deepseek-ai/dsh-plugin-market"
2026
2354
  config:
2027
2355
  indexes:
2028
- - ${indexUrl}
2356
+ - ${HARNESS_INDEX_URL}
2029
2357
  `;
2030
- await (0, import_promises4.writeFile)(patchPath, existingPatch.replace(/\n*$/, "") + snippet, "utf8").catch(() => {
2031
- });
2032
- }
2033
- const pkgPath = (0, import_node_path3.join)(profileDir, "package.json");
2034
- if (!(0, import_node_fs2.existsSync)(pkgPath)) return;
2035
- const pkg = JSON.parse(await (0, import_promises4.readFile)(pkgPath, "utf8"));
2036
- const bundles = pkg.dsh?.profile?.bundles;
2037
- if (Array.isArray(bundles) && !bundles.includes("@deepseek-ai/dsh-experimental-plugin-market-bundle")) {
2038
- bundles.push("@deepseek-ai/dsh-experimental-plugin-market-bundle");
2039
- await (0, import_promises4.writeFile)(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8").catch(() => {
2040
- });
2041
- }
2042
- if (pkg.dependencies?.["dsh-inkmap"]) return;
2043
- const stagedDsh = (0, import_node_path3.join)(process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap"), "dsh-inkmap");
2044
- const spec = (0, import_node_fs2.existsSync)((0, import_node_path3.join)(stagedDsh, "package.json")) ? stagedDsh : "dsh-inkmap";
2045
- const candidates = [
2046
- process.platform === "darwin" ? "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh" : "",
2047
- process.platform === "darwin" ? (0, import_node_path3.join)((0, import_node_os3.homedir)(), "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh") : "",
2048
- process.platform === "win32" ? (0, import_node_path3.join)(process.env.LOCALAPPDATA || (0, import_node_path3.join)((0, import_node_os3.homedir)(), "AppData", "Local"), "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd") : ""
2049
- ].filter(Boolean);
2050
- const dshBin = candidates.find((c) => (0, import_node_fs2.existsSync)(c));
2051
- if (dshBin) {
2052
- const child = (0, import_node_child_process4.spawn)(dshBin, ["plugin", "--profile", "desktop", "add", spec], { stdio: "ignore", detached: true });
2053
- child.unref();
2054
- }
2358
+ const trimmed = profile.patch.trim();
2359
+ const next = !trimmed || trimmed === "[]" ? snippet : profile.patch.replace(/\n*$/, "\n\n") + snippet;
2360
+ await (0, import_promises5.writeFile)((0, import_node_path4.join)(profile.dir, "cordis.patch.yml"), next, "utf8");
2361
+ }
2362
+ if (profile.needsBundle && profile.pkg?.dsh?.profile?.bundles) {
2363
+ profile.pkg.dsh.profile.bundles.push(HARNESS_MARKET_BUNDLE);
2364
+ await (0, import_promises5.writeFile)((0, import_node_path4.join)(profile.dir, "package.json"), JSON.stringify(profile.pkg, null, 2) + "\n", "utf8");
2365
+ }
2366
+ if (!profile.needsPlugin) return "installed";
2367
+ const cli = harnessCli();
2368
+ if (!cli) return "configured";
2369
+ const staged = (0, import_node_path4.join)(process.env.INKMAP_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".inkmap"), "dsh-inkmap");
2370
+ await runHarnessCli(cli, ["plugin", "--profile", "desktop", "add", (0, import_node_fs2.existsSync)((0, import_node_path4.join)(staged, "package.json")) ? staged : "dsh-inkmap"]);
2371
+ return "installed";
2372
+ }
2373
+ async function installInDeepSeekHarness() {
2374
+ const dir = harnessProfileDir();
2375
+ if (!(0, import_node_fs2.existsSync)(dir)) return void vscode5.window.showWarningMessage(t("harnessNotFound"));
2376
+ try {
2377
+ const profile = await readHarnessProfile(dir);
2378
+ if (harnessSetUp(profile)) return void vscode5.window.showInformationMessage(t("harnessAlready"));
2379
+ const result = await vscode5.window.withProgress(
2380
+ { location: vscode5.ProgressLocation.Notification, title: t("harnessInstalling") },
2381
+ () => installIntoHarness(profile)
2382
+ );
2383
+ void vscode5.window.showInformationMessage(t(result === "installed" ? "harnessInstalled" : "harnessConfigured"));
2384
+ } catch (err) {
2385
+ void vscode5.window.showErrorMessage(t("harnessFailed", { error: err instanceof Error ? err.message : String(err) }));
2386
+ }
2387
+ }
2388
+ async function offerDeepSeekHarnessSetup(context) {
2389
+ try {
2390
+ if (context.globalState.get(HARNESS_PROMPTED)) return;
2391
+ const dir = harnessProfileDir();
2392
+ if (!(0, import_node_fs2.existsSync)(dir) || harnessSetUp(await readHarnessProfile(dir))) return;
2393
+ await context.globalState.update(HARNESS_PROMPTED, true);
2394
+ const install = t("harnessInstall");
2395
+ const pick = await vscode5.window.showInformationMessage(t("harnessOffer"), install, t("harnessNoThanks"));
2396
+ if (pick === install) await installInDeepSeekHarness();
2055
2397
  } catch {
2056
2398
  }
2057
2399
  }
2058
2400
  function activate(context) {
2059
- void syncDeepSeekHarnessIfInstalled();
2401
+ void offerDeepSeekHarnessSetup(context);
2060
2402
  const log = vscode5.window.createOutputChannel("Inkmap");
2061
2403
  const license = extensionLicense(context);
2062
2404
  license.track?.("plugin_activate");
2063
- const ads = adFeed(PRODUCT.adFeedUrl);
2064
- const browsers = new BrowserServers(context, vscode5.Uri.joinPath(context.extensionUri, "dist", "web").fsPath, log, license, ads);
2405
+ const browsers = new BrowserServers(context, vscode5.Uri.joinPath(context.extensionUri, "dist", "web").fsPath, log, license);
2065
2406
  const withUri = (run) => (arg) => {
2066
2407
  const uri = targetUri(arg);
2067
2408
  if (!uri) return vscode5.window.showWarningMessage(t("openMarkdownFirst"));
@@ -2073,6 +2414,16 @@ function activate(context) {
2073
2414
  preserveFocus: true
2074
2415
  })
2075
2416
  );
2417
+ const openDemo = async () => {
2418
+ const dir = context.globalStorageUri?.fsPath || (0, import_node_path4.join)((0, import_node_os4.tmpdir)(), "inkmap-welcome");
2419
+ (0, import_node_fs2.mkdirSync)(dir, { recursive: true });
2420
+ const demoPath = (0, import_node_path4.join)(dir, "Inkmap-Welcome.md");
2421
+ if (!(0, import_node_fs2.existsSync)(demoPath)) await (0, import_promises5.writeFile)(demoPath, t("welcomeDoc"), "utf8");
2422
+ await vscode5.commands.executeCommand("vscode.openWith", vscode5.Uri.file(demoPath), MindmapEditorProvider.viewType, {
2423
+ viewColumn: vscode5.ViewColumn.Active,
2424
+ preserveFocus: false
2425
+ });
2426
+ };
2076
2427
  const maybeOfferOnboarding = (editor) => {
2077
2428
  if (!editor || editor.document.languageId !== "markdown" || editor.document.uri.scheme !== "file") return;
2078
2429
  if (context.globalState.get("inkmap.hasOpenedMap") || context.globalState.get("inkmap.onboardingPrompted")) return;
@@ -2086,9 +2437,77 @@ function activate(context) {
2086
2437
  }
2087
2438
  });
2088
2439
  };
2089
- const editors = new MindmapEditorProvider(context, license, ads);
2440
+ const maybeOfferWelcome = () => {
2441
+ const active = vscode5.window.activeTextEditor;
2442
+ if (active?.document.languageId === "markdown" && active.document.uri.scheme === "file") {
2443
+ maybeOfferOnboarding(active);
2444
+ return;
2445
+ }
2446
+ if (context.globalState.get("inkmap.hasOpenedMap") || context.globalState.get("inkmap.welcomePrompted") || context.globalState.get("inkmap.onboardingPrompted")) {
2447
+ return;
2448
+ }
2449
+ void context.globalState.update("inkmap.welcomePrompted", true);
2450
+ license.track?.("onboarding_view");
2451
+ void vscode5.window.showInformationMessage(t("welcomeTip"), t("welcomeAction")).then((pick) => {
2452
+ if (pick) {
2453
+ license.track?.("onboarding_open");
2454
+ void openDemo();
2455
+ }
2456
+ });
2457
+ };
2458
+ const statusBar = vscode5.window.createStatusBarItem?.(vscode5.StatusBarAlignment?.Right ?? 2, 100);
2459
+ if (statusBar) {
2460
+ statusBar.text = t("statusBarLabel");
2461
+ statusBar.tooltip = t("statusBarTooltip");
2462
+ statusBar.command = "inkmap.openToSide";
2463
+ const updateStatusBar = (editor) => {
2464
+ if (editor?.document.languageId === "markdown" && editor.document.uri.scheme === "file") statusBar.show();
2465
+ else statusBar.hide();
2466
+ };
2467
+ updateStatusBar(vscode5.window.activeTextEditor);
2468
+ context.subscriptions.push(statusBar, vscode5.window.onDidChangeActiveTextEditor(updateStatusBar));
2469
+ }
2470
+ const editors = new MindmapEditorProvider(context, license);
2090
2471
  chatAvailable().then((available) => vscode5.commands.executeCommand("setContext", "inkmap.chatAvailable", available));
2091
- maybeOfferOnboarding(vscode5.window.activeTextEditor);
2472
+ maybeOfferWelcome();
2473
+ if (vscode5.languages?.registerCodeLensProvider) {
2474
+ const lensEmitter = vscode5.EventEmitter ? new vscode5.EventEmitter() : void 0;
2475
+ const lensProvider = {
2476
+ ...lensEmitter && { onDidChangeCodeLenses: lensEmitter.event },
2477
+ provideCodeLenses(document) {
2478
+ if (document.uri.scheme !== "file") return [];
2479
+ if (vscode5.workspace.getConfiguration("inkmap", document.uri).get("codeLens", true) === false) {
2480
+ return [];
2481
+ }
2482
+ const top = new vscode5.Range(0, 0, 0, 0);
2483
+ return [
2484
+ new vscode5.CodeLens(top, {
2485
+ title: t("codeLensOpen"),
2486
+ tooltip: t("codeLensOpenTooltip"),
2487
+ command: "inkmap.codeLensOpen",
2488
+ arguments: [document.uri]
2489
+ }),
2490
+ new vscode5.CodeLens(top, {
2491
+ title: t("codeLensBrowser"),
2492
+ tooltip: t("codeLensBrowserTooltip"),
2493
+ command: "inkmap.openInBrowser",
2494
+ arguments: [document.uri]
2495
+ })
2496
+ ];
2497
+ }
2498
+ };
2499
+ context.subscriptions.push(vscode5.languages.registerCodeLensProvider({ language: "markdown", scheme: "file" }, lensProvider));
2500
+ if (lensEmitter) {
2501
+ context.subscriptions.push(lensEmitter);
2502
+ if (vscode5.workspace.onDidChangeConfiguration) {
2503
+ context.subscriptions.push(
2504
+ vscode5.workspace.onDidChangeConfiguration((e) => {
2505
+ if (e.affectsConfiguration("inkmap.codeLens")) lensEmitter.fire();
2506
+ })
2507
+ );
2508
+ }
2509
+ }
2510
+ }
2092
2511
  context.subscriptions.push(
2093
2512
  log,
2094
2513
  license,
@@ -2096,10 +2515,13 @@ function activate(context) {
2096
2515
  startMcpTargetBridge(),
2097
2516
  vscode5.window.onDidChangeActiveTextEditor(maybeOfferOnboarding),
2098
2517
  vscode5.window.registerUriHandler({
2099
- handleUri(uri) {
2518
+ async handleUri(uri) {
2100
2519
  if (uri.path === "/open") {
2101
- const target = new URLSearchParams(uri.query).get("path");
2102
- if (target) void openFileInEditorPane(target);
2520
+ const target = new URLSearchParams(uri.query).get("path")?.trim();
2521
+ if (!target || !(0, import_node_path4.isAbsolute)(target) || !/\.md$/i.test(target)) return;
2522
+ const info = await (0, import_promises5.lstat)(target).catch(() => null);
2523
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > 5 * 1024 * 1024) return;
2524
+ void openFileInEditorPane(target);
2103
2525
  }
2104
2526
  }
2105
2527
  }),
@@ -2109,6 +2531,12 @@ function activate(context) {
2109
2531
  vscode5.commands.registerCommand("inkmap.addToChat", () => editors.requestChat()),
2110
2532
  vscode5.commands.registerCommand("inkmap.open", openToSide),
2111
2533
  vscode5.commands.registerCommand("inkmap.openToSide", openToSide),
2534
+ vscode5.commands.registerCommand("inkmap.codeLensOpen", (arg) => {
2535
+ if (!context.globalState.get("inkmap.hasOpenedMap")) {
2536
+ license.track?.("onboarding_open");
2537
+ }
2538
+ return openToSide(arg);
2539
+ }),
2112
2540
  vscode5.commands.registerCommand(
2113
2541
  "inkmap.showSource",
2114
2542
  withUri((uri) => vscode5.window.showTextDocument(uri, { viewColumn: vscode5.ViewColumn.Beside, preview: false }))
@@ -2118,7 +2546,7 @@ function activate(context) {
2118
2546
  withUri(async (uri) => {
2119
2547
  if (!hasAccess(await license.state())) {
2120
2548
  await openToSide(uri);
2121
- setTimeout(() => editors.openAccount(), 250);
2549
+ editors.openAccount(uri);
2122
2550
  return;
2123
2551
  }
2124
2552
  try {
@@ -2131,12 +2559,14 @@ function activate(context) {
2131
2559
  }
2132
2560
  })
2133
2561
  ),
2562
+ vscode5.commands.registerCommand("inkmap.installDeepSeekHarness", installInDeepSeekHarness),
2563
+ vscode5.commands.registerCommand("inkmap.openDemo", openDemo),
2134
2564
  vscode5.commands.registerCommand("inkmap.upgrade", async (arg) => {
2135
2565
  if (editors.openAccount()) return;
2136
2566
  const uri = targetUri(arg);
2137
2567
  if (!uri) return vscode5.window.showWarningMessage(t("openMarkdownFirst"));
2138
2568
  await openToSide(uri);
2139
- setTimeout(() => editors.openAccount(), 280);
2569
+ editors.openAccount(uri);
2140
2570
  })
2141
2571
  );
2142
2572
  }