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