inkmap-mcp 0.0.0-stage → 0.2.5

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.
@@ -0,0 +1,1198 @@
1
+ // packages/antigravity/src/main.mjs
2
+ import { execFile } from "node:child_process";
3
+ import { createHash as createHash2 } from "node:crypto";
4
+ import { readFileSync, readdirSync } from "node:fs";
5
+ import { lstat as lstat2, readdir, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
6
+ import { homedir as homedir4 } from "node:os";
7
+ import { basename as basename2, dirname as dirname4, extname as extname2, isAbsolute as isAbsolute2, join as join4, normalize as normalize2, relative as relative2, resolve as resolve3, sep as sep3 } from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+
10
+ // packages/core/dist/product.js
11
+ var PRODUCT = {
12
+ id: "inkmap-pro",
13
+ entitlement: "inkmap.pro",
14
+ /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
15
+ adFeedUrl: ""
16
+ };
17
+ var YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
18
+ function billingFlowUrl(raw, origin, mode, legacy = false) {
19
+ if (typeof raw !== "string")
20
+ throw new Error("Invalid Yunfan account link.");
21
+ const url = new URL(raw);
22
+ const base = mode === "restore" && !legacy ? "login" : "checkout";
23
+ if (url.protocol !== "https:" || url.origin !== origin || url.username || url.password || url.search || url.hash || !new RegExp(`^/billing/${base}/[0-9a-f]{32}$`).test(url.pathname)) {
24
+ throw new Error("Invalid Yunfan account link.");
25
+ }
26
+ return url.href;
27
+ }
28
+ var DAY_MS = 24 * 60 * 60 * 1e3;
29
+ var TRIAL_MS = 7 * DAY_MS;
30
+ function hasAccess(state, now = Date.now()) {
31
+ return state.pro || (state.trialUntil ?? 0) > now;
32
+ }
33
+
34
+ // packages/core/dist/index.js
35
+ function sanitizeViewState(raw) {
36
+ if (!raw || typeof raw !== "object")
37
+ return void 0;
38
+ const r = raw;
39
+ let folds;
40
+ if (r.folds && typeof r.folds === "object" && !Array.isArray(r.folds)) {
41
+ const out = {};
42
+ for (const [k, v] of Object.entries(r.folds).slice(0, 5e3)) {
43
+ if (typeof v === "boolean")
44
+ out[k] = v;
45
+ }
46
+ if (Object.keys(out).length)
47
+ folds = out;
48
+ }
49
+ let view;
50
+ if (r.view && typeof r.view === "object") {
51
+ const v = r.view;
52
+ if (typeof v.scale === "number" && Number.isFinite(v.scale) && v.scale >= 0.05 && v.scale <= 20 && typeof v.dx === "number" && Number.isFinite(v.dx) && Math.abs(v.dx) < 1e6 && typeof v.dy === "number" && Number.isFinite(v.dy) && Math.abs(v.dy) < 1e6) {
53
+ view = { scale: v.scale, dx: v.dx, dy: v.dy };
54
+ }
55
+ }
56
+ return folds || view ? { ...folds && { folds }, ...view && { view } } : void 0;
57
+ }
58
+
59
+ // packages/cli/dist/license.js
60
+ import { link, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
61
+ import { randomUUID } from "node:crypto";
62
+ import { homedir } from "node:os";
63
+ import { dirname, join } from "node:path";
64
+ function billingOrigin(raw) {
65
+ if (!raw)
66
+ throw new Error("Inkmap checkout is not configured.");
67
+ const url = new URL(raw);
68
+ if (url.protocol !== "https:" || url.origin !== raw.replace(/\/$/, "")) {
69
+ throw new Error("Inkmap checkout requires an HTTPS origin.");
70
+ }
71
+ return url.origin;
72
+ }
73
+ function licenseService(storage, getOrigin, { loginOnly = false } = {}) {
74
+ const listeners = /* @__PURE__ */ new Set();
75
+ let current = { pro: false };
76
+ let trial;
77
+ let trialTimer;
78
+ let timer;
79
+ let lastCheck = 0;
80
+ let disposed = false;
81
+ let generation = 0;
82
+ let connection;
83
+ let activeOrigin;
84
+ let pendingWrite = Promise.resolve();
85
+ let pendingCheckout;
86
+ let cachedOrder;
87
+ function mergeCookies(existing, response) {
88
+ const map = /* @__PURE__ */ new Map();
89
+ if (existing) {
90
+ for (const pair of existing.split(/;\s*/)) {
91
+ const eq = pair.indexOf("=");
92
+ if (eq > 0)
93
+ map.set(pair.slice(0, eq).trim(), pair.slice(eq + 1).trim());
94
+ }
95
+ }
96
+ const headers = response.headers;
97
+ const rawList = typeof headers.getSetCookie === "function" ? headers.getSetCookie() : response.headers.get("set-cookie") ? [response.headers.get("set-cookie")] : [];
98
+ for (const raw of rawList) {
99
+ const first = raw.split(";")[0]?.trim() ?? "";
100
+ const eq = first.indexOf("=");
101
+ if (eq > 0)
102
+ map.set(first.slice(0, eq).trim(), first.slice(eq + 1).trim());
103
+ }
104
+ return map.size ? [...map.entries()].map(([k, v]) => `${k}=${v}`).join("; ") : void 0;
105
+ }
106
+ function maskPhone(phone) {
107
+ const clean = phone.trim();
108
+ return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
109
+ }
110
+ function writeSession(operation) {
111
+ const next = pendingWrite.then(operation);
112
+ pendingWrite = next.then(() => {
113
+ }, () => {
114
+ });
115
+ return next;
116
+ }
117
+ async function createCheckoutFlow(origin, existingToken, existingCookie) {
118
+ const response = await fetch(origin + "/billing/v1/connections", {
119
+ method: "POST",
120
+ headers: {
121
+ "content-type": "application/json",
122
+ ...existingToken && { authorization: "Bearer " + existingToken },
123
+ ...existingCookie && { cookie: existingCookie }
124
+ },
125
+ redirect: "error",
126
+ body: JSON.stringify({ product: PRODUCT.id, mode: "buy" }),
127
+ signal: AbortSignal.timeout(8e3)
128
+ });
129
+ if (!response.ok)
130
+ throw new Error("Unable to start the checkout flow.");
131
+ const cookie = mergeCookies(existingCookie, response);
132
+ const data = await response.json();
133
+ const url = billingFlowUrl(data.url, origin, "buy", false);
134
+ if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
135
+ throw new Error("Invalid Inkmap checkout response.");
136
+ }
137
+ return { origin, url, token: data.token, ...cookie && { cookie } };
138
+ }
139
+ function checkoutPost(checkoutUrl, action, origin, body, token, cookie) {
140
+ return fetch(checkoutUrl + "/" + action, {
141
+ method: "POST",
142
+ headers: {
143
+ "content-type": "application/json",
144
+ origin,
145
+ ...token && { authorization: "Bearer " + token },
146
+ ...cookie && { cookie }
147
+ },
148
+ redirect: "error",
149
+ body: JSON.stringify(body),
150
+ signal: AbortSignal.timeout(12e3)
151
+ });
152
+ }
153
+ function phoneRequest(origin, action, phone, code) {
154
+ return fetch(origin + "/billing/v1/phone-sign-in/" + action, {
155
+ method: "POST",
156
+ headers: { "content-type": "application/json" },
157
+ redirect: "error",
158
+ body: JSON.stringify({ product: PRODUCT.id, phone, code }),
159
+ signal: AbortSignal.timeout(12e3)
160
+ });
161
+ }
162
+ function phoneFailure(status) {
163
+ if (status === 400 || status === 401)
164
+ return { ok: false, reason: "invalid" };
165
+ return { ok: false, reason: status === 429 ? "rateLimited" : "unavailable" };
166
+ }
167
+ function entitlement(origin, token) {
168
+ return fetch(origin + "/billing/v1/entitlement", {
169
+ headers: { authorization: "Bearer " + token },
170
+ redirect: "error",
171
+ signal: AbortSignal.timeout(5e3)
172
+ });
173
+ }
174
+ function applyEntitlement(state) {
175
+ lastCheck = Date.now();
176
+ const connected = state.connected === true;
177
+ const active = connected && state.active === true && state.entitlement === PRODUCT.entitlement;
178
+ const account = typeof state.account === "string" ? state.account.trim().slice(0, 64) : "";
179
+ if (!connected && state.pending === true && current.connected)
180
+ return;
181
+ update(active, connected, account);
182
+ }
183
+ function update(pro, connected = false, account) {
184
+ const cleanAccount = connected && account ? account : void 0;
185
+ if (current.pro === pro && Boolean(current.connected) === connected && current.account === cleanAccount)
186
+ return;
187
+ current = {
188
+ pro,
189
+ ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
190
+ ...connected && { connected: true },
191
+ ...cleanAccount && { account: cleanAccount }
192
+ };
193
+ for (const listener of listeners)
194
+ listener(current);
195
+ }
196
+ async function startTrial() {
197
+ const trialUntil = await localTrialDeadline().catch(() => void 0);
198
+ if (disposed || trialUntil === void 0)
199
+ return;
200
+ current = { ...current, trialUntil };
201
+ const remaining = trialUntil - Date.now();
202
+ if (remaining > 0) {
203
+ trialTimer = setTimeout(() => {
204
+ for (const listener of listeners)
205
+ listener(current);
206
+ }, remaining);
207
+ trialTimer.unref();
208
+ }
209
+ }
210
+ function schedule(delay) {
211
+ clearTimeout(timer);
212
+ if (disposed)
213
+ return;
214
+ timer = setTimeout(() => void refresh(), delay);
215
+ timer.unref();
216
+ }
217
+ function refresh() {
218
+ if (connection)
219
+ return connection;
220
+ const version = generation;
221
+ connection = (async () => {
222
+ let token;
223
+ let delay = 6e4;
224
+ try {
225
+ const origin = billingOrigin(getOrigin());
226
+ if (origin !== activeOrigin) {
227
+ lastCheck = 0;
228
+ activeOrigin = origin;
229
+ update(false);
230
+ }
231
+ const stored = await storage.read();
232
+ if (version !== generation || disposed)
233
+ return;
234
+ if (!stored)
235
+ return update(false);
236
+ const record = JSON.parse(stored);
237
+ if (record.origin !== origin || typeof record.token !== "string")
238
+ return update(false);
239
+ token = record.token;
240
+ const response = await entitlement(origin, record.token);
241
+ if (version !== generation || disposed)
242
+ return;
243
+ if (response.status === 401) {
244
+ token = void 0;
245
+ return await writeSession(async () => {
246
+ if (version !== generation || disposed)
247
+ return;
248
+ await storage.write(void 0).catch(() => {
249
+ });
250
+ update(false);
251
+ });
252
+ }
253
+ if (!response.ok)
254
+ throw new Error("Unable to check Inkmap Pro.");
255
+ const state = await response.json();
256
+ if (version !== generation || disposed)
257
+ return;
258
+ applyEntitlement(state);
259
+ delay = state.active !== true && state.pending === true ? 4e3 : 6e4;
260
+ } catch {
261
+ if (version === generation && Date.now() - lastCheck > 15 * 6e4)
262
+ update(false);
263
+ } finally {
264
+ if (version === generation && token)
265
+ schedule(delay);
266
+ }
267
+ })().finally(() => {
268
+ connection = void 0;
269
+ });
270
+ return connection;
271
+ }
272
+ return {
273
+ async state() {
274
+ await (trial ??= startTrial());
275
+ if (Date.now() - lastCheck >= 4e3)
276
+ await refresh();
277
+ return current;
278
+ },
279
+ async connect(mode) {
280
+ if (loginOnly && mode !== "restore")
281
+ throw new Error("Only Yunfan account sign-in is available.");
282
+ const origin = billingOrigin(getOrigin());
283
+ const version = generation;
284
+ let existingToken;
285
+ try {
286
+ const stored = await storage.read();
287
+ if (stored) {
288
+ const record = JSON.parse(stored);
289
+ if (record.origin === origin && typeof record.token === "string")
290
+ existingToken = record.token;
291
+ }
292
+ } catch {
293
+ }
294
+ const create = (path, body) => fetch(origin + "/billing/v1/" + path, {
295
+ method: "POST",
296
+ headers: {
297
+ "content-type": "application/json",
298
+ ...existingToken && { authorization: "Bearer " + existingToken }
299
+ },
300
+ redirect: "error",
301
+ body: JSON.stringify(body),
302
+ signal: AbortSignal.timeout(8e3)
303
+ });
304
+ let legacy = false;
305
+ let response = await (mode === "restore" ? create("restore-connections", { product: PRODUCT.id }) : create("connections", { product: PRODUCT.id, mode }));
306
+ if (mode === "restore" && !loginOnly && response.status === 404) {
307
+ legacy = true;
308
+ response = await create("connections", { product: PRODUCT.id, mode });
309
+ }
310
+ if (!response.ok)
311
+ throw new Error("Unable to start the Yunfan account flow.");
312
+ const data = await response.json();
313
+ const url = billingFlowUrl(data.url, origin, mode, legacy);
314
+ if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
315
+ throw new Error("Invalid Inkmap checkout response.");
316
+ }
317
+ await writeSession(async () => {
318
+ if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
319
+ throw new Error("The Yunfan account session changed. Please try again.");
320
+ }
321
+ await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
322
+ ++generation;
323
+ lastCheck = 0;
324
+ if (mode !== "buy" || !current.connected)
325
+ update(false);
326
+ schedule(1e3);
327
+ });
328
+ return url;
329
+ },
330
+ async orderPro() {
331
+ if (loginOnly)
332
+ throw new Error("Only Yunfan account sign-in is available.");
333
+ const origin = billingOrigin(getOrigin());
334
+ if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
335
+ const hit = cachedOrder.result;
336
+ cachedOrder = void 0;
337
+ schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
338
+ return hit;
339
+ }
340
+ const version = generation;
341
+ let record;
342
+ try {
343
+ const stored = await storage.read();
344
+ if (stored)
345
+ record = JSON.parse(stored);
346
+ } catch {
347
+ }
348
+ const requestOrder = async (checkoutUrl, token, cookie, persist) => {
349
+ const res = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie);
350
+ if (res.status === 401 || res.status === 403 || res.status === 404 || res.status === 410)
351
+ return null;
352
+ if (!res.ok)
353
+ throw new Error("Unable to load WeChat Pay QR code.");
354
+ const nextCookie = mergeCookies(cookie, res);
355
+ const data = await res.json();
356
+ if (persist || nextCookie !== cookie) {
357
+ await writeSession(async () => {
358
+ if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
359
+ return;
360
+ await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
361
+ if (persist) {
362
+ ++generation;
363
+ lastCheck = 0;
364
+ }
365
+ });
366
+ }
367
+ if (data.active === true) {
368
+ const rights = await entitlement(origin, token).catch(() => null);
369
+ if (rights?.ok)
370
+ applyEntitlement(await rights.json());
371
+ else
372
+ update(true, true, current.account);
373
+ schedule(6e4);
374
+ return { status: "active", state: current };
375
+ }
376
+ if (typeof data.qr === "string" && data.qr) {
377
+ schedule(4e3);
378
+ const qr = data.qr.startsWith("data:image/") ? data.qr : "data:image/png;base64," + data.qr;
379
+ return {
380
+ status: "qr",
381
+ qr,
382
+ amountFen: typeof data.amountFen === "number" ? data.amountFen : 2990,
383
+ ...typeof data.expiresAt === "string" && { expiresAt: data.expiresAt }
384
+ };
385
+ }
386
+ if (typeof data.checkoutUrl === "string" && /^https:\/\//.test(data.checkoutUrl)) {
387
+ schedule(4e3);
388
+ return { status: "redirect", url: data.checkoutUrl };
389
+ }
390
+ throw new Error("Invalid Inkmap checkout response.");
391
+ };
392
+ const existingCookie = record?.origin === origin && typeof record.cookie === "string" ? record.cookie : void 0;
393
+ if (record?.origin === origin && typeof record.checkoutUrl === "string" && typeof record.token === "string") {
394
+ const existing = await requestOrder(record.checkoutUrl, record.token, existingCookie, false);
395
+ if (existing)
396
+ return existing;
397
+ }
398
+ const existingToken = record?.origin === origin && typeof record.token === "string" ? record.token : void 0;
399
+ const flow = await createCheckoutFlow(origin, existingToken, existingCookie);
400
+ const ordered = await requestOrder(flow.url, flow.token, flow.cookie, true);
401
+ if (ordered)
402
+ return ordered;
403
+ pendingCheckout = flow;
404
+ return { status: "needsPhone" };
405
+ },
406
+ async sendPhoneCode(phone) {
407
+ if (typeof phone !== "string" || !phone.trim() || phone.length > 40)
408
+ return phoneFailure(400);
409
+ try {
410
+ const origin = billingOrigin(getOrigin());
411
+ if (!loginOnly) {
412
+ try {
413
+ if (!pendingCheckout || pendingCheckout.origin !== origin) {
414
+ pendingCheckout = await createCheckoutFlow(origin);
415
+ }
416
+ let smsRes = await checkoutPost(pendingCheckout.url, "sms", origin, { phone }, pendingCheckout.token, pendingCheckout.cookie);
417
+ if (smsRes.status === 410 || smsRes.status === 404) {
418
+ pendingCheckout = await createCheckoutFlow(origin);
419
+ smsRes = await checkoutPost(pendingCheckout.url, "sms", origin, { phone }, pendingCheckout.token, pendingCheckout.cookie);
420
+ }
421
+ pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
422
+ return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
423
+ } catch {
424
+ pendingCheckout = void 0;
425
+ }
426
+ }
427
+ const response = await phoneRequest(origin, "send", phone);
428
+ return response.status === 204 ? { ok: true, value: void 0 } : phoneFailure(response.status);
429
+ } catch {
430
+ return phoneFailure();
431
+ }
432
+ },
433
+ async signInByPhone(phone, code) {
434
+ if (typeof phone !== "string" || !phone.trim() || phone.length > 40 || typeof code !== "string" || !/^\d{6}$/.test(code))
435
+ return phoneFailure(400);
436
+ const version = generation;
437
+ try {
438
+ const origin = billingOrigin(getOrigin());
439
+ let token;
440
+ let checkoutUrl;
441
+ let cookie;
442
+ if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
443
+ const loginRes = await checkoutPost(pendingCheckout.url, "login", origin, { phone, code }, pendingCheckout.token, pendingCheckout.cookie);
444
+ if (!loginRes.ok) {
445
+ if (loginRes.status === 410 || loginRes.status === 404)
446
+ pendingCheckout = void 0;
447
+ return phoneFailure(loginRes.status);
448
+ }
449
+ cookie = mergeCookies(pendingCheckout.cookie, loginRes);
450
+ token = pendingCheckout.token;
451
+ checkoutUrl = pendingCheckout.url;
452
+ pendingCheckout = void 0;
453
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
454
+ if (orderRes?.ok) {
455
+ cookie = mergeCookies(cookie, orderRes);
456
+ const orderData = await orderRes.json().catch(() => null);
457
+ if (orderData && typeof orderData === "object") {
458
+ if (orderData.active === true) {
459
+ cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
460
+ } else if (typeof orderData.qr === "string" && orderData.qr) {
461
+ const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
462
+ cachedOrder = {
463
+ at: Date.now(),
464
+ origin,
465
+ result: {
466
+ status: "qr",
467
+ qr,
468
+ amountFen: typeof orderData.amountFen === "number" ? orderData.amountFen : 2990,
469
+ ...typeof orderData.expiresAt === "string" && { expiresAt: orderData.expiresAt }
470
+ }
471
+ };
472
+ } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
473
+ cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
474
+ }
475
+ }
476
+ }
477
+ } else {
478
+ const response = await phoneRequest(origin, "verify", phone, code);
479
+ if (response.status !== 201)
480
+ return phoneFailure(response.status);
481
+ cookie = mergeCookies(void 0, response);
482
+ const body = await response.json();
483
+ token = body.token;
484
+ }
485
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(token))
486
+ return phoneFailure();
487
+ let state = { entitlement: PRODUCT.entitlement, connected: true, account: maskPhone(phone) };
488
+ const rights = await entitlement(origin, token).catch(() => null);
489
+ if (rights?.ok) {
490
+ state = await rights.json();
491
+ if (state.entitlement !== PRODUCT.entitlement)
492
+ return phoneFailure();
493
+ if (state.connected !== true) {
494
+ if (!checkoutUrl)
495
+ return phoneFailure();
496
+ state.connected = true;
497
+ }
498
+ if (checkoutUrl && (!state.account || typeof state.account !== "string" || !state.account.trim())) {
499
+ state.account = maskPhone(phone);
500
+ }
501
+ } else if (!checkoutUrl) {
502
+ return phoneFailure();
503
+ }
504
+ if (cachedOrder?.result.status === "active")
505
+ state.active = true;
506
+ return await writeSession(async () => {
507
+ if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
508
+ return phoneFailure();
509
+ await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
510
+ ++generation;
511
+ activeOrigin = origin;
512
+ applyEntitlement(state);
513
+ if (cachedOrder?.result.status === "active")
514
+ cachedOrder.result.state = current;
515
+ schedule(cachedOrder?.result.status === "qr" ? 4e3 : 6e4);
516
+ return { ok: true, value: current };
517
+ });
518
+ } catch {
519
+ return phoneFailure();
520
+ }
521
+ },
522
+ async deactivate() {
523
+ pendingCheckout = void 0;
524
+ cachedOrder = void 0;
525
+ const saved = await writeSession(async () => {
526
+ const previous = await storage.read();
527
+ await storage.write(void 0);
528
+ ++generation;
529
+ clearTimeout(timer);
530
+ lastCheck = 0;
531
+ update(false);
532
+ return previous;
533
+ });
534
+ if (!saved)
535
+ return;
536
+ try {
537
+ const { origin, token } = JSON.parse(saved);
538
+ if (origin !== billingOrigin(getOrigin()))
539
+ return;
540
+ await fetch(origin + "/billing/v1/entitlement", {
541
+ method: "DELETE",
542
+ headers: { authorization: "Bearer " + token },
543
+ redirect: "error",
544
+ signal: AbortSignal.timeout(5e3)
545
+ });
546
+ } catch {
547
+ }
548
+ },
549
+ onChange(listener) {
550
+ listeners.add(listener);
551
+ return () => listeners.delete(listener);
552
+ },
553
+ dispose() {
554
+ disposed = true;
555
+ clearTimeout(trialTimer);
556
+ clearTimeout(timer);
557
+ listeners.clear();
558
+ }
559
+ };
560
+ }
561
+ function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "billing-session")) {
562
+ return {
563
+ read: () => readFile(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
564
+ async write(token) {
565
+ if (!token)
566
+ return rm(path, { force: true });
567
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
568
+ const temporary = path + "." + randomUUID();
569
+ try {
570
+ await writeFile(temporary, token, { mode: 384, flag: "wx" });
571
+ await rename(temporary, path);
572
+ } finally {
573
+ await rm(temporary, { force: true });
574
+ }
575
+ }
576
+ };
577
+ }
578
+ async function localTrialDeadline() {
579
+ const path = join(homedir(), ".inkmap", "trial-start");
580
+ const now = Date.now();
581
+ let value;
582
+ try {
583
+ value = await readFile(path, "utf8");
584
+ } catch (error) {
585
+ if (error.code !== "ENOENT")
586
+ throw error;
587
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
588
+ const temporary = path + "." + randomUUID();
589
+ try {
590
+ await writeFile(temporary, String(now), { mode: 384, flag: "wx" });
591
+ await link(temporary, path).catch((error2) => {
592
+ if (error2.code !== "EEXIST")
593
+ throw error2;
594
+ });
595
+ } finally {
596
+ await rm(temporary, { force: true });
597
+ }
598
+ value = await readFile(path, "utf8");
599
+ }
600
+ const started = Number(value);
601
+ return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
602
+ }
603
+ var AD_TTL = 6 * 60 * 60 * 1e3;
604
+
605
+ // packages/cli/dist/server.js
606
+ import { createHash, randomBytes } from "node:crypto";
607
+ import { watch } from "node:fs";
608
+ import { mkdir as mkdir2, readFile as readFile2, realpath, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
609
+ import { homedir as homedir2 } from "node:os";
610
+ import { basename, dirname as dirname2, extname, join as join2, normalize, resolve, sep } from "node:path";
611
+ var MAX_BODY = 20 * 1024 * 1024;
612
+ var hash = (s) => createHash("sha1").update(s).digest("hex");
613
+ function docName(path) {
614
+ return basename(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
615
+ }
616
+ function viewStateFile(key) {
617
+ const base = process.env.INKMAP_HOME ?? join2(homedir2(), ".inkmap");
618
+ return join2(base, "view-state", hash(key) + ".json");
619
+ }
620
+ async function readDiskViewState(key) {
621
+ try {
622
+ return sanitizeViewState(JSON.parse(await readFile2(viewStateFile(key), "utf8")));
623
+ } catch {
624
+ return void 0;
625
+ }
626
+ }
627
+ async function writeDiskViewState(key, state) {
628
+ const target = viewStateFile(key);
629
+ await mkdir2(dirname2(target), { recursive: true, mode: 448 });
630
+ const temp = `${target}.${process.pid}.${Date.now()}`;
631
+ try {
632
+ await writeFile2(temp, JSON.stringify(state), { mode: 384 });
633
+ await rename2(temp, target);
634
+ } finally {
635
+ await rm2(temp, { force: true }).catch(() => {
636
+ });
637
+ }
638
+ }
639
+ async function fileSource(file, log = () => {
640
+ }) {
641
+ const path = resolve(file);
642
+ if (!(await stat(path)).isFile())
643
+ throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
644
+ const dir = dirname2(path);
645
+ return {
646
+ name: docName(path),
647
+ key: path,
648
+ dir,
649
+ read: () => readFile2(path, "utf8"),
650
+ async write(md) {
651
+ await writeFile2(path, md, "utf8");
652
+ log(`\u5DF2\u5199\u56DE ${path}`);
653
+ },
654
+ watch(onChange) {
655
+ const watcher = watch(dir, (_, changed) => {
656
+ if (!changed || changed === basename(path))
657
+ onChange();
658
+ });
659
+ return () => watcher.close();
660
+ },
661
+ readView: () => readDiskViewState(path),
662
+ writeView: (state) => writeDiskViewState(path, state)
663
+ };
664
+ }
665
+
666
+ // packages/antigravity/src/select.mjs
667
+ import { randomUUID as randomUUID2 } from "node:crypto";
668
+ import { lstat, mkdir as mkdir3, realpath as realpath2, rename as rename3, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
669
+ import { homedir as homedir3 } from "node:os";
670
+ import { dirname as dirname3, isAbsolute, join as join3, relative, resolve as resolve2, sep as sep2 } from "node:path";
671
+ var MAX_BYTES = 5 * 1024 * 1024;
672
+ function targetStateFile() {
673
+ const base = process.env.INKMAP_HOME ?? join3(homedir3(), ".inkmap");
674
+ return join3(base, "antigravity-target.json");
675
+ }
676
+ function inside(root, file) {
677
+ const rel = relative(root, file);
678
+ return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep2));
679
+ }
680
+ async function selectTargetFile(rawFile, rawWorkspace) {
681
+ if (typeof rawFile !== "string" || !/\.md$/i.test(rawFile.trim())) {
682
+ throw new Error("\u8BF7\u6307\u5B9A\u4E00\u4E2A .md \u6216 .markmap.md \u6587\u4EF6\u8DEF\u5F84\u3002");
683
+ }
684
+ const candidate = resolve2(rawFile.trim());
685
+ const info = await lstat(candidate);
686
+ if (!info.isFile() || info.size > MAX_BYTES) {
687
+ throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002");
688
+ }
689
+ const file = await realpath2(candidate);
690
+ if (file !== candidate && !/\.md$/i.test(file)) {
691
+ throw new Error("\u65E0\u6548\u7684 Markdown \u6587\u4EF6\u8DEF\u5F84\u3002");
692
+ }
693
+ let workspace = dirname3(file);
694
+ if (rawWorkspace) {
695
+ const resolvedWs = await realpath2(resolve2(rawWorkspace)).catch(() => null);
696
+ if (resolvedWs && inside(resolvedWs, file)) workspace = resolvedWs;
697
+ } else {
698
+ const cwd = await realpath2(process.cwd()).catch(() => null);
699
+ if (cwd && inside(cwd, file)) workspace = cwd;
700
+ }
701
+ const statePath = targetStateFile();
702
+ await mkdir3(dirname3(statePath), { recursive: true, mode: 448 });
703
+ const temp = `${statePath}.${process.pid}.${randomUUID2()}`;
704
+ const payload = { file, workspace, seq: Date.now() };
705
+ try {
706
+ await writeFile3(temp, JSON.stringify(payload, null, 2) + "\n", { mode: 384 });
707
+ await rename3(temp, statePath);
708
+ } finally {
709
+ await rm3(temp, { force: true }).catch(() => {
710
+ });
711
+ }
712
+ return payload;
713
+ }
714
+ if (process.argv[1] && /select\.m?js$/i.test(process.argv[1])) {
715
+ const args = process.argv.slice(2);
716
+ let fileArg = "";
717
+ let workspaceArg = "";
718
+ for (let i = 0; i < args.length; i++) {
719
+ if (args[i] === "--workspace" && args[i + 1]) {
720
+ workspaceArg = args[++i];
721
+ } else if (!fileArg) {
722
+ fileArg = args[i];
723
+ }
724
+ }
725
+ selectTargetFile(fileArg, workspaceArg).then(
726
+ ({ file }) => {
727
+ console.log(`\u5DF2\u9009\u5B9A Inkmap \u6587\u6863\uFF1A${file}`);
728
+ console.log("\u5728\u5BF9\u8BDD\u4E2D\u8F93\u51FA\u4EE5\u4E0B\u80F6\u56CA\u6309\u94AE\u5373\u53EF\u5728\u53F3\u4FA7\u6253\u5F00\uFF1A[Inkmap](sidecar://inkmap/inkmap/)");
729
+ },
730
+ (error) => {
731
+ console.error(error instanceof Error ? error.message : String(error));
732
+ process.exitCode = 1;
733
+ }
734
+ );
735
+ }
736
+
737
+ // packages/antigravity/src/main.mjs
738
+ var __dirname = dirname4(fileURLToPath(import.meta.url));
739
+ var defaultWebRoot = join4(__dirname, "web");
740
+ var SidecarResponse = class {
741
+ constructor(body, { contentType = "text/plain", status = 200, headers } = {}) {
742
+ this.body = body;
743
+ this.contentType = contentType;
744
+ this.status = status;
745
+ this.headers = headers;
746
+ }
747
+ };
748
+ var MAX_BYTES2 = 5 * 1024 * 1024;
749
+ var MAX_SCAN_DEPTH = 4;
750
+ var MAX_FILES = 200;
751
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
752
+ ".git",
753
+ ".hg",
754
+ ".svn",
755
+ "node_modules",
756
+ "dist",
757
+ "build",
758
+ "out",
759
+ ".next",
760
+ ".nuxt",
761
+ ".agents",
762
+ ".agent",
763
+ ".gemini",
764
+ ".venv",
765
+ "venv",
766
+ "target",
767
+ "coverage"
768
+ ]);
769
+ var TYPES = {
770
+ ".html": "text/html; charset=utf-8",
771
+ ".js": "application/javascript; charset=utf-8",
772
+ ".css": "text/css; charset=utf-8",
773
+ ".svg": "image/svg+xml",
774
+ ".png": "image/png",
775
+ ".jpg": "image/jpeg",
776
+ ".jpeg": "image/jpeg",
777
+ ".gif": "image/gif",
778
+ ".webp": "image/webp",
779
+ ".woff2": "font/woff2",
780
+ ".woff": "font/woff",
781
+ ".ttf": "font/ttf",
782
+ ".json": "application/json; charset=utf-8"
783
+ };
784
+ var hash2 = (text) => createHash2("sha1").update(text).digest("hex");
785
+ function insideOrEqual(root, target) {
786
+ if (root === target) return true;
787
+ const rel = relative2(root, target);
788
+ return Boolean(rel && !isAbsolute2(rel) && rel !== ".." && !rel.startsWith(".." + sep3));
789
+ }
790
+ function uriToPath(uri) {
791
+ if (typeof uri !== "string" || !uri) return null;
792
+ try {
793
+ if (uri.startsWith("file://")) return fileURLToPath(uri);
794
+ if (isAbsolute2(uri)) return uri;
795
+ } catch {
796
+ }
797
+ return null;
798
+ }
799
+ async function readTargetSelection() {
800
+ try {
801
+ const raw = JSON.parse(await readFile3(targetStateFile(), "utf8"));
802
+ if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file)) return null;
803
+ const file = await realpath3(raw.file);
804
+ const info = await lstat2(file);
805
+ if (!info.isFile() || info.size > MAX_BYTES2) return null;
806
+ const workspace = typeof raw.workspace === "string" ? await realpath3(raw.workspace).catch(() => dirname4(file)) : dirname4(file);
807
+ if (!insideOrEqual(workspace, file)) return null;
808
+ return { file, workspace, seq: Number(raw.seq) || 0 };
809
+ } catch {
810
+ return null;
811
+ }
812
+ }
813
+ async function discoverAntigravityProjects() {
814
+ const projectsDir = join4(process.env.ANTIGRAVITY_CONFIG_DIR || join4(homedir4(), ".gemini", "config"), "projects");
815
+ const roots = [];
816
+ let entries = [];
817
+ try {
818
+ entries = await readdir(projectsDir);
819
+ } catch {
820
+ return roots;
821
+ }
822
+ for (const name of entries) {
823
+ if (!name.endsWith(".json")) continue;
824
+ try {
825
+ const data = JSON.parse(await readFile3(join4(projectsDir, name), "utf8"));
826
+ const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
827
+ for (const r of resources) {
828
+ const uri = r?.gitFolder?.folderUri || r?.folderUri;
829
+ const p = uriToPath(uri);
830
+ if (!p) continue;
831
+ const real = await realpath3(p).catch(() => null);
832
+ if (real) roots.push({ path: real, name: data.name || basename2(real) });
833
+ }
834
+ } catch {
835
+ }
836
+ }
837
+ return roots;
838
+ }
839
+ async function scanMarkdownFiles(rootDir) {
840
+ const found = [];
841
+ async function walk(dir, depth) {
842
+ if (depth > MAX_SCAN_DEPTH || found.length >= MAX_FILES) return;
843
+ let entries = [];
844
+ try {
845
+ entries = await readdir(dir, { withFileTypes: true });
846
+ } catch {
847
+ return;
848
+ }
849
+ for (const entry of entries) {
850
+ if (found.length >= MAX_FILES) break;
851
+ if (entry.name.startsWith(".") && entry.isDirectory()) continue;
852
+ const full = join4(dir, entry.name);
853
+ if (entry.isDirectory()) {
854
+ if (!SKIP_DIRS.has(entry.name)) await walk(full, depth + 1);
855
+ } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
856
+ try {
857
+ const info = await lstat2(full);
858
+ if (info.isFile() && info.size <= MAX_BYTES2) {
859
+ const real = await realpath3(full);
860
+ if (insideOrEqual(rootDir, real)) found.push(real);
861
+ }
862
+ } catch {
863
+ }
864
+ }
865
+ }
866
+ }
867
+ await walk(rootDir, 0);
868
+ found.sort((a, b) => {
869
+ const aMarkmap = /\.markmap\.md$/i.test(a) ? 0 : 1;
870
+ const bMarkmap = /\.markmap\.md$/i.test(b) ? 0 : 1;
871
+ if (aMarkmap !== bMarkmap) return aMarkmap - bMarkmap;
872
+ return a.localeCompare(b);
873
+ });
874
+ return found;
875
+ }
876
+ function openExternalUrl(url) {
877
+ if (typeof url !== "string" || !/^https:\/\//i.test(url)) return;
878
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
879
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
880
+ execFile(cmd, args, () => {
881
+ });
882
+ }
883
+ function createAntigravitySidecar({
884
+ app,
885
+ webRoot = defaultWebRoot,
886
+ billingOrigin: billingOrigin2 = () => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN
887
+ } = {}) {
888
+ const license = licenseService(fileSessionStorage(), billingOrigin2);
889
+ let activeFile = null;
890
+ async function allowedRoots(workspaceUris = []) {
891
+ const roots = /* @__PURE__ */ new Map();
892
+ const uris = Array.isArray(workspaceUris) ? workspaceUris : [];
893
+ for (const uri of uris) {
894
+ const p = uriToPath(uri);
895
+ if (!p) continue;
896
+ const real = await realpath3(p).catch(() => null);
897
+ if (real && !roots.has(real)) {
898
+ roots.set(real, { path: real, name: basename2(real), active: true });
899
+ }
900
+ }
901
+ const target = await readTargetSelection();
902
+ if (target && !roots.has(target.workspace)) {
903
+ roots.set(target.workspace, { path: target.workspace, name: basename2(target.workspace), active: roots.size === 0 });
904
+ }
905
+ for (const proj of await discoverAntigravityProjects()) {
906
+ if (!roots.has(proj.path)) {
907
+ roots.set(proj.path, { path: proj.path, name: proj.name, active: false });
908
+ }
909
+ }
910
+ if (roots.size === 0) {
911
+ const cwd = await realpath3(process.cwd()).catch(() => null);
912
+ if (cwd) roots.set(cwd, { path: cwd, name: basename2(cwd), active: true });
913
+ }
914
+ return { roots: [...roots.values()], target };
915
+ }
916
+ async function assertAllowedMarkdownFile(candidatePath, workspaceUris = []) {
917
+ if (typeof candidatePath !== "string" || !candidatePath.trim()) {
918
+ throw new Error("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002");
919
+ }
920
+ const raw = uriToPath(candidatePath.trim()) || resolve3(candidatePath.trim());
921
+ if (!/\.md$/i.test(raw)) throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
922
+ const info = await lstat2(raw);
923
+ if (!info.isFile() || info.size > MAX_BYTES2) throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002");
924
+ const real = await realpath3(raw);
925
+ if (real !== raw || !/\.md$/i.test(real)) throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u6216\u975E Markdown \u6587\u4EF6\u3002");
926
+ const { roots, target } = await allowedRoots(workspaceUris);
927
+ const permitted = target && target.file === real || roots.some((r) => insideOrEqual(r.path, real));
928
+ if (!permitted) throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u5141\u8BB8\u7684\u5DE5\u4F5C\u533A\u6216\u9879\u76EE\u76EE\u5F55\u5185\u3002");
929
+ return real;
930
+ }
931
+ async function readDocState(filePath) {
932
+ const source = await fileSource(filePath);
933
+ const [md, viewState] = await Promise.all([source.read(), source.readView?.()]);
934
+ return {
935
+ source,
936
+ doc: {
937
+ name: source.name,
938
+ md,
939
+ version: hash2(md),
940
+ writable: true,
941
+ ...viewState && { viewState }
942
+ }
943
+ };
944
+ }
945
+ async function collectFiles(workspaceUris = []) {
946
+ const { roots, target } = await allowedRoots(workspaceUris);
947
+ const items = [];
948
+ const seen = /* @__PURE__ */ new Set();
949
+ if (target && !seen.has(target.file)) {
950
+ const owner = roots.find((r) => insideOrEqual(r.path, target.file));
951
+ const rel = owner ? relative2(owner.path, target.file) : basename2(target.file);
952
+ items.push({
953
+ path: target.file,
954
+ uri: pathToFileURL(target.file).href,
955
+ label: owner ? `${owner.name} / ${rel}` : rel,
956
+ group: owner?.active ? "active" : "project"
957
+ });
958
+ seen.add(target.file);
959
+ }
960
+ for (const root of roots) {
961
+ const files = await scanMarkdownFiles(root.path);
962
+ for (const file of files) {
963
+ if (seen.has(file)) continue;
964
+ seen.add(file);
965
+ const rel = relative2(root.path, file);
966
+ items.push({
967
+ path: file,
968
+ uri: pathToFileURL(file).href,
969
+ label: roots.length > 1 ? `${root.name} / ${rel}` : rel,
970
+ group: root.active ? "active" : "project"
971
+ });
972
+ }
973
+ }
974
+ return { files: items, target };
975
+ }
976
+ const rawHtml = readFileSync(join4(webRoot, "index.html"), "utf8");
977
+ const pageHtml = rawHtml.replace(
978
+ "<head>",
979
+ '<head>\n <script src="/preload.js"></script>\n <script src="/bridge.js"></script>'
980
+ );
981
+ app.page("/", () => {
982
+ console.log("[inkmap] GET /");
983
+ return pageHtml;
984
+ });
985
+ const bridgeJs = readFileSync(join4(__dirname, "bridge.js"), "utf8");
986
+ app.page("/bridge.js", () => {
987
+ console.log("[inkmap] GET /bridge.js");
988
+ return bridgeJs;
989
+ });
990
+ app.api("/bridge.js", () => new SidecarResponse(bridgeJs, { contentType: "application/javascript; charset=utf-8" }), "GET");
991
+ try {
992
+ const appJs = readFileSync(join4(webRoot, "app.js"), "utf8");
993
+ app.page("/app.js", () => {
994
+ console.log(`[inkmap] GET /app.js (${appJs.length} chars)`);
995
+ return appJs;
996
+ });
997
+ } catch {
998
+ }
999
+ app.api("/api/debug", async (data) => {
1000
+ console.log("[inkmap] CLIENT_DEBUG:", JSON.stringify(data));
1001
+ return { ok: true };
1002
+ }, "POST");
1003
+ function registerStaticDir(dir, prefix = "") {
1004
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1005
+ const full = join4(dir, entry.name);
1006
+ const route = `${prefix}/${entry.name}`;
1007
+ if (entry.isDirectory()) {
1008
+ registerStaticDir(full, route);
1009
+ } else if (entry.isFile() && route !== "/index.html") {
1010
+ const contentType = TYPES[extname2(entry.name).toLowerCase()] || "application/octet-stream";
1011
+ const body = readFileSync(full);
1012
+ app.api(route, () => {
1013
+ console.log(`[inkmap] GET ${route} (${body.length} bytes)`);
1014
+ return new SidecarResponse(body, {
1015
+ contentType,
1016
+ headers: { "Cache-Control": "private, max-age=3600" }
1017
+ });
1018
+ }, "GET");
1019
+ }
1020
+ }
1021
+ }
1022
+ registerStaticDir(webRoot);
1023
+ app.api("/api/init", async (data) => {
1024
+ const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1025
+ console.log(`[inkmap] /api/init workspaces=${JSON.stringify(workspaceUris)} requested=${data?.requestedFile || ""}`);
1026
+ const { files, target } = await collectFiles(workspaceUris);
1027
+ let chosen = null;
1028
+ if (typeof data?.requestedFile === "string" && data.requestedFile.trim()) {
1029
+ chosen = await assertAllowedMarkdownFile(data.requestedFile, workspaceUris).catch(() => null);
1030
+ }
1031
+ if (!chosen && target?.file) {
1032
+ chosen = target.file;
1033
+ }
1034
+ if (!chosen && activeFile && files.some((f) => f.path === activeFile)) {
1035
+ chosen = activeFile;
1036
+ }
1037
+ if (!chosen) {
1038
+ const activeGroup = files.filter((f) => f.group === "active");
1039
+ chosen = (activeGroup[0] || files[0])?.path || null;
1040
+ }
1041
+ const lic = await license.state();
1042
+ if (!chosen) {
1043
+ return {
1044
+ files,
1045
+ currentFile: null,
1046
+ currentFileUri: null,
1047
+ targetSeq: target?.seq || 0,
1048
+ license: lic,
1049
+ doc: {
1050
+ name: "Inkmap",
1051
+ md: "# Inkmap\n\n- \u8BF7\u5728\u5DE5\u4F5C\u533A\u4E2D\u6DFB\u52A0\u6216\u9009\u62E9\u4E00\u4EFD `.md` / `.markmap.md` \u6587\u4EF6\n- \u6216\u5728\u5BF9\u8BDD\u4E2D\u544A\u8BC9 AI\uFF1A\u300C\u7528 Inkmap \u6253\u5F00\u67D0\u6587\u4EF6\u300D\n",
1052
+ version: "empty",
1053
+ writable: false
1054
+ }
1055
+ };
1056
+ }
1057
+ activeFile = chosen;
1058
+ const { doc } = await readDocState(chosen);
1059
+ return {
1060
+ files,
1061
+ currentFile: chosen,
1062
+ currentFileUri: pathToFileURL(chosen).href,
1063
+ targetSeq: target?.seq || 0,
1064
+ license: lic,
1065
+ doc
1066
+ };
1067
+ }, "POST");
1068
+ app.api("/api/open", async (data) => {
1069
+ const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1070
+ const file = await assertAllowedMarkdownFile(data?.file, workspaceUris);
1071
+ activeFile = file;
1072
+ const [{ doc }, { files, target }] = await Promise.all([
1073
+ readDocState(file),
1074
+ collectFiles(workspaceUris)
1075
+ ]);
1076
+ return {
1077
+ files,
1078
+ currentFile: file,
1079
+ currentFileUri: pathToFileURL(file).href,
1080
+ targetSeq: target?.seq || 0,
1081
+ doc
1082
+ };
1083
+ }, "POST");
1084
+ const pollHandler = async (data) => {
1085
+ const target = await readTargetSelection();
1086
+ const clientSeq = Number(data?.targetSeq) || 0;
1087
+ if (target && target.seq > clientSeq && target.file !== data?.file) {
1088
+ console.log(`[inkmap] /api/poll SWITCH data=${JSON.stringify(data)} targetSeq=${target.seq}`);
1089
+ activeFile = target.file;
1090
+ const { doc } = await readDocState(target.file);
1091
+ return {
1092
+ switchedFile: target.file,
1093
+ currentFileUri: pathToFileURL(target.file).href,
1094
+ targetSeq: target.seq,
1095
+ doc
1096
+ };
1097
+ }
1098
+ const file = data?.file || activeFile;
1099
+ if (!file) return { unchanged: true, targetSeq: target?.seq || clientSeq };
1100
+ try {
1101
+ const { doc } = await readDocState(file);
1102
+ if (data?.version && doc.version !== data.version) {
1103
+ return { changed: true, doc, targetSeq: target?.seq || clientSeq };
1104
+ }
1105
+ return { unchanged: true, targetSeq: target?.seq || clientSeq };
1106
+ } catch {
1107
+ return { unchanged: true, targetSeq: target?.seq || clientSeq };
1108
+ }
1109
+ };
1110
+ app.api("/api/poll", pollHandler, "GET");
1111
+ app.api("/api/poll", pollHandler, "POST");
1112
+ app.api("/api/save", async (data) => {
1113
+ const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1114
+ const file = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris);
1115
+ const md = data?.md;
1116
+ if (typeof md !== "string" || Buffer.byteLength(md, "utf8") > MAX_BYTES2) {
1117
+ throw new Error("Markdown \u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7 5 MiB \u9650\u5236\u3002");
1118
+ }
1119
+ if (!hasAccess(await license.state())) {
1120
+ throw new Error("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u6216\u89E3\u9501 Pro\u3002");
1121
+ }
1122
+ const { source, doc } = await readDocState(file);
1123
+ if (data?.baseVersion && data.baseVersion !== doc.version) {
1124
+ return { ok: false, conflict: true, doc };
1125
+ }
1126
+ if (md !== doc.md) {
1127
+ await source.write(md);
1128
+ }
1129
+ return { ok: true, version: hash2(md) };
1130
+ }, "POST");
1131
+ app.api("/api/view", async (data) => {
1132
+ const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1133
+ const file = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris).catch(() => null);
1134
+ if (!file) return { ok: false };
1135
+ const cleaned = sanitizeViewState(data?.state);
1136
+ if (cleaned) {
1137
+ const source = await fileSource(file);
1138
+ await source.writeView?.(cleaned).catch(() => {
1139
+ });
1140
+ }
1141
+ return { ok: true };
1142
+ }, "POST");
1143
+ app.api("/api/license", async () => await license.state(), "GET");
1144
+ app.api("/api/checkout", async (data) => {
1145
+ const mode = data?.mode === "buy" ? "buy" : "restore";
1146
+ const url = await license.connect(mode);
1147
+ openExternalUrl(url);
1148
+ return { url };
1149
+ }, "POST");
1150
+ app.api("/api/order-pro", async () => {
1151
+ const result = await license.orderPro();
1152
+ if (result.status === "redirect") openExternalUrl(result.url);
1153
+ return { result };
1154
+ }, "POST");
1155
+ app.api("/api/phone-send", async (data) => {
1156
+ return { result: await license.sendPhoneCode(String(data?.phone ?? "")) };
1157
+ }, "POST");
1158
+ app.api("/api/phone-verify", async (data) => {
1159
+ return { result: await license.signInByPhone(String(data?.phone ?? ""), String(data?.code ?? "")) };
1160
+ }, "POST");
1161
+ app.api("/api/signout", async () => {
1162
+ await license.deactivate();
1163
+ return { state: await license.state() };
1164
+ }, "POST");
1165
+ app.api("/api/doc-asset", async (data) => {
1166
+ const notFound = () => new SidecarResponse("not found", { status: 404 });
1167
+ const file = activeFile;
1168
+ const rel = typeof data?.path === "string" ? data.path.replace(/\?.*$/, "") : "";
1169
+ if (!file || !rel) return notFound();
1170
+ try {
1171
+ const dir = await realpath3(dirname4(file));
1172
+ const candidate = normalize2(join4(dir, decodeURIComponent(rel)));
1173
+ if (!insideOrEqual(dir, candidate) || candidate === dir) return notFound();
1174
+ const realAsset = await realpath3(candidate);
1175
+ if (!insideOrEqual(dir, realAsset) || !/\.(?:png|jpe?g|gif|webp|svg)$/i.test(realAsset)) return notFound();
1176
+ const info = await lstat2(realAsset);
1177
+ if (!info.isFile() || info.size > MAX_BYTES2) return notFound();
1178
+ const type = TYPES[extname2(realAsset).toLowerCase()] || "application/octet-stream";
1179
+ return new SidecarResponse(await readFile3(realAsset), {
1180
+ contentType: type,
1181
+ headers: { "Cache-Control": "no-cache" }
1182
+ });
1183
+ } catch {
1184
+ return notFound();
1185
+ }
1186
+ }, "GET");
1187
+ return { app, license };
1188
+ }
1189
+ if (process.env.ANTIGRAVITY_SIDECAR_WEB_PORT) {
1190
+ const sdk = await import("sidecar_sdk").catch(
1191
+ () => import(pathToFileURL(join4(homedir4(), ".gemini", "config", "node_modules", "sidecar_sdk", "index.mjs")).href)
1192
+ );
1193
+ const { app } = createAntigravitySidecar({ app: new sdk.SidecarApp() });
1194
+ app.run();
1195
+ }
1196
+ export {
1197
+ createAntigravitySidecar
1198
+ };