figma-lupa 0.2.0 → 0.2.1

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/dist/cli.js CHANGED
@@ -2276,7 +2276,7 @@ var require_websocket = __commonJS({
2276
2276
  var EventEmitter = __require("events");
2277
2277
  var https = __require("https");
2278
2278
  var http = __require("http");
2279
- var net = __require("net");
2279
+ var net2 = __require("net");
2280
2280
  var tls = __require("tls");
2281
2281
  var { randomBytes, createHash } = __require("crypto");
2282
2282
  var { Duplex, Readable } = __require("stream");
@@ -3033,12 +3033,12 @@ var require_websocket = __commonJS({
3033
3033
  }
3034
3034
  function netConnect(options) {
3035
3035
  options.path = options.socketPath;
3036
- return net.connect(options);
3036
+ return net2.connect(options);
3037
3037
  }
3038
3038
  function tlsConnect(options) {
3039
3039
  options.path = void 0;
3040
3040
  if (!options.servername && options.servername !== "") {
3041
- options.servername = net.isIP(options.host) ? "" : options.host;
3041
+ options.servername = net2.isIP(options.host) ? "" : options.host;
3042
3042
  }
3043
3043
  return tls.connect(options);
3044
3044
  }
@@ -3743,7 +3743,7 @@ var init_package = __esm({
3743
3743
  "package.json"() {
3744
3744
  package_default = {
3745
3745
  name: "figma-lupa",
3746
- version: "0.2.0",
3746
+ version: "0.2.1",
3747
3747
  description: "Read-only Figma CLI, MCP server and plugin for pixel-faithful design-to-code with a small context footprint.",
3748
3748
  type: "module",
3749
3749
  license: "GPL-3.0-or-later",
@@ -3867,12 +3867,23 @@ var init_hub = __esm({
3867
3867
  waiters = /* @__PURE__ */ new Set();
3868
3868
  want;
3869
3869
  activeAt = Date.now();
3870
+ onStopRequest;
3871
+ version;
3872
+ /** Peer: the hub's version and whether it stops on request. */
3873
+ hubVersion;
3874
+ hubCanStop = false;
3870
3875
  constructor(opts = {}) {
3871
3876
  this.port = opts.port ?? Number(process.env.LUPA_PORT ?? DEFAULT_PORT);
3872
3877
  this.host = opts.host ?? "127.0.0.1";
3873
3878
  this.log = opts.log ?? (() => {
3874
3879
  });
3875
3880
  this.want = opts.role ?? "auto";
3881
+ this.onStopRequest = opts.onStopRequest;
3882
+ this.version = opts.version ?? SERVER_VERSION;
3883
+ }
3884
+ /** Peer: ask the hub to stop. Only `lupa serve` hubs (hubCanStop) do. */
3885
+ askHubToStop() {
3886
+ if (this.hubSocket?.readyState === import_websocket.default.OPEN) this.hubSocket.send(JSON.stringify({ t: "stop" }));
3876
3887
  }
3877
3888
  /** Milliseconds since this process last handled or forwarded a request. */
3878
3889
  get idleMs() {
@@ -4025,7 +4036,7 @@ var init_hub = __esm({
4025
4036
  ws.terminate();
4026
4037
  finish(false);
4027
4038
  }, 2e3);
4028
- ws.on("open", () => ws.send(JSON.stringify({ t: "hello", role: "peer", protocol: PROTOCOL_VERSION })));
4039
+ ws.on("open", () => ws.send(JSON.stringify({ t: "hello", role: "peer", protocol: PROTOCOL_VERSION, version: this.version })));
4029
4040
  ws.on("message", (data) => {
4030
4041
  let msg;
4031
4042
  try {
@@ -4035,6 +4046,8 @@ var init_hub = __esm({
4035
4046
  }
4036
4047
  if (msg.t === "welcome") {
4037
4048
  this.hubSocket = ws;
4049
+ this.hubVersion = msg.serverVersion;
4050
+ this.hubCanStop = msg.canStop === true;
4038
4051
  this.role = "peer";
4039
4052
  this.log("connected to hub as peer");
4040
4053
  finish(true);
@@ -4119,7 +4132,7 @@ var init_hub = __esm({
4119
4132
  } else {
4120
4133
  this.peers.add(ws);
4121
4134
  }
4122
- ws.send(JSON.stringify({ t: "welcome", role: msg.role, conn, serverVersion: SERVER_VERSION }));
4135
+ ws.send(JSON.stringify({ t: "welcome", role: msg.role, conn, serverVersion: this.version, canStop: !!this.onStopRequest }));
4123
4136
  if (msg.role === "peer") ws.send(JSON.stringify({ t: "plugins", plugins: this.list() }));
4124
4137
  return;
4125
4138
  }
@@ -4149,7 +4162,10 @@ var init_hub = __esm({
4149
4162
  }
4150
4163
  return;
4151
4164
  }
4152
- if (msg.t === "list") {
4165
+ if (msg.t === "stop") {
4166
+ this.log(this.onStopRequest ? "a newer Lupa asked this hub to stop" : "ignored a stop request (not a lupa serve hub)");
4167
+ this.onStopRequest?.();
4168
+ } else if (msg.t === "list") {
4153
4169
  ws.send(JSON.stringify({ t: "plugins", plugins: this.list() }));
4154
4170
  } else if (msg.t === "req") {
4155
4171
  let target;
@@ -4247,6 +4263,193 @@ Reproduce exact values (sizes, spacing, colours, type). Before writing any colou
4247
4263
  }
4248
4264
  });
4249
4265
 
4266
+ // src/tools/browser.ts
4267
+ import { existsSync as existsSync2, readdirSync } from "node:fs";
4268
+ import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
4269
+ import { createServer } from "node:http";
4270
+ import { createRequire } from "node:module";
4271
+ import os2 from "node:os";
4272
+ import path2 from "node:path";
4273
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
4274
+ async function loadChromium() {
4275
+ const fromProject = createRequire(path2.join(process.cwd(), "package.json"));
4276
+ for (const name of ["playwright", "@playwright/test", "playwright-core"]) {
4277
+ try {
4278
+ const mod = await import(pathToFileURL(fromProject.resolve(name)).href);
4279
+ const chromium = mod.chromium ?? mod.default?.chromium;
4280
+ if (chromium) return chromium;
4281
+ } catch {
4282
+ }
4283
+ }
4284
+ try {
4285
+ const mod = await import("playwright-core");
4286
+ return mod.chromium ?? mod.default?.chromium;
4287
+ } catch {
4288
+ throw new Error(`Rendering a URL needs Playwright: run \`npm install\` in the Lupa folder, or add playwright to your project. ${INSTALL_HINT}`);
4289
+ }
4290
+ }
4291
+ function playwrightCache() {
4292
+ if (process.env.PLAYWRIGHT_BROWSERS_PATH) return process.env.PLAYWRIGHT_BROWSERS_PATH;
4293
+ if (process.platform === "darwin") return path2.join(os2.homedir(), "Library", "Caches", "ms-playwright");
4294
+ if (process.platform === "win32") return path2.join(process.env.LOCALAPPDATA ?? os2.homedir(), "ms-playwright");
4295
+ return path2.join(os2.homedir(), ".cache", "ms-playwright");
4296
+ }
4297
+ function cachedChromiums() {
4298
+ const root = playwrightCache();
4299
+ let dirs;
4300
+ try {
4301
+ dirs = readdirSync(root).filter((d) => /^chromium-\d+$/.test(d));
4302
+ } catch {
4303
+ return [];
4304
+ }
4305
+ dirs.sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]));
4306
+ const inside = [
4307
+ "chrome-linux64/chrome",
4308
+ "chrome-linux/chrome",
4309
+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
4310
+ "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
4311
+ "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
4312
+ "chrome-win64/chrome.exe",
4313
+ "chrome-win/chrome.exe"
4314
+ ];
4315
+ return dirs.flatMap((d) => inside.map((p) => path2.join(root, d, p))).filter((p) => existsSync2(p));
4316
+ }
4317
+ async function launch(chromium) {
4318
+ const attempts = [];
4319
+ if (process.env.LUPA_BROWSER) attempts.push({ executablePath: process.env.LUPA_BROWSER, label: `LUPA_BROWSER (${process.env.LUPA_BROWSER})` });
4320
+ attempts.push(
4321
+ { label: "Playwright's Chromium" },
4322
+ ...cachedChromiums().map((p) => ({ executablePath: p, label: `Playwright's Chromium (${p})` })),
4323
+ { channel: "chrome", label: "Google Chrome" }
4324
+ );
4325
+ const errors = [];
4326
+ for (const { label, ...a } of attempts) {
4327
+ try {
4328
+ return { browser: await chromium.launch({ ...a, headless: true }), label };
4329
+ } catch (e) {
4330
+ errors.push(`${a.executablePath ?? a.channel ?? "bundled"}: ${String(e.message).split("\n")[0]}`);
4331
+ }
4332
+ }
4333
+ throw new Error(`Could not start Chromium. ${INSTALL_HINT}
4334
+ ${errors.map((e) => ` ${e}`).join("\n")}`);
4335
+ }
4336
+ async function checkBrowser() {
4337
+ const { browser, label } = await launch(await loadChromium());
4338
+ await browser.close();
4339
+ return label;
4340
+ }
4341
+ function missingFamilies(families) {
4342
+ const doc = globalThis.document;
4343
+ const ctx = doc.createElement("canvas").getContext("2d");
4344
+ const width = (font) => {
4345
+ ctx.font = font;
4346
+ return ctx.measureText("mmmmmmmmmmlli10WQ@#").width;
4347
+ };
4348
+ return families.filter((f) => ["monospace", "serif", "sans-serif"].every((g) => width(`72px "${f}", ${g}`) === width(`72px ${g}`)));
4349
+ }
4350
+ async function serveFile(url2) {
4351
+ const u = new URL(url2);
4352
+ const file2 = fileURLToPath2(u);
4353
+ if (!existsSync2(file2)) throw new Error(`${file2} does not exist`);
4354
+ const inCwd = !path2.relative(process.cwd(), file2).startsWith("..");
4355
+ const root = inCwd ? process.cwd() : path2.dirname(file2);
4356
+ const server = createServer(async (req, res) => {
4357
+ let p = path2.join(root, decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname));
4358
+ try {
4359
+ if (path2.relative(root, p).startsWith("..")) throw new Error("outside");
4360
+ if ((await stat(p)).isDirectory()) p = path2.join(p, "index.html");
4361
+ const body = await readFile(p);
4362
+ res.writeHead(200, { "content-type": TYPES[path2.extname(p).toLowerCase()] ?? "application/octet-stream" });
4363
+ res.end(body);
4364
+ } catch {
4365
+ res.writeHead(404).end();
4366
+ }
4367
+ });
4368
+ await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
4369
+ const port = server.address().port;
4370
+ const rel = path2.relative(root, file2).split(path2.sep).map(encodeURIComponent).join("/");
4371
+ return { url: `http://127.0.0.1:${port}/${rel}${u.search}${u.hash}`, close: () => server.close() };
4372
+ }
4373
+ async function renderUrl(opts) {
4374
+ const served = opts.url.startsWith("file:") ? await serveFile(opts.url) : void 0;
4375
+ try {
4376
+ const { browser } = await launch(await loadChromium());
4377
+ try {
4378
+ const page = await browser.newPage({
4379
+ viewport: { width: Math.round(opts.width), height: opts.height ?? 900 },
4380
+ deviceScaleFactor: opts.scale ?? 2
4381
+ });
4382
+ await page.goto(served?.url ?? opts.url, { waitUntil: "load", timeout: 3e4 });
4383
+ await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => {
4384
+ });
4385
+ const waitFor = opts.waitFor ?? opts.selector;
4386
+ if (waitFor) {
4387
+ await page.locator(waitFor).first().waitFor({ state: "visible", timeout: 15e3 }).catch(() => {
4388
+ throw new Error(`"${waitFor}" did not appear on ${opts.url} within 15s`);
4389
+ });
4390
+ }
4391
+ await page.evaluate(() => globalThis.document.fonts.ready);
4392
+ const missingFonts = await page.evaluate(missingFamilies, opts.fonts ?? []);
4393
+ const png = opts.selector ? await page.locator(opts.selector).first().screenshot({ animations: "disabled" }) : await page.screenshot({ fullPage: true, animations: "disabled" });
4394
+ return { png, missingFonts };
4395
+ } finally {
4396
+ await browser.close();
4397
+ }
4398
+ } finally {
4399
+ served?.close();
4400
+ }
4401
+ }
4402
+ async function renderSvg(svg, o) {
4403
+ const dir = path2.join(os2.tmpdir(), "lupa");
4404
+ await mkdir(dir, { recursive: true });
4405
+ const file2 = path2.join(dir, `render-${process.pid}-${Date.now()}.svg`);
4406
+ await writeFile(file2, svg);
4407
+ try {
4408
+ const { browser } = await launch(await loadChromium());
4409
+ try {
4410
+ const page = await browser.newPage({
4411
+ viewport: { width: Math.ceil(o.width), height: Math.ceil(o.height) },
4412
+ deviceScaleFactor: o.scale
4413
+ });
4414
+ await page.goto(pathToFileURL(file2).href, { waitUntil: "load", timeout: 3e4 });
4415
+ return await page.screenshot({ clip: { x: 0, y: 0, width: o.width, height: o.height }, omitBackground: true, animations: "disabled" });
4416
+ } finally {
4417
+ await browser.close();
4418
+ }
4419
+ } finally {
4420
+ await rm(file2, { force: true });
4421
+ }
4422
+ }
4423
+ var INSTALL_HINT, TYPES;
4424
+ var init_browser = __esm({
4425
+ "src/tools/browser.ts"() {
4426
+ "use strict";
4427
+ INSTALL_HINT = "Install a browser with `npx playwright install chromium` (or install Google Chrome), or set LUPA_BROWSER to a Chrome/Chromium executable. You can also pass a screenshot with --image.";
4428
+ TYPES = {
4429
+ ".html": "text/html",
4430
+ ".htm": "text/html",
4431
+ ".css": "text/css",
4432
+ ".js": "text/javascript",
4433
+ ".mjs": "text/javascript",
4434
+ ".json": "application/json",
4435
+ ".svg": "image/svg+xml",
4436
+ ".png": "image/png",
4437
+ ".jpg": "image/jpeg",
4438
+ ".jpeg": "image/jpeg",
4439
+ ".gif": "image/gif",
4440
+ ".webp": "image/webp",
4441
+ ".avif": "image/avif",
4442
+ ".ico": "image/x-icon",
4443
+ ".woff": "font/woff",
4444
+ ".woff2": "font/woff2",
4445
+ ".ttf": "font/ttf",
4446
+ ".otf": "font/otf",
4447
+ ".mp4": "video/mp4",
4448
+ ".webm": "video/webm"
4449
+ };
4450
+ }
4451
+ });
4452
+
4250
4453
  // src/model/css.ts
4251
4454
  function n(v, places = 2) {
4252
4455
  if (!Number.isFinite(v)) return "0";
@@ -5246,7 +5449,7 @@ var init_components = __esm({
5246
5449
  this.diffChildren(inst, def, "", out, keyOf, resized);
5247
5450
  return out;
5248
5451
  }
5249
- diffChildren(a, d, path5, out, keyOf, resized) {
5452
+ diffChildren(a, d, path6, out, keyOf, resized) {
5250
5453
  const defByKey = new Map(d.children.map((c) => [keyOf(c, true), c]));
5251
5454
  const matched = /* @__PURE__ */ new Set();
5252
5455
  const names = pathNames(d.children);
@@ -5257,7 +5460,7 @@ var init_components = __esm({
5257
5460
  const cand = d.children[a.children.indexOf(child)];
5258
5461
  dc = ok(cand) ? cand : d.children.find(ok);
5259
5462
  }
5260
- const p = joinPath(path5, dc ? names.get(dc) ?? dc.name : child.name);
5463
+ const p = joinPath(path6, dc ? names.get(dc) ?? dc.name : child.name);
5261
5464
  if (!dc) {
5262
5465
  out.push({ path: p, changes: ["added"], sub: child });
5263
5466
  continue;
@@ -5268,20 +5471,20 @@ var init_components = __esm({
5268
5471
  for (const dc of d.children) {
5269
5472
  if (matched.has(dc) || dc.hidden) continue;
5270
5473
  if (dc.propRefs?.visible) continue;
5271
- out.push({ path: joinPath(path5, names.get(dc) ?? dc.name), changes: ["hidden"] });
5474
+ out.push({ path: joinPath(path6, names.get(dc) ?? dc.name), changes: ["hidden"] });
5272
5475
  }
5273
5476
  }
5274
- diffNode(a, d, path5, out, keyOf, resized) {
5477
+ diffNode(a, d, path6, out, keyOf, resized) {
5275
5478
  if (a.hidden && !d.hidden) {
5276
- if (!d.propRefs?.visible) out.push({ path: path5, changes: ["hidden"] });
5479
+ if (!d.propRefs?.visible) out.push({ path: path6, changes: ["hidden"] });
5277
5480
  return;
5278
5481
  }
5279
5482
  if (!a.hidden && d.hidden) {
5280
5483
  if (d.propRefs?.visible) {
5281
5484
  const changes2 = this.nodeChanges(a, d, resized);
5282
- if (changes2.length) out.push({ path: path5, changes: changes2 });
5283
- this.diffChildren(a, d, path5, out, keyOf, resized);
5284
- } else out.push({ path: path5, changes: ["shown"], sub: a });
5485
+ if (changes2.length) out.push({ path: path6, changes: changes2 });
5486
+ this.diffChildren(a, d, path6, out, keyOf, resized);
5487
+ } else out.push({ path: path6, changes: ["shown"], sub: a });
5285
5488
  return;
5286
5489
  }
5287
5490
  if (a.hidden) return;
@@ -5295,22 +5498,22 @@ var init_components = __esm({
5295
5498
  if (a.kind === "svg" || !a.children.length) {
5296
5499
  if (a.kind === "svg" && a.style.src !== d.style.src && a.style.src) changes2.push(`src:${a.style.src}`);
5297
5500
  if (a.kind === "svg" && a.style.color !== d.style.color && a.style.color) changes2.push(`color:${a.style.color}`);
5298
- if (changes2.length) out.push({ path: path5, changes: changes2 });
5501
+ if (changes2.length) out.push({ path: path6, changes: changes2 });
5299
5502
  } else if (def) {
5300
5503
  changes2.push(...this.rootChanges(a, def.ir));
5301
- if (changes2.length) out.push({ path: path5, changes: changes2 });
5504
+ if (changes2.length) out.push({ path: path6, changes: changes2 });
5302
5505
  const nested = this.overrides(a, def.ir);
5303
- for (const o2 of nested) out.push({ ...o2, path: joinPath(path5, o2.path) });
5506
+ for (const o2 of nested) out.push({ ...o2, path: joinPath(path6, o2.path) });
5304
5507
  } else {
5305
- out.push({ path: path5, changes: changes2.length ? changes2 : [`swap\u2192${label}`], sub: a });
5508
+ out.push({ path: path6, changes: changes2.length ? changes2 : [`swap\u2192${label}`], sub: a });
5306
5509
  }
5307
5510
  return;
5308
5511
  }
5309
5512
  const changes = this.nodeChanges(a, d, resized);
5310
- const o = { path: path5, changes };
5513
+ const o = { path: path6, changes };
5311
5514
  if (a.runs && JSON.stringify(a.runs) !== JSON.stringify(d.runs)) o.runs = a.runs;
5312
5515
  if (changes.length || o.runs) out.push(o);
5313
- if (a.kind !== "svg") this.diffChildren(a, d, path5, out, keyOf, resized);
5516
+ if (a.kind !== "svg") this.diffChildren(a, d, path6, out, keyOf, resized);
5314
5517
  }
5315
5518
  nodeChanges(a, d, resized) {
5316
5519
  const changes = [];
@@ -5795,190 +5998,12 @@ var init_render = __esm({
5795
5998
  }
5796
5999
  });
5797
6000
 
5798
- // src/tools/browser.ts
5799
- import { existsSync, readdirSync } from "node:fs";
5800
- import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
5801
- import { createServer } from "node:http";
5802
- import { createRequire } from "node:module";
5803
- import os from "node:os";
5804
- import path from "node:path";
5805
- import { fileURLToPath, pathToFileURL } from "node:url";
5806
- async function loadChromium() {
5807
- const fromProject = createRequire(path.join(process.cwd(), "package.json"));
5808
- for (const name of ["playwright", "@playwright/test", "playwright-core"]) {
5809
- try {
5810
- const mod = await import(pathToFileURL(fromProject.resolve(name)).href);
5811
- const chromium = mod.chromium ?? mod.default?.chromium;
5812
- if (chromium) return chromium;
5813
- } catch {
5814
- }
5815
- }
5816
- try {
5817
- const mod = await import("playwright-core");
5818
- return mod.chromium ?? mod.default?.chromium;
5819
- } catch {
5820
- throw new Error(`Rendering a URL needs Playwright: run \`npm install\` in the Lupa folder, or add playwright to your project. ${INSTALL_HINT}`);
5821
- }
5822
- }
5823
- function playwrightCache() {
5824
- if (process.env.PLAYWRIGHT_BROWSERS_PATH) return process.env.PLAYWRIGHT_BROWSERS_PATH;
5825
- if (process.platform === "darwin") return path.join(os.homedir(), "Library", "Caches", "ms-playwright");
5826
- if (process.platform === "win32") return path.join(process.env.LOCALAPPDATA ?? os.homedir(), "ms-playwright");
5827
- return path.join(os.homedir(), ".cache", "ms-playwright");
5828
- }
5829
- function cachedChromiums() {
5830
- const root = playwrightCache();
5831
- let dirs;
5832
- try {
5833
- dirs = readdirSync(root).filter((d) => /^chromium-\d+$/.test(d));
5834
- } catch {
5835
- return [];
5836
- }
5837
- dirs.sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]));
5838
- const inside = [
5839
- "chrome-linux64/chrome",
5840
- "chrome-linux/chrome",
5841
- "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
5842
- "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
5843
- "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
5844
- "chrome-win64/chrome.exe",
5845
- "chrome-win/chrome.exe"
5846
- ];
5847
- return dirs.flatMap((d) => inside.map((p) => path.join(root, d, p))).filter((p) => existsSync(p));
5848
- }
5849
- async function launch(chromium) {
5850
- const attempts = [];
5851
- if (process.env.LUPA_BROWSER) attempts.push({ executablePath: process.env.LUPA_BROWSER });
5852
- attempts.push({}, ...cachedChromiums().map((p) => ({ executablePath: p })), { channel: "chrome" });
5853
- const errors = [];
5854
- for (const a of attempts) {
5855
- try {
5856
- return await chromium.launch({ ...a, headless: true });
5857
- } catch (e) {
5858
- errors.push(`${a.executablePath ?? a.channel ?? "bundled"}: ${String(e.message).split("\n")[0]}`);
5859
- }
5860
- }
5861
- throw new Error(`Could not start Chromium. ${INSTALL_HINT}
5862
- ${errors.map((e) => ` ${e}`).join("\n")}`);
5863
- }
5864
- function missingFamilies(families) {
5865
- const doc = globalThis.document;
5866
- const ctx = doc.createElement("canvas").getContext("2d");
5867
- const width = (font) => {
5868
- ctx.font = font;
5869
- return ctx.measureText("mmmmmmmmmmlli10WQ@#").width;
5870
- };
5871
- return families.filter((f) => ["monospace", "serif", "sans-serif"].every((g) => width(`72px "${f}", ${g}`) === width(`72px ${g}`)));
5872
- }
5873
- async function serveFile(url2) {
5874
- const u = new URL(url2);
5875
- const file2 = fileURLToPath(u);
5876
- if (!existsSync(file2)) throw new Error(`${file2} does not exist`);
5877
- const inCwd = !path.relative(process.cwd(), file2).startsWith("..");
5878
- const root = inCwd ? process.cwd() : path.dirname(file2);
5879
- const server = createServer(async (req, res) => {
5880
- let p = path.join(root, decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname));
5881
- try {
5882
- if (path.relative(root, p).startsWith("..")) throw new Error("outside");
5883
- if ((await stat(p)).isDirectory()) p = path.join(p, "index.html");
5884
- const body = await readFile(p);
5885
- res.writeHead(200, { "content-type": TYPES[path.extname(p).toLowerCase()] ?? "application/octet-stream" });
5886
- res.end(body);
5887
- } catch {
5888
- res.writeHead(404).end();
5889
- }
5890
- });
5891
- await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
5892
- const port = server.address().port;
5893
- const rel = path.relative(root, file2).split(path.sep).map(encodeURIComponent).join("/");
5894
- return { url: `http://127.0.0.1:${port}/${rel}${u.search}${u.hash}`, close: () => server.close() };
5895
- }
5896
- async function renderUrl(opts) {
5897
- const served = opts.url.startsWith("file:") ? await serveFile(opts.url) : void 0;
5898
- try {
5899
- const browser = await launch(await loadChromium());
5900
- try {
5901
- const page = await browser.newPage({
5902
- viewport: { width: Math.round(opts.width), height: opts.height ?? 900 },
5903
- deviceScaleFactor: opts.scale ?? 2
5904
- });
5905
- await page.goto(served?.url ?? opts.url, { waitUntil: "load", timeout: 3e4 });
5906
- await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => {
5907
- });
5908
- const waitFor = opts.waitFor ?? opts.selector;
5909
- if (waitFor) {
5910
- await page.locator(waitFor).first().waitFor({ state: "visible", timeout: 15e3 }).catch(() => {
5911
- throw new Error(`"${waitFor}" did not appear on ${opts.url} within 15s`);
5912
- });
5913
- }
5914
- await page.evaluate(() => globalThis.document.fonts.ready);
5915
- const missingFonts = await page.evaluate(missingFamilies, opts.fonts ?? []);
5916
- const png = opts.selector ? await page.locator(opts.selector).first().screenshot({ animations: "disabled" }) : await page.screenshot({ fullPage: true, animations: "disabled" });
5917
- return { png, missingFonts };
5918
- } finally {
5919
- await browser.close();
5920
- }
5921
- } finally {
5922
- served?.close();
5923
- }
5924
- }
5925
- async function renderSvg(svg, o) {
5926
- const dir = path.join(os.tmpdir(), "lupa");
5927
- await mkdir(dir, { recursive: true });
5928
- const file2 = path.join(dir, `render-${process.pid}-${Date.now()}.svg`);
5929
- await writeFile(file2, svg);
5930
- try {
5931
- const browser = await launch(await loadChromium());
5932
- try {
5933
- const page = await browser.newPage({
5934
- viewport: { width: Math.ceil(o.width), height: Math.ceil(o.height) },
5935
- deviceScaleFactor: o.scale
5936
- });
5937
- await page.goto(pathToFileURL(file2).href, { waitUntil: "load", timeout: 3e4 });
5938
- return await page.screenshot({ clip: { x: 0, y: 0, width: o.width, height: o.height }, omitBackground: true, animations: "disabled" });
5939
- } finally {
5940
- await browser.close();
5941
- }
5942
- } finally {
5943
- await rm(file2, { force: true });
5944
- }
5945
- }
5946
- var INSTALL_HINT, TYPES;
5947
- var init_browser = __esm({
5948
- "src/tools/browser.ts"() {
5949
- "use strict";
5950
- INSTALL_HINT = "Install a browser with `npx playwright install chromium` (or install Google Chrome), or set LUPA_BROWSER to a Chrome/Chromium executable. You can also pass a screenshot with --image.";
5951
- TYPES = {
5952
- ".html": "text/html",
5953
- ".htm": "text/html",
5954
- ".css": "text/css",
5955
- ".js": "text/javascript",
5956
- ".mjs": "text/javascript",
5957
- ".json": "application/json",
5958
- ".svg": "image/svg+xml",
5959
- ".png": "image/png",
5960
- ".jpg": "image/jpeg",
5961
- ".jpeg": "image/jpeg",
5962
- ".gif": "image/gif",
5963
- ".webp": "image/webp",
5964
- ".avif": "image/avif",
5965
- ".ico": "image/x-icon",
5966
- ".woff": "font/woff",
5967
- ".woff2": "font/woff2",
5968
- ".ttf": "font/ttf",
5969
- ".otf": "font/otf",
5970
- ".mp4": "video/mp4",
5971
- ".webm": "video/webm"
5972
- };
5973
- }
5974
- });
5975
-
5976
6001
  // src/tools/format.ts
5977
6002
  function formatStatus(plugins, role, port) {
5978
6003
  if (!plugins.length) {
5979
6004
  return [
5980
6005
  `Lupa ${role} on port ${port}. No Figma file connected.`,
5981
- "In Figma: open the file \u2192 Plugins \u2192 Development \u2192 Lupa (import plugin/manifest.json once). Keep the plugin window open."
6006
+ "In Figma: open the file \u2192 Plugins \u2192 Development \u2192 Lupa. Keep the plugin window open. Not in the list yet? lupa setup shows the manifest to import once."
5982
6007
  ].join("\n");
5983
6008
  }
5984
6009
  const lines = [`Lupa ${role} on port ${port}. Connected files (most recently active first):`];
@@ -6016,9 +6041,9 @@ function formatOutline(o) {
6016
6041
  function formatMatches(r) {
6017
6042
  if (!r.matches.length) return "No matches.";
6018
6043
  const out = r.matches.map((m) => {
6019
- const path5 = [m.page, ...m.path].filter(Boolean).join(" \u203A ");
6044
+ const path6 = [m.page, ...m.path].filter(Boolean).join(" \u203A ");
6020
6045
  const text2 = m.text !== void 0 ? ` ${JSON.stringify(m.text)}` : "";
6021
- return `${m.type.toLowerCase()} "${m.name}" #${m.id} ${m.w}\xD7${m.h}${text2} \u2014 ${path5}`;
6046
+ return `${m.type.toLowerCase()} "${m.name}" #${m.id} ${m.w}\xD7${m.h}${text2} \u2014 ${path6}`;
6022
6047
  });
6023
6048
  if (r.truncated) out.push("\u2026 more matches; narrow the query, page or type.");
6024
6049
  return out.join("\n");
@@ -6118,12 +6143,12 @@ var init_format = __esm({
6118
6143
 
6119
6144
  // src/tools/project.ts
6120
6145
  import { readdir, readFile as readFile2 } from "node:fs/promises";
6121
- import os2 from "node:os";
6122
- import path2 from "node:path";
6146
+ import os3 from "node:os";
6147
+ import path3 from "node:path";
6123
6148
  async function scanProject(root, exclude = []) {
6124
- root = path2.resolve(root);
6125
- if (root === path2.parse(root).root || root === os2.homedir()) return void 0;
6126
- const skip = new Set(exclude.map((e) => path2.resolve(e)));
6149
+ root = path3.resolve(root);
6150
+ if (root === path3.parse(root).root || root === os3.homedir()) return void 0;
6151
+ const skip = new Set(exclude.map((e) => path3.resolve(e)));
6127
6152
  const styles = [];
6128
6153
  const svgs = [];
6129
6154
  const comps = [];
@@ -6140,7 +6165,7 @@ async function scanProject(root, exclude = []) {
6140
6165
  entries += list.length;
6141
6166
  list.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
6142
6167
  for (const e of list) {
6143
- const p = path2.join(dir, e.name);
6168
+ const p = path3.join(dir, e.name);
6144
6169
  if (e.isDirectory()) {
6145
6170
  if (!e.name.startsWith(".") && !SKIP_DIRS.has(e.name) && !skip.has(p)) await walk(p, depth + 1);
6146
6171
  } else if (e.isFile()) {
@@ -6153,7 +6178,7 @@ async function scanProject(root, exclude = []) {
6153
6178
  await walk(root, 0);
6154
6179
  const idx = { colors: /* @__PURE__ */ new Map(), fonts: /* @__PURE__ */ new Map(), icons: /* @__PURE__ */ new Map(), components: /* @__PURE__ */ new Map(), textStyles: [] };
6155
6180
  const rules = [];
6156
- const shown = (p) => path2.relative(process.cwd(), p).split(path2.sep).join("/");
6181
+ const shown = (p) => path3.relative(process.cwd(), p).split(path3.sep).join("/");
6157
6182
  const add = (m, key, ref2) => {
6158
6183
  const list = m.get(key) ?? [];
6159
6184
  if (!list.includes(ref2)) list.push(ref2);
@@ -6171,7 +6196,7 @@ async function scanProject(root, exclude = []) {
6171
6196
  define(/(?<=(?:^|[{;])\s*)(--[\w-]+)\s*:\s*([^;{}]+)/g);
6172
6197
  if (/\.(scss|sass)$/i.test(f)) define(/^\s*(\$[\w-]+)\s*:\s*([^;\n]+)/gm);
6173
6198
  if (/\.less$/i.test(f)) define(/^\s*(@[\w-]+)\s*:\s*([^;\n]+)/gm);
6174
- const stem = slug2(path2.basename(f).replace(/\.[^.]+$/, ""));
6199
+ const stem = slug2(path3.basename(f).replace(/\.[^.]+$/, ""));
6175
6200
  for (const m of text2.matchAll(/(?<=^|[{};])\s*\.(-?[_a-zA-Z][\w-]*)\s*\{([^{}]*)\}/g)) {
6176
6201
  if (!/__|--/.test(m[1])) rules.push({ cls: m[1], decls: m[2], file: shown(f) });
6177
6202
  }
@@ -6232,8 +6257,8 @@ async function scanProject(root, exclude = []) {
6232
6257
  idx.icons.set(s.key, list);
6233
6258
  }
6234
6259
  for (const f of comps) {
6235
- let stem = path2.basename(f).replace(/\.[^.]+$/, "");
6236
- if (/^index$/i.test(stem)) stem = path2.basename(path2.dirname(f));
6260
+ let stem = path3.basename(f).replace(/\.[^.]+$/, "");
6261
+ if (/^index$/i.test(stem)) stem = path3.basename(path3.dirname(f));
6237
6262
  if (NOT_COMPONENT.test(stem)) continue;
6238
6263
  add(idx.components, slug2(stem), shown(f));
6239
6264
  }
@@ -8999,7 +9024,7 @@ var init_png = __esm({
8999
9024
 
9000
9025
  // src/tools/media.ts
9001
9026
  import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
9002
- import path3 from "node:path";
9027
+ import path4 from "node:path";
9003
9028
  function rasterWaitMs(frozen) {
9004
9029
  return Number(process.env.LUPA_RASTER_WAIT_MS) || (frozen ? 2500 : 1e4);
9005
9030
  }
@@ -9044,9 +9069,9 @@ async function screenshot(bridge, ids, file2, opts) {
9044
9069
  const raster = decodePng(buf);
9045
9070
  if (opts.saveTo) {
9046
9071
  const target = ids.length > 1 || head.roots.length > 1 ? withSuffix(opts.saveTo, slug(root.name) || root.id) : opts.saveTo;
9047
- await mkdir2(path3.dirname(path3.resolve(target)), { recursive: true });
9072
+ await mkdir2(path4.dirname(path4.resolve(target)), { recursive: true });
9048
9073
  await writeFile2(target, buf);
9049
- lines.push(`saved ${path3.resolve(target)} (${raster.width}\xD7${raster.height}px)`);
9074
+ lines.push(`saved ${path4.resolve(target)} (${raster.width}\xD7${raster.height}px)`);
9050
9075
  }
9051
9076
  const parts = tiles(raster);
9052
9077
  const visionScale = scale * parts[0].scale;
@@ -9060,8 +9085,8 @@ async function screenshot(bridge, ids, file2, opts) {
9060
9085
  return { text: lines.join("\n"), images };
9061
9086
  }
9062
9087
  function withSuffix(file2, suffix) {
9063
- const ext = path3.extname(file2) || ".png";
9064
- return `${file2.slice(0, file2.length - path3.extname(file2).length)}-${suffix}${ext}`;
9088
+ const ext = path4.extname(file2) || ".png";
9089
+ return `${file2.slice(0, file2.length - path4.extname(file2).length)}-${suffix}${ext}`;
9065
9090
  }
9066
9091
  function collect(snap, defs = []) {
9067
9092
  const graphics = [];
@@ -9131,7 +9156,7 @@ function fileNamer() {
9131
9156
  }
9132
9157
  async function exportAssets(bridge, ids, file2, opts) {
9133
9158
  if (opts.as !== "auto") {
9134
- const dir = path3.resolve(opts.dir);
9159
+ const dir = path4.resolve(opts.dir);
9135
9160
  await mkdir2(dir, { recursive: true });
9136
9161
  const fileName = fileNamer();
9137
9162
  const lines = [];
@@ -9140,7 +9165,7 @@ async function exportAssets(bridge, ids, file2, opts) {
9140
9165
  for (const b of res2.blobs) {
9141
9166
  const name = fileName(b.name, opts.as);
9142
9167
  const data = b.encoding === "utf8" ? opts.currentColor ? toCurrentColor(b.data) : b.data : Buffer.from(b.data, "base64");
9143
- await writeFile2(path3.join(dir, name), data);
9168
+ await writeFile2(path4.join(dir, name), data);
9144
9169
  lines.push(`${name} \u2190 "${b.name}" #${b.id} ${n(b.w)}\xD7${n(b.h)}${opts.as === "png" ? ` @${opts.scale ?? 2}x` : ""}`);
9145
9170
  }
9146
9171
  for (const e of res2.errors) lines.push(`failed #${e.id}: ${e.error}`);
@@ -9154,10 +9179,10 @@ async function exportAssets(bridge, ids, file2, opts) {
9154
9179
  return res.report;
9155
9180
  }
9156
9181
  async function writeAssets(bridge, snap, file2, opts) {
9157
- const dir = path3.resolve(opts.dir);
9182
+ const dir = path4.resolve(opts.dir);
9158
9183
  await mkdir2(dir, { recursive: true });
9159
9184
  const fileName = fileNamer();
9160
- const rel = (name) => path3.join(opts.dir, name).split(path3.sep).join("/");
9185
+ const rel = (name) => path4.join(opts.dir, name).split(path4.sep).join("/");
9161
9186
  const lines = [];
9162
9187
  const failures = [];
9163
9188
  const fail2 = (line) => {
@@ -9195,7 +9220,7 @@ async function writeAssets(bridge, snap, file2, opts) {
9195
9220
  const own3 = opts.project && iconFile(opts.project, svg);
9196
9221
  const name = own3 || fileName(g.base, "svg");
9197
9222
  if (own3) reused.add(own3);
9198
- else await writeFile2(path3.join(dir, name), svg);
9223
+ else await writeFile2(path4.join(dir, name), svg);
9199
9224
  written.set(key, { name, line: lines.length, uses: 1, component: g.component, also: [] });
9200
9225
  byNode.set(g.nodeId, own3 || rel(name));
9201
9226
  if (g.sig) bySig.set(g.sig, name);
@@ -9230,7 +9255,7 @@ async function writeAssets(bridge, snap, file2, opts) {
9230
9255
  }
9231
9256
  const buf = Buffer.from(got.data, "base64");
9232
9257
  const name = fileName(img.base, imageExt(buf));
9233
- await writeFile2(path3.join(dir, name), buf);
9258
+ await writeFile2(path4.join(dir, name), buf);
9234
9259
  byImage.set(img.hash, rel(name));
9235
9260
  lines.push(`${name} \u2190 src:${img.hash.slice(0, 10)} "${img.name}" #${img.nodeId}${got.w ? ` ${got.w}\xD7${got.h}px original` : ""}${img.uses > 1 ? ` (used ${img.uses}\xD7)` : ""}`);
9236
9261
  }
@@ -9341,9 +9366,9 @@ async function compare(bridge, root, file2, opts) {
9341
9366
  if (d.regions.length > 10) lines.push(` \u2026 +${d.regions.length - 10} smaller regions`);
9342
9367
  let strip = sideBySide([a, b, d.diff]);
9343
9368
  if (opts.saveDiff) {
9344
- await mkdir2(path3.dirname(path3.resolve(opts.saveDiff)), { recursive: true });
9369
+ await mkdir2(path4.dirname(path4.resolve(opts.saveDiff)), { recursive: true });
9345
9370
  await writeFile2(opts.saveDiff, encodePng(strip));
9346
- lines.push(`saved ${path3.resolve(opts.saveDiff)}`);
9371
+ lines.push(`saved ${path4.resolve(opts.saveDiff)}`);
9347
9372
  }
9348
9373
  if (strip.width > VISION_MAX_EDGE || strip.height > VISION_MAX_EDGE) {
9349
9374
  const s = Math.min(VISION_MAX_EDGE / strip.width, VISION_MAX_EDGE / strip.height);
@@ -9957,8 +9982,8 @@ var init_parseUtil = __esm({
9957
9982
  init_errors();
9958
9983
  init_en();
9959
9984
  makeIssue = (params) => {
9960
- const { data, path: path5, errorMaps, issueData } = params;
9961
- const fullPath = [...path5, ...issueData.path || []];
9985
+ const { data, path: path6, errorMaps, issueData } = params;
9986
+ const fullPath = [...path6, ...issueData.path || []];
9962
9987
  const fullIssue = {
9963
9988
  ...issueData,
9964
9989
  path: fullPath
@@ -10242,11 +10267,11 @@ var init_types = __esm({
10242
10267
  init_parseUtil();
10243
10268
  init_util();
10244
10269
  ParseInputLazyPath = class {
10245
- constructor(parent, value, path5, key) {
10270
+ constructor(parent, value, path6, key) {
10246
10271
  this._cachedPath = [];
10247
10272
  this.parent = parent;
10248
10273
  this.data = value;
10249
- this._path = path5;
10274
+ this._path = path6;
10250
10275
  this._key = key;
10251
10276
  }
10252
10277
  get path() {
@@ -13721,10 +13746,10 @@ function mergeDefs(...defs) {
13721
13746
  function cloneDef(schema) {
13722
13747
  return mergeDefs(schema._zod.def);
13723
13748
  }
13724
- function getElementAtPath(obj, path5) {
13725
- if (!path5)
13749
+ function getElementAtPath(obj, path6) {
13750
+ if (!path6)
13726
13751
  return obj;
13727
- return path5.reduce((acc, key) => acc?.[key], obj);
13752
+ return path6.reduce((acc, key) => acc?.[key], obj);
13728
13753
  }
13729
13754
  function promiseAllObject(promisesObj) {
13730
13755
  const keys = Object.keys(promisesObj);
@@ -13983,11 +14008,11 @@ function explicitlyAborted(x, startIndex = 0) {
13983
14008
  }
13984
14009
  return false;
13985
14010
  }
13986
- function prefixIssues(path5, issues) {
14011
+ function prefixIssues(path6, issues) {
13987
14012
  return issues.map((iss) => {
13988
14013
  var _a3;
13989
14014
  (_a3 = iss).path ?? (_a3.path = []);
13990
- iss.path.unshift(path5);
14015
+ iss.path.unshift(path6);
13991
14016
  return iss;
13992
14017
  });
13993
14018
  }
@@ -14520,16 +14545,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
14520
14545
  }
14521
14546
  function formatError(error62, mapper = (issue2) => issue2.message) {
14522
14547
  const fieldErrors = { _errors: [] };
14523
- const processError = (error63, path5 = []) => {
14548
+ const processError = (error63, path6 = []) => {
14524
14549
  for (const issue2 of error63.issues) {
14525
14550
  if (issue2.code === "invalid_union" && issue2.errors.length) {
14526
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
14551
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
14527
14552
  } else if (issue2.code === "invalid_key") {
14528
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14553
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14529
14554
  } else if (issue2.code === "invalid_element") {
14530
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14555
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14531
14556
  } else {
14532
- const fullpath = [...path5, ...issue2.path];
14557
+ const fullpath = [...path6, ...issue2.path];
14533
14558
  if (fullpath.length === 0) {
14534
14559
  fieldErrors._errors.push(mapper(issue2));
14535
14560
  } else {
@@ -14568,17 +14593,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
14568
14593
  }
14569
14594
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
14570
14595
  const result = { errors: [] };
14571
- const processError = (error63, path5 = []) => {
14596
+ const processError = (error63, path6 = []) => {
14572
14597
  var _a3;
14573
14598
  for (const issue2 of error63.issues) {
14574
14599
  if (issue2.code === "invalid_union" && issue2.errors.length) {
14575
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
14600
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
14576
14601
  } else if (issue2.code === "invalid_key") {
14577
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14602
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14578
14603
  } else if (issue2.code === "invalid_element") {
14579
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14604
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14580
14605
  } else {
14581
- const fullpath = [...path5, ...issue2.path];
14606
+ const fullpath = [...path6, ...issue2.path];
14582
14607
  if (fullpath.length === 0) {
14583
14608
  result.errors.push(mapper(issue2));
14584
14609
  continue;
@@ -14617,8 +14642,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
14617
14642
  }
14618
14643
  function toDotPath(_path) {
14619
14644
  const segs = [];
14620
- const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
14621
- for (const seg of path5) {
14645
+ const path6 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
14646
+ for (const seg of path6) {
14622
14647
  if (typeof seg === "number")
14623
14648
  segs.push(`[${seg}]`);
14624
14649
  else if (typeof seg === "symbol")
@@ -31156,11 +31181,11 @@ function normalizeObjectSchema(schema) {
31156
31181
  }
31157
31182
  return void 0;
31158
31183
  }
31159
- function getDotPath(path5) {
31160
- if (path5.length === 0) {
31184
+ function getDotPath(path6) {
31185
+ if (path6.length === 0) {
31161
31186
  return "object root";
31162
31187
  }
31163
- return path5.reduce((acc, seg, index) => {
31188
+ return path6.reduce((acc, seg, index) => {
31164
31189
  if (index === 0) {
31165
31190
  return String(seg);
31166
31191
  }
@@ -33098,13 +33123,13 @@ function resolveRef(ref, ctx) {
33098
33123
  if (!ref.startsWith("#")) {
33099
33124
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
33100
33125
  }
33101
- const path5 = ref.slice(1).split("/").filter(Boolean);
33102
- if (path5.length === 0) {
33126
+ const path6 = ref.slice(1).split("/").filter(Boolean);
33127
+ if (path6.length === 0) {
33103
33128
  return ctx.rootSchema;
33104
33129
  }
33105
33130
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
33106
- if (path5[0] === defsKey) {
33107
- const key = path5[1] === void 0 ? void 0 : decodeJSONPointerSegment(path5[1]);
33131
+ if (path6[0] === defsKey) {
33132
+ const key = path6[1] === void 0 ? void 0 : decodeJSONPointerSegment(path6[1]);
33108
33133
  if (!key || !ctx.defs[key]) {
33109
33134
  throw new Error(`Reference not found: ${ref}`);
33110
33135
  }
@@ -41581,8 +41606,8 @@ var require_utils = __commonJS({
41581
41606
  }
41582
41607
  return ind;
41583
41608
  }
41584
- function removeDotSegments(path5) {
41585
- let input2 = path5;
41609
+ function removeDotSegments(path6) {
41610
+ let input2 = path6;
41586
41611
  const output2 = [];
41587
41612
  let nextSlash = -1;
41588
41613
  let len = 0;
@@ -41656,11 +41681,11 @@ var require_utils = __commonJS({
41656
41681
  }
41657
41682
  return output2.join("");
41658
41683
  }
41659
- function removeDotSegmentsRelative(path5) {
41660
- if (path5 === "" || path5[0] === "/") {
41661
- return removeDotSegments(path5);
41684
+ function removeDotSegmentsRelative(path6) {
41685
+ if (path6 === "" || path6[0] === "/") {
41686
+ return removeDotSegments(path6);
41662
41687
  }
41663
- const segments = path5.split("/");
41688
+ const segments = path6.split("/");
41664
41689
  const last = segments.length - 1;
41665
41690
  const output2 = [];
41666
41691
  let trailingDirectory = false;
@@ -42023,8 +42048,8 @@ var require_schemes = __commonJS({
42023
42048
  }
42024
42049
  if (wsComponent.resourceName) {
42025
42050
  const queryIndex = wsComponent.resourceName.indexOf("?");
42026
- const path5 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
42027
- wsComponent.path = path5 && path5 !== "/" ? path5 : void 0;
42051
+ const path6 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
42052
+ wsComponent.path = path6 && path6 !== "/" ? path6 : void 0;
42028
42053
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
42029
42054
  wsComponent.resourceName = void 0;
42030
42055
  }
@@ -47637,15 +47662,190 @@ ${FORMAT_LEGEND}`;
47637
47662
 
47638
47663
  // src/cli.ts
47639
47664
  init_hub();
47665
+ import { spawn } from "node:child_process";
47666
+ import { mkdirSync as mkdirSync2, openSync, writeFileSync as writeFileSync2 } from "node:fs";
47667
+ import net from "node:net";
47668
+ import os4 from "node:os";
47669
+ import path5 from "node:path";
47670
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
47671
+ import { parseArgs } from "node:util";
47672
+
47673
+ // src/install.ts
47674
+ init_hub();
47675
+ import { spawnSync } from "node:child_process";
47676
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
47677
+ import os from "node:os";
47678
+ import path from "node:path";
47679
+ import { fileURLToPath } from "node:url";
47680
+ var PACKAGE_NAME = "figma-lupa";
47681
+ var SKILL = "figma-implement";
47682
+ var DAY = 24 * 60 * 60 * 1e3;
47683
+ function packageRoot() {
47684
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
47685
+ }
47686
+ function isCheckout(root = packageRoot()) {
47687
+ return existsSync(path.join(root, ".git"));
47688
+ }
47689
+ function compareVersions(a, b) {
47690
+ const parse3 = (v) => {
47691
+ const [core = "", pre] = v.trim().replace(/^v/, "").split("-", 2);
47692
+ return { nums: core.split(".").map((x2) => Number(x2) || 0), pre };
47693
+ };
47694
+ const x = parse3(a);
47695
+ const y = parse3(b);
47696
+ for (let i = 0; i < 3; i++) {
47697
+ const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
47698
+ if (d) return Math.sign(d);
47699
+ }
47700
+ if (x.pre === y.pre) return 0;
47701
+ if (!x.pre) return 1;
47702
+ if (!y.pre) return -1;
47703
+ return x.pre < y.pre ? -1 : 1;
47704
+ }
47705
+ function cacheDir() {
47706
+ if (process.env.LUPA_CACHE_DIR) return process.env.LUPA_CACHE_DIR;
47707
+ return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "lupa");
47708
+ }
47709
+ var updateChecksOff = () => !!process.env.LUPA_NO_UPDATE_CHECK;
47710
+ function readInfo(dir) {
47711
+ try {
47712
+ return JSON.parse(readFileSync(path.join(dir, "update.json"), "utf8"));
47713
+ } catch {
47714
+ return void 0;
47715
+ }
47716
+ }
47717
+ function writeInfo(dir, info) {
47718
+ try {
47719
+ mkdirSync(dir, { recursive: true });
47720
+ writeFileSync(path.join(dir, "update.json"), JSON.stringify(info));
47721
+ } catch {
47722
+ }
47723
+ }
47724
+ async function fetchLatest(timeoutMs = 4e3) {
47725
+ try {
47726
+ const res = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, { signal: AbortSignal.timeout(timeoutMs) });
47727
+ if (!res.ok) return void 0;
47728
+ const body = await res.json();
47729
+ return typeof body.version === "string" ? body.version : void 0;
47730
+ } catch {
47731
+ return void 0;
47732
+ }
47733
+ }
47734
+ async function refreshUpdateInfo(dir = cacheDir(), fetchVersion = fetchLatest) {
47735
+ if (updateChecksOff()) return;
47736
+ const info = readInfo(dir);
47737
+ if (info && Date.now() - info.checkedAt < DAY) return;
47738
+ const latest = await fetchVersion();
47739
+ writeInfo(dir, { ...info, checkedAt: Date.now(), latest: latest ?? info?.latest });
47740
+ }
47741
+ function updateNotice(dir = cacheDir(), current = SERVER_VERSION) {
47742
+ if (updateChecksOff()) return void 0;
47743
+ const info = readInfo(dir);
47744
+ if (!info?.latest || compareVersions(info.latest, current) <= 0) return void 0;
47745
+ if (info.notified === info.latest && info.notifiedAt && Date.now() - info.notifiedAt < DAY) return void 0;
47746
+ writeInfo(dir, { ...info, notified: info.latest, notifiedAt: Date.now() });
47747
+ return `Lupa ${info.latest} is available (this is ${current}). To update, run: lupa update`;
47748
+ }
47749
+ function skillsDirs() {
47750
+ const home = path.join(os.homedir(), ".claude", "skills");
47751
+ const config2 = process.env.CLAUDE_CONFIG_DIR ? path.join(process.env.CLAUDE_CONFIG_DIR, "skills") : home;
47752
+ return [.../* @__PURE__ */ new Set([config2, home])];
47753
+ }
47754
+ function linkSkill(skillsDir, source = path.join(packageRoot(), "skills", SKILL)) {
47755
+ const link = path.join(skillsDir, SKILL);
47756
+ let stat2;
47757
+ try {
47758
+ stat2 = lstatSync(link);
47759
+ } catch {
47760
+ }
47761
+ let note = "";
47762
+ if (stat2?.isSymbolicLink()) {
47763
+ const target = path.resolve(skillsDir, readlinkSync(link));
47764
+ if (target === source) return `\u2713 Claude skill: ${link} \u2192 ${source}`;
47765
+ rmSync(link);
47766
+ note = ` (it pointed at ${target})`;
47767
+ } else if (stat2) {
47768
+ const backup = `${link}.old-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
47769
+ rmSync(backup, { recursive: true, force: true });
47770
+ renameSync(link, backup);
47771
+ note = ` (your copy is now ${backup}; delete it when you like)`;
47772
+ }
47773
+ mkdirSync(skillsDir, { recursive: true });
47774
+ symlinkSync(source, link, process.platform === "win32" ? "junction" : "dir");
47775
+ return `\u2713 Claude skill: linked ${link} \u2192 ${source}${note}`;
47776
+ }
47777
+ async function setup(o) {
47778
+ const root = packageRoot();
47779
+ const lines = [`Lupa ${SERVER_VERSION} in ${root}${isCheckout(root) ? " (a git checkout)" : ""}`, ""];
47780
+ const dirs = o.skillsDir ? [path.resolve(o.skillsDir)] : skillsDirs().filter((d, i) => i === 0 || existsSync(path.join(d, SKILL)));
47781
+ for (const d of dirs) {
47782
+ try {
47783
+ lines.push(linkSkill(d));
47784
+ } catch (e) {
47785
+ lines.push(`\u2717 Claude skill: could not link it into ${d}: ${e.message}`);
47786
+ }
47787
+ }
47788
+ const manifest = path.join(root, "plugin", "manifest.json");
47789
+ if (existsSync(path.join(root, "plugin", "dist", "code.js"))) {
47790
+ lines.push(
47791
+ "\u2713 Figma plugin: import it once. In Figma: Plugins \u2192 Development \u2192 Import plugin from manifest\u2026, then pick",
47792
+ ` ${manifest}`,
47793
+ " Updates replace the files at this path, so you never import it again. After an update, run the plugin again."
47794
+ );
47795
+ } else {
47796
+ lines.push(`\u2717 Figma plugin: ${path.dirname(manifest)}/dist is missing. Run npm run build in ${root}.`);
47797
+ }
47798
+ try {
47799
+ lines.push(`\u2713 Browser for lupa compare --url: ${await o.checkBrowser()}`);
47800
+ } catch {
47801
+ lines.push("\u2717 Browser for lupa compare --url: none found. Run: npx playwright install chromium (or install Google Chrome, or set LUPA_BROWSER)");
47802
+ }
47803
+ lines.push(" Optional, for MCP clients without a shell: claude mcp add --scope user lupa -- lupa mcp");
47804
+ const latest = await (o.latest ?? fetchLatest)();
47805
+ if (!latest) lines.push(" Could not reach npm to check for updates.");
47806
+ else if (compareVersions(latest, SERVER_VERSION) > 0) lines.push(`\u2191 Lupa ${latest} is available. Run: lupa update`);
47807
+ else lines.push("\u2713 Up to date.");
47808
+ return lines.join("\n");
47809
+ }
47810
+ function npm(args, inherit = false) {
47811
+ return spawnSync("npm", args, { stdio: inherit ? "inherit" : "pipe", encoding: "utf8", shell: process.platform === "win32" });
47812
+ }
47813
+ async function update(latest = fetchLatest) {
47814
+ const root = packageRoot();
47815
+ if (isCheckout(root)) {
47816
+ return { code: 0, text: `This lupa runs from a git checkout. Update it with:
47817
+ cd ${root} && git pull && npm ci && npm run build` };
47818
+ }
47819
+ const version2 = await latest();
47820
+ if (!version2) return { code: 1, text: "Could not reach the npm registry. Check your connection and try again." };
47821
+ if (compareVersions(version2, SERVER_VERSION) <= 0) return { code: 0, text: `Lupa ${SERVER_VERSION} is the latest version.` };
47822
+ const globalRoot = npm(["root", "-g"]).stdout?.trim();
47823
+ if (!globalRoot || path.resolve(globalRoot) !== path.dirname(root)) {
47824
+ return {
47825
+ code: 1,
47826
+ text: `Lupa ${version2} is available, but this copy (${root}) was not installed with npm install -g. Update it with the tool that installed it, e.g. pnpm add -g ${PACKAGE_NAME}@latest.`
47827
+ };
47828
+ }
47829
+ const res = npm(["install", "-g", `${PACKAGE_NAME}@${version2}`], true);
47830
+ if (res.status !== 0) {
47831
+ return { code: 1, text: `npm install failed. Run it yourself to see why:
47832
+ npm install -g ${PACKAGE_NAME}@latest` };
47833
+ }
47834
+ return {
47835
+ code: 0,
47836
+ text: [
47837
+ `Updated Lupa ${SERVER_VERSION} \u2192 ${version2}.`,
47838
+ "- The next lupa command restarts the background hub on the new version.",
47839
+ "- In Figma, close the Lupa plugin and run it again to load its new version."
47840
+ ].join("\n")
47841
+ };
47842
+ }
47843
+
47844
+ // src/cli.ts
47640
47845
  init_legend();
47641
47846
  init_protocol();
47847
+ init_browser();
47642
47848
  init_ops();
47643
- import { spawn } from "node:child_process";
47644
- import { mkdirSync, openSync, writeFileSync } from "node:fs";
47645
- import os3 from "node:os";
47646
- import path4 from "node:path";
47647
- import { fileURLToPath as fileURLToPath2 } from "node:url";
47648
- import { parseArgs } from "node:util";
47649
47849
  var USAGE = `lupa \u2014 read Figma designs for faithful implementation (read-only)
47650
47850
 
47651
47851
  Usage: lupa <command> [target] [options]
@@ -47679,6 +47879,11 @@ Verify
47679
47879
  --image PNG or use a screenshot you took
47680
47880
  --threshold N (0\u20131, default 0.1) -o PATH
47681
47881
 
47882
+ Install
47883
+ setup Link the Claude skill, show where the Figma plugin is, check the browser
47884
+ --skills-dir DIR Claude Code's skills folder (default: $CLAUDE_CONFIG_DIR/skills or ~/.claude/skills)
47885
+ update Install the latest Lupa from npm
47886
+
47682
47887
  Other
47683
47888
  format Legend for the design output
47684
47889
  serve [--idle MIN] Run the hub in the foreground (otherwise started automatically;
@@ -47716,6 +47921,8 @@ var SPECS = {
47716
47921
  out: { type: "string", short: "o" }
47717
47922
  },
47718
47923
  format: {},
47924
+ setup: { "skills-dir": { type: "string" } },
47925
+ update: {},
47719
47926
  serve: { idle: { type: "string" } },
47720
47927
  mcp: {}
47721
47928
  };
@@ -47736,17 +47943,17 @@ function oneOf(v, key, allowed) {
47736
47943
  }
47737
47944
  var str = (v, key) => v[key];
47738
47945
  function imageDir() {
47739
- return path4.join(os3.tmpdir(), "lupa");
47946
+ return path5.join(os4.tmpdir(), "lupa");
47740
47947
  }
47741
47948
  function deliver(v, out, kind) {
47742
47949
  if (!v.images.length) return v.text;
47743
- const base = out ?? path4.join(imageDir(), `${kind}-${Date.now().toString(36)}.png`);
47744
- mkdirSync(path4.dirname(path4.resolve(base)), { recursive: true });
47745
- const ext = path4.extname(base) || ".png";
47746
- const stem = base.slice(0, base.length - path4.extname(base).length);
47950
+ const base = out ?? path5.join(imageDir(), `${kind}-${Date.now().toString(36)}.png`);
47951
+ mkdirSync2(path5.dirname(path5.resolve(base)), { recursive: true });
47952
+ const ext = path5.extname(base) || ".png";
47953
+ const stem = base.slice(0, base.length - path5.extname(base).length);
47747
47954
  const files = v.images.map((png, i) => {
47748
- const f = path4.resolve(i === 0 ? `${stem}${ext}` : `${stem}-${i + 1}${ext}`);
47749
- writeFileSync(f, png);
47955
+ const f = path5.resolve(i === 0 ? `${stem}${ext}` : `${stem}-${i + 1}${ext}`);
47956
+ writeFileSync2(f, png);
47750
47957
  return f;
47751
47958
  });
47752
47959
  return [v.text, ...files.map((f) => `image: ${f}`)].join("\n");
@@ -47825,10 +48032,10 @@ ${deliver(await lupa.screenshot({ target, file: file2 }), void 0, "screenshot")}
47825
48032
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
47826
48033
  function spawnHub(port) {
47827
48034
  const dir = imageDir();
47828
- mkdirSync(dir, { recursive: true });
47829
- const logFile = path4.join(dir, "hub.log");
48035
+ mkdirSync2(dir, { recursive: true });
48036
+ const logFile = path5.join(dir, "hub.log");
47830
48037
  const log = openSync(logFile, "a");
47831
- const entry = fileURLToPath2(import.meta.url);
48038
+ const entry = fileURLToPath3(import.meta.url);
47832
48039
  spawn(process.execPath, [...process.execArgv, entry, "serve", "--port", String(port)], {
47833
48040
  detached: true,
47834
48041
  stdio: ["ignore", log, log],
@@ -47836,9 +48043,32 @@ function spawnHub(port) {
47836
48043
  }).unref();
47837
48044
  return logFile;
47838
48045
  }
48046
+ function portInUse(port) {
48047
+ return new Promise((resolve) => {
48048
+ const s = net.connect({ port, host: "127.0.0.1" });
48049
+ s.once("connect", () => {
48050
+ s.destroy();
48051
+ resolve(true);
48052
+ });
48053
+ s.once("error", () => resolve(false));
48054
+ });
48055
+ }
48056
+ function outdatedHub(bridge) {
48057
+ return bridge.hubCanStop && !!bridge.hubVersion && compareVersions(bridge.hubVersion, SERVER_VERSION) < 0;
48058
+ }
48059
+ async function stopHub(bridge, port) {
48060
+ bridge.askHubToStop();
48061
+ await bridge.close();
48062
+ for (const until = Date.now() + 3e3; Date.now() < until && await portInUse(port); ) await sleep(100);
48063
+ }
47839
48064
  async function joinHub(port, log) {
47840
- const bridge = new Bridge({ port, role: "peer", log });
48065
+ let bridge = new Bridge({ port, role: "peer", log });
47841
48066
  try {
48067
+ await bridge.start();
48068
+ if (!outdatedHub(bridge)) return { bridge, fresh: false };
48069
+ log(`replacing the hub of Lupa ${bridge.hubVersion}`);
48070
+ await stopHub(bridge, port);
48071
+ bridge = new Bridge({ port, role: "peer", log });
47842
48072
  await bridge.start();
47843
48073
  return { bridge, fresh: false };
47844
48074
  } catch {
@@ -47855,17 +48085,21 @@ async function joinHub(port, log) {
47855
48085
  throw new Error(`Could not start the Lupa hub on port ${port} (is another program using it? set LUPA_PORT). Log: ${logFile}`);
47856
48086
  }
47857
48087
  async function serve(port, idleMin, log) {
47858
- const bridge = new Bridge({ port, role: "hub", log });
48088
+ const bridge = new Bridge({ port, role: "hub", log, onStopRequest: () => stop("a newer Lupa replaces this hub") });
47859
48089
  try {
47860
48090
  await bridge.start();
47861
48091
  } catch (e) {
47862
48092
  log(e.message);
47863
48093
  return;
47864
48094
  }
47865
- const stop = (why) => {
48095
+ function stop(why) {
47866
48096
  log(`stopping: ${why}`);
47867
48097
  bridge.close().finally(() => process.exit(0));
47868
- };
48098
+ }
48099
+ const check2 = () => refreshUpdateInfo().catch(() => {
48100
+ });
48101
+ void check2();
48102
+ setInterval(check2, 6 * 60 * 60 * 1e3);
47869
48103
  if (idleMin > 0) {
47870
48104
  setInterval(() => {
47871
48105
  if (bridge.idleMs > idleMin * 6e4) stop(`idle for ${idleMin} min`);
@@ -47876,6 +48110,11 @@ async function serve(port, idleMin, log) {
47876
48110
  await new Promise(() => {
47877
48111
  });
47878
48112
  }
48113
+ function pluginWarnings(plugins) {
48114
+ return plugins.filter((p) => p.pluginVersion && p.pluginVersion !== SERVER_VERSION).map(
48115
+ (p) => `the Lupa plugin in "${p.fileName}" is version ${p.pluginVersion}, lupa is ${SERVER_VERSION}. Close the plugin in Figma and run it again. If it keeps the old version, Figma loads it from an old folder: run lupa setup and import the manifest it shows.`
48116
+ );
48117
+ }
47879
48118
  async function runCli(argv, io = { out: (t) => process.stdout.write(`${t}
47880
48119
  `), err: (t) => process.stderr.write(`${t}
47881
48120
  `) }) {
@@ -47912,6 +48151,15 @@ Run lupa help.`);
47912
48151
  io.out(FORMAT_LEGEND);
47913
48152
  return 0;
47914
48153
  }
48154
+ if (cmd === "setup") {
48155
+ io.out(await setup({ skillsDir: str(values, "skills-dir"), checkBrowser }));
48156
+ return 0;
48157
+ }
48158
+ if (cmd === "update") {
48159
+ const r = await update();
48160
+ (r.code ? io.err : io.out)(r.text);
48161
+ return r.code;
48162
+ }
47915
48163
  const debug = !!process.env.LUPA_DEBUG;
47916
48164
  let port;
47917
48165
  let idle;
@@ -47940,6 +48188,7 @@ Run lupa help.`);
47940
48188
  const lupa = new Lupa(bridge);
47941
48189
  if (fresh) lupa.pluginWaitMs = 8e3;
47942
48190
  io.out(await run(cmd, values, positionals, lupa));
48191
+ for (const line of [...pluginWarnings(bridge.list()), updateNotice()]) if (line) io.err(`lupa: ${line}`);
47943
48192
  return 0;
47944
48193
  } catch (e) {
47945
48194
  io.err(`Error: ${e.message}`);