lofting 0.0.0-stage → 0.1.0

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,524 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res, err) => function __init() {
5
+ if (err) throw err[0];
6
+ try {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ } catch (e) {
9
+ throw err = [e], e;
10
+ }
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // src/clipboard.mjs
18
+ import { spawnSync } from "node:child_process";
19
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
20
+ import { tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ function cfHtml(html) {
23
+ const [before, after] = ["<html><body><!--StartFragment-->", "<!--EndFragment--></body></html>"];
24
+ const header = (n) => `Version:0.9\r
25
+ StartHTML:${n[0]}\r
26
+ EndHTML:${n[1]}\r
27
+ StartFragment:${n[2]}\r
28
+ EndFragment:${n[3]}\r
29
+ `;
30
+ const pad = (v) => String(v).padStart(10, "0");
31
+ const start = header(Array(4).fill(pad(0))).length;
32
+ const fragment = start + Buffer.byteLength(before);
33
+ const end = fragment + Buffer.byteLength(html);
34
+ return header([start, end + Buffer.byteLength(after), fragment, end].map(pad)) + before + html + after;
35
+ }
36
+ function clipboardCommands(platform, env, file) {
37
+ if (platform === "darwin") return [{ cmd: "osascript", args: ["-l", "JavaScript", "-e", MAC, file] }];
38
+ if (platform === "win32") return [{ cmd: "powershell.exe", args: ["-NoProfile", "-NonInteractive", "-STA", "-Command", WINDOWS], env: { LOFTING_FILE: file } }];
39
+ const commands = [];
40
+ if (env.WAYLAND_DISPLAY) commands.push({ cmd: "wl-copy", args: ["--type", "text/html"], stdin: true });
41
+ if (env.DISPLAY) commands.push({ cmd: "xclip", args: ["-selection", "clipboard", "-t", "text/html", "-i", file] });
42
+ return commands;
43
+ }
44
+ function writeClipboard(html) {
45
+ if (process.env.LOFTING_CLIPBOARD === "off") throw new Error("The clipboard is switched off (LOFTING_CLIPBOARD=off).");
46
+ const dir = mkdtempSync(join(tmpdir(), "lofting-"));
47
+ const file = join(dir, "copy.html");
48
+ try {
49
+ writeFileSync(file, process.platform === "win32" ? cfHtml(html) : html);
50
+ const commands = clipboardCommands(process.platform, process.env, file);
51
+ for (const { cmd, args, env, stdin } of commands) {
52
+ const r = spawnSync(cmd, args, { input: stdin ? html : void 0, stdio: [stdin ? "pipe" : "ignore", "ignore", "ignore"], env: { ...process.env, ...env }, timeout: 6e4, maxBuffer: 1 });
53
+ if (!r.error && r.status === 0) return;
54
+ }
55
+ throw new Error(process.platform === "linux" || !commands.length ? "Couldn't write HTML to the clipboard. Install wl-clipboard (Wayland) or xclip (X11)." : "Couldn't write HTML to the clipboard.");
56
+ } finally {
57
+ rmSync(dir, { recursive: true, force: true });
58
+ }
59
+ }
60
+ var MAC, WINDOWS, pasteKeys;
61
+ var init_clipboard = __esm({
62
+ "src/clipboard.mjs"() {
63
+ MAC = `ObjC.import('AppKit');
64
+ function run([file]) {
65
+ const html = $.NSString.stringWithContentsOfFileEncodingError(file, $.NSUTF8StringEncoding, null);
66
+ if (html.isNil()) throw new Error('Could not read ' + file);
67
+ const pasteboard = $.NSPasteboard.generalPasteboard;
68
+ pasteboard.clearContents;
69
+ if (!pasteboard.setStringForType(html, $.NSPasteboardTypeHTML)) throw new Error('Could not write to the clipboard');
70
+ }`;
71
+ WINDOWS = "Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.DataObject; $d.SetData('HTML Format', [IO.MemoryStream]::new([IO.File]::ReadAllBytes($env:LOFTING_FILE))); [System.Windows.Forms.Clipboard]::SetDataObject($d, $true)";
72
+ pasteKeys = process.platform === "darwin" ? "Cmd+V" : "Ctrl+V";
73
+ }
74
+ });
75
+
76
+ // ../pages.mjs
77
+ function pick(urls, start, limit) {
78
+ const site = new URL(start);
79
+ const paths = [];
80
+ for (const raw of urls) {
81
+ let u;
82
+ try {
83
+ u = new URL(raw, site);
84
+ } catch {
85
+ continue;
86
+ }
87
+ if (!/^https?:$/.test(u.protocol) || host(u) !== host(site) || NOT_PAGES.test(u.pathname)) continue;
88
+ if (decodeURIComponent(u.pathname).split("/").some((s) => s.includes(":")) || u.search && SCRIPT.test(u.pathname)) continue;
89
+ const path = pathOf(u);
90
+ if (!paths.includes(path)) paths.push(path);
91
+ }
92
+ const parts = (p) => p.split("/").filter(Boolean).map((s) => /\d/.test(s) ? "*" : s);
93
+ const under = {};
94
+ for (const p of paths) parts(p).slice(0, -1).forEach((_, d, ps) => under[ps.slice(0, d + 1).join("/")] = (under[ps.slice(0, d + 1).join("/")] ?? 0) + 1);
95
+ const kindOf = (p) => {
96
+ const ps = parts(p);
97
+ for (let d = 1; d < ps.length; d++) if (under[ps.slice(0, d).join("/")] >= 3 || ps[d] === "*") return `${ps.slice(0, d).join("/")}/*`;
98
+ return ps.join("/");
99
+ };
100
+ const kinds = /* @__PURE__ */ new Map();
101
+ for (const p of paths) {
102
+ const kind = kindOf(p);
103
+ kinds.has(kind) ? kinds.get(kind).like++ : kinds.set(kind, { path: p, like: 1 });
104
+ }
105
+ const depth = (p) => parts(p).length;
106
+ return [...kinds.values()].sort((a, b) => depth(a.path) - depth(b.path)).slice(0, limit).map(({ path, like }) => ({
107
+ path,
108
+ label: like > 1 ? `${path} (and ${like - 1} like it)` : path,
109
+ section: sectionOf(path)
110
+ }));
111
+ }
112
+ async function settle(pages, start, init = {}) {
113
+ const site = new URL(start);
114
+ const ends = [];
115
+ let next = 0;
116
+ const one = async () => {
117
+ for (let i; (i = next++) < pages.length; ) {
118
+ const at = new URL(pages[i].path, site);
119
+ ends[i] = await fetch(at, { method: "HEAD", redirect: "follow", signal: AbortSignal.timeout(1e4), ...init }).then((r) => new URL(r.url || at), () => at);
120
+ }
121
+ };
122
+ await Promise.all(Array.from({ length: 8 }, one));
123
+ const seen = /* @__PURE__ */ new Set();
124
+ return pages.flatMap((page, i) => {
125
+ const path = pathOf(ends[i]);
126
+ if (host(ends[i]) !== host(site) || seen.has(path)) return [];
127
+ seen.add(path);
128
+ return [{ ...page, path, label: path + page.label.slice(page.path.length), section: sectionOf(path) }];
129
+ });
130
+ }
131
+ async function fromSitemaps(site) {
132
+ const robots = await get(new URL("/robots.txt", site));
133
+ const queue = [...robots.matchAll(/^sitemap:\s*(\S+)/gim)].map((m) => m[1]);
134
+ if (!queue.length) queue.push(new URL("/sitemap.xml", site).href);
135
+ const pages = [];
136
+ for (let i = 0; i < queue.length && i < 20; i++) {
137
+ for (const loc of locs(await get(queue[i]))) (/\.xml(\.gz)?$/i.test(loc) ? queue : pages).push(loc);
138
+ }
139
+ return pages;
140
+ }
141
+ function merge(htmls, names, title) {
142
+ const GAP = 200;
143
+ let next = 0;
144
+ let x = 0;
145
+ const pages = [];
146
+ const assets = {};
147
+ const fonts = {};
148
+ let source = "mcp";
149
+ let first;
150
+ for (const [i, html] of htmls.entries()) {
151
+ const meta = decode(field(html, "figmeta"));
152
+ if (meta.source !== "mcp") source = meta.source;
153
+ const doc2 = decode(field(html, "figh2d"));
154
+ first ??= doc2;
155
+ (function walk(node) {
156
+ node.id = `h2d-node-${next++}`;
157
+ if (node.rect) node.rect = { ...node.rect, x: node.rect.x + x };
158
+ if (node.styles?.position === "fixed") node.styles.position = "absolute";
159
+ node.childNodes?.forEach(walk);
160
+ })(doc2.root);
161
+ const body = doc2.root.childNodes.find((n) => n.tag === "BODY");
162
+ const clear = (c) => !c || /^(transparent|rgba\(0, 0, 0, 0\))$/.test(c);
163
+ const background = [doc2.root.styles.backgroundColor, body?.styles?.backgroundColor].find((c) => !clear(c)) ?? "rgb(255, 255, 255)";
164
+ Object.assign(doc2.root, { tag: "DIV", owningReactComponent: names[i] });
165
+ Object.assign(doc2.root.styles, { position: "absolute", left: `${x}px`, top: "0px", zIndex: "0", overflow: "hidden", backgroundColor: background });
166
+ pages.push(doc2.root);
167
+ Object.assign(assets, doc2.assets);
168
+ for (const [k, f] of Object.entries(doc2.fonts)) fonts[k] ? fonts[k].usages.push(...f.usages) : fonts[k] = f;
169
+ x += doc2.documentRect.width + GAP;
170
+ }
171
+ const whole = { x: 0, y: 0, width: x - GAP, height: Math.max(...pages.map((p) => p.rect.height)) };
172
+ const styles = { position: "relative", backgroundColor: "rgba(0, 0, 0, 0)", width: `${whole.width}px`, height: `${whole.height}px` };
173
+ const root = { nodeType: 1, id: `h2d-node-${next++}`, tag: "HTML", attributes: {}, styles, rect: whole, childNodes: pages };
174
+ const doc = { ...first, documentTitle: title, root, documentRect: whole, assets, fonts };
175
+ return `<meta charset="utf-8"><span data-metadata="<!--(figmeta)${encode({ dataType: "h2d", source, capturedAtIso: (/* @__PURE__ */ new Date()).toISOString() })}(/figmeta)-->"></span><span data-h2d="<!--(figh2d)${encode(doc)}(/figh2d)-->"></span>`;
176
+ }
177
+ var NOT_PAGES, host, sectionOf, pathOf, SCRIPT, locs, get, field, decode, encode;
178
+ var init_pages = __esm({
179
+ "../pages.mjs"() {
180
+ NOT_PAGES = /\.(pdf|png|jpe?g|gif|svg|webp|avif|ico|zip|gz|xml|txt|json|rss|atom|css|js|mjs|mp3|mp4|webm|mov|woff2?)$/i;
181
+ host = (u) => new URL(u).hostname.replace(/^www\./, "");
182
+ sectionOf = (path) => path.split("/").filter(Boolean).length > 1 ? `/${path.split("/")[1]}` : "/";
183
+ pathOf = (u) => u.pathname.replace(/\/+$/, "") || "/";
184
+ SCRIPT = /\.(php|aspx?|cgi|jsp)$/i;
185
+ locs = (xml) => [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&amp;/g, "&"));
186
+ get = (url) => fetch(url, { redirect: "follow" }).then((r) => r.ok ? r.text() : "").catch(() => "");
187
+ field = (html, name) => html.match(new RegExp(`\\(${name}\\)(.*?)\\(/${name}\\)`))?.[1];
188
+ decode = (b64) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))));
189
+ encode = (value) => {
190
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
191
+ let s = "";
192
+ for (let i = 0; i < bytes.length; i += 32768) s += String.fromCharCode(...bytes.subarray(i, i + 32768));
193
+ return btoa(s);
194
+ };
195
+ }
196
+ });
197
+
198
+ // src/capture.mjs
199
+ import { readFileSync } from "node:fs";
200
+ import { createRequire } from "node:module";
201
+ import { chromium } from "playwright-core";
202
+ async function openBrowser() {
203
+ try {
204
+ return await chromium.launch({ channel: "chrome" });
205
+ } catch {
206
+ }
207
+ try {
208
+ return await chromium.launch();
209
+ } catch {
210
+ }
211
+ const { version } = createRequire(import.meta.url)("playwright-core/package.json");
212
+ throw new Error(`Lofting opens pages in Google Chrome, and couldn't find it on this computer. Install Chrome (https://www.google.com/chrome/), or get the Chromium that Playwright uses with:
213
+ npx playwright@${version} install chromium`);
214
+ }
215
+ function newContext(browser, width = 1440) {
216
+ const os = { darwin: "Macintosh; Intel Mac OS X 10_15_7", win32: "Windows NT 10.0; Win64; x64" }[process.platform] ?? "X11; Linux x86_64";
217
+ const userAgent = `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${browser.version()} Safari/537.36`;
218
+ return browser.newContext({ viewport: { width, height: HEIGHT }, bypassCSP: true, userAgent });
219
+ }
220
+ async function open(context, url) {
221
+ const page = await context.newPage();
222
+ const response = await page.goto(url, { waitUntil: "load", timeout: 6e4 });
223
+ if (response && response.status() >= 400) throw new Error(`${url} answered ${response.status()}.`);
224
+ await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => {
225
+ });
226
+ await page.waitForTimeout(1e3);
227
+ return page;
228
+ }
229
+ async function fetchPictures(context, urls) {
230
+ const given = {};
231
+ let next = 0;
232
+ const one = async () => {
233
+ for (let i; (i = next++) < urls.length; ) {
234
+ try {
235
+ const r = await context.request.get(urls[i], { timeout: 15e3 });
236
+ if (r.ok()) given[urls[i]] = { type: r.headers()["content-type"] ?? "", base64Blob: `data:application/octet-stream;base64,${(await r.body()).toString("base64")}` };
237
+ } catch {
238
+ }
239
+ }
240
+ };
241
+ await Promise.all(Array.from({ length: 8 }, one));
242
+ return given;
243
+ }
244
+ async function capturePage(context, url) {
245
+ const page = await open(context, url);
246
+ try {
247
+ await page.addScriptTag({ content: PAGE_SCRIPT });
248
+ const step = (name, arg = null) => page.evaluate(([n, a]) => window.__capture[n](a), [name, arg]);
249
+ const kits = await step("kits").catch(() => []);
250
+ const components = await step("componentNames").catch(() => []);
251
+ const notes = [];
252
+ const { width } = page.viewportSize();
253
+ let [height, extra] = [HEIGHT, await step("overflow")];
254
+ while (extra > 0) {
255
+ const next = Math.min(height + extra, MAX_HEIGHT);
256
+ if (next === height) {
257
+ notes.push(`A panel taller than ${MAX_HEIGHT}px is cut off where the window ends.`);
258
+ break;
259
+ }
260
+ await page.setViewportSize({ width, height: next });
261
+ await page.waitForTimeout(300);
262
+ const left = await step("overflow");
263
+ if (left >= extra) {
264
+ await page.setViewportSize({ width, height });
265
+ break;
266
+ }
267
+ [height, extra] = [next, left];
268
+ }
269
+ const { masks } = await step("before");
270
+ for (let i = 0; i < masks; i++) {
271
+ const at = await step("solo", [i, "transparent"]);
272
+ const shot = at && await page.locator(`img[data-solo="${i}"]`).screenshot({ omitBackground: true }).catch(() => null);
273
+ await step("unmask", [i, shot && `data:image/png;base64,${shot.toString("base64")}`]);
274
+ }
275
+ const others = await step("otherSites");
276
+ if (others.length) await step("give", await fetchPictures(context, others));
277
+ const title = await page.title() || host(url);
278
+ const result = await step("after", [title, false, null, true]);
279
+ if (result.missing.length) notes.push(`Some icons came out as their names, not pictures: ${result.missing.join(", ")}.`);
280
+ if (result.unfetched.length) notes.push(`${result.unfetched.length} picture${result.unfetched.length > 1 ? "s" : ""} from other sites couldn't be read, so ${result.unfetched.length > 1 ? "they were" : "it was"} left out.`);
281
+ if (result.reverted.length) notes.push(`A few decorations were left out, as copying them moved the layout: ${result.reverted.join(", ")}.`);
282
+ return { html: result.snapshot, title, url: page.url(), layers: result.layers, components, kits, notes };
283
+ } finally {
284
+ await page.close().catch(() => {
285
+ });
286
+ }
287
+ }
288
+ async function sitePages(context, url) {
289
+ let urls = await fromSitemaps(new URL(url).origin);
290
+ const from = urls.length > 1 ? "sitemap" : "links";
291
+ if (from === "links") {
292
+ const page = await open(context, url);
293
+ try {
294
+ urls = [...urls, ...await page.evaluate(() => [...document.querySelectorAll("nav a[href], header a[href], [role=navigation] a[href]"), ...document.links].map((a) => a.href))];
295
+ } finally {
296
+ await page.close().catch(() => {
297
+ });
298
+ }
299
+ }
300
+ const pages = await settle(pick([new URL("/", url).href, url, ...urls], url, 500), url);
301
+ return { from, found: urls.length, pages };
302
+ }
303
+ async function captureSite(context, url, limit = 10, progress = () => {
304
+ }) {
305
+ const { pages: all } = await sitePages(context, url);
306
+ const pages = all.slice(0, limit);
307
+ const origin = new URL(url).origin;
308
+ const [htmls, names, copied, skipped, kits, components] = [[], [], [], [], /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set()];
309
+ let layers = 0;
310
+ for (const [i, p] of pages.entries()) {
311
+ progress(`Copying page ${i + 1} of ${pages.length}: ${p.path}`);
312
+ try {
313
+ const one = await capturePage(context, new URL(p.path, origin).href);
314
+ htmls.push(one.html);
315
+ names.push(p.label);
316
+ copied.push(p.label);
317
+ layers += one.layers;
318
+ one.kits.forEach((k) => kits.add(k));
319
+ one.components.forEach((c) => components.add(c));
320
+ } catch (err) {
321
+ skipped.push(`${p.path} (${String(err?.message ?? err).split("\n")[0]})`);
322
+ }
323
+ }
324
+ if (!htmls.length) throw new Error(`None of ${host(url)}'s pages could be copied: ${skipped.join("; ")}`);
325
+ return { html: merge(htmls, names, host(url)), title: host(url), layers, components: [...components], kits: [...kits], copied, skipped, more: all.length - pages.length };
326
+ }
327
+ var PAGE_SCRIPT, HEIGHT, MAX_HEIGHT;
328
+ var init_capture = __esm({
329
+ "src/capture.mjs"() {
330
+ init_pages();
331
+ PAGE_SCRIPT = readFileSync(new URL("./page.js", import.meta.url), "utf8");
332
+ HEIGHT = 900;
333
+ MAX_HEIGHT = 2e4;
334
+ }
335
+ });
336
+
337
+ // src/run.mjs
338
+ function summary(copy2, seconds) {
339
+ const lines = [];
340
+ const what = copy2.copied ? `${plural(copy2.copied.length, "page")} of ${copy2.title}` : `"${copy2.title}"`;
341
+ lines.push(`Copied ${what} in ${seconds.toFixed(1)} s: ${plural(copy2.layers, "layer")}.`);
342
+ if (copy2.components.length) {
343
+ const names = copy2.components.slice(0, 8).join(", ") + (copy2.components.length > 8 ? ` and ${copy2.components.length - 8} more` : "");
344
+ lines.push(`Components found${copy2.kits.length ? ` (${copy2.kits.join(", ")})` : ""}: ${names}. Their layers are named after them.`);
345
+ }
346
+ if (copy2.copied) {
347
+ lines.push(...copy2.copied.map((label) => ` ${label}`));
348
+ if (copy2.copied.some((label) => label.includes(" like it)"))) lines.push("Pages made from the same template were copied once.");
349
+ if (copy2.skipped.length) lines.push(`Couldn't copy ${copy2.skipped.join(", ")}.`);
350
+ if (copy2.more > 0) lines.push(`The site has ${plural(copy2.more, "more kind")} of page; copy more with --pages.`);
351
+ }
352
+ lines.push(...copy2.notes ?? []);
353
+ return lines.join("\n");
354
+ }
355
+ async function copy(url, { site = false, pages = 10, width = 1440, progress } = {}) {
356
+ const browser = await openBrowser();
357
+ try {
358
+ const context = await newContext(browser, width);
359
+ return site ? await captureSite(context, url, pages, progress) : await capturePage(context, url);
360
+ } finally {
361
+ await browser.close().catch(() => {
362
+ });
363
+ }
364
+ }
365
+ async function listPages(url) {
366
+ const browser = await openBrowser();
367
+ try {
368
+ return await sitePages(await newContext(browser), url);
369
+ } finally {
370
+ await browser.close().catch(() => {
371
+ });
372
+ }
373
+ }
374
+ var plural, checkUrl;
375
+ var init_run = __esm({
376
+ "src/run.mjs"() {
377
+ init_capture();
378
+ plural = (n, word) => `${n.toLocaleString("en")} ${word}${n === 1 ? "" : "s"}`;
379
+ checkUrl = (url) => {
380
+ let u;
381
+ try {
382
+ u = new URL(url);
383
+ } catch {
384
+ }
385
+ if (!u || !/^https?:$/.test(u.protocol)) throw new Error(`Give a web address starting with http:// or https://, not "${url}".`);
386
+ return u.href;
387
+ };
388
+ }
389
+ });
390
+
391
+ // src/mcp.mjs
392
+ var mcp_exports = {};
393
+ __export(mcp_exports, {
394
+ serve: () => serve
395
+ });
396
+ import { mkdirSync, writeFileSync as writeFileSync2 } from "node:fs";
397
+ import { tmpdir as tmpdir2 } from "node:os";
398
+ import { join as join2 } from "node:path";
399
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
400
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
401
+ import { z } from "zod";
402
+ async function answer(url, options) {
403
+ const started = performance.now();
404
+ const result = await copy(checkUrl(url), options);
405
+ const text = summary(result, (performance.now() - started) / 1e3);
406
+ const dir = join2(tmpdir2(), "lofting");
407
+ mkdirSync(dir, { recursive: true });
408
+ const file = join2(dir, `${new URL(result.url ?? url).hostname}-${Date.now()}.html`);
409
+ writeFileSync2(file, result.html);
410
+ let clipboard;
411
+ try {
412
+ writeClipboard(result.html);
413
+ clipboard = `It's on the clipboard: paste into Figma with ${pasteKeys}.`;
414
+ } catch (err) {
415
+ clipboard = `It isn't on the clipboard: ${err.message}`;
416
+ }
417
+ return { content: [{ type: "text", text: `${text}
418
+ ${clipboard}
419
+ Saved to ${file}` }] };
420
+ }
421
+ async function serve() {
422
+ const server = new McpServer({ name: "lofting", version: "0.1.0" });
423
+ server.registerTool("copy_page", {
424
+ title: "Copy a page into Figma",
425
+ description: `Opens a web page in a headless Chrome and copies it as Figma layers, named after its UI components (MUI, shadcn/ui and others). ${PASTE} Pages behind a login can't be reached: the browser isn't signed in.`,
426
+ inputSchema: { url: z.string().describe("The page, starting with http:// or https://"), width: z.number().int().min(320).max(3840).optional().describe("The browser window width in pixels (default 1440)") }
427
+ }, ({ url, width }) => answer(url, { width }).catch(failed));
428
+ server.registerTool("copy_site", {
429
+ title: "Copy a whole site into Figma",
430
+ description: `Finds a site's pages (its sitemap, else its links), keeps one page of each kind with the home page first, and copies them as one paste: a frame per page, side by side, named by its address. ${PASTE} Use list_site_pages first to see which pages it would copy.`,
431
+ inputSchema: { url: z.string().describe("The site's address, starting with http:// or https://"), pages: z.number().int().min(1).max(50).optional().describe("How many pages to copy (default 10)") }
432
+ }, ({ url, pages }) => answer(url, { site: true, pages }).catch(failed));
433
+ server.registerTool("list_site_pages", {
434
+ title: "List a site's pages",
435
+ description: "Lists the pages copy_site would pick from, in its order: one of each kind, home first, each with a label saying how many pages share its template. Copies nothing.",
436
+ inputSchema: { url: z.string().describe("The site's address, starting with http:// or https://") }
437
+ }, async ({ url }) => {
438
+ try {
439
+ const { from, found, pages } = await listPages(checkUrl(url));
440
+ const lines = pages.map((p, i) => `${i + 1}. ${p.label}`);
441
+ return { content: [{ type: "text", text: `${pages.length} kinds of page, from the site's ${from === "sitemap" ? "sitemap" : "links"} (${found} addresses found). copy_site copies the first 10 unless told otherwise:
442
+ ${lines.join("\n")}` }] };
443
+ } catch (err) {
444
+ return failed(err);
445
+ }
446
+ });
447
+ await server.connect(new StdioServerTransport());
448
+ }
449
+ var PASTE, failed;
450
+ var init_mcp = __esm({
451
+ "src/mcp.mjs"() {
452
+ init_clipboard();
453
+ init_run();
454
+ PASTE = `The copy is on the user's clipboard: they paste it into Figma themselves with ${pasteKeys}, where it lands as editable layers. Tell them to. It is also saved as an HTML file, whose path the result gives.`;
455
+ failed = (err) => ({ isError: true, content: [{ type: "text", text: String(err?.message ?? err) }] });
456
+ }
457
+ });
458
+
459
+ // src/cli.mjs
460
+ init_clipboard();
461
+ init_run();
462
+ import { writeFileSync as writeFileSync3 } from "node:fs";
463
+ import { resolve } from "node:path";
464
+ import { parseArgs } from "node:util";
465
+ var HELP = `Copy a web page into Figma as editable layers.
466
+
467
+ Usage:
468
+ lofting <url> copy the page to the clipboard, then paste it into Figma
469
+ lofting <url> --site copy the whole site: one page of each kind, side by side in one paste
470
+ lofting mcp run as an MCP server (stdio), for Claude, Cursor and other AI tools
471
+
472
+ Options:
473
+ --pages <n> with --site, how many pages to copy (default 10)
474
+ --width <px> the browser window's width (default 1440)
475
+ --out <file> save the copy to an HTML file instead of the clipboard
476
+ --copy with --out, put it on the clipboard as well
477
+ --help show this
478
+ --version show the version
479
+
480
+ It opens the page in the Google Chrome on this computer, without your logins: for a page behind a login, use the
481
+ Lofting browser extension (https://lofting.dev). Lofting sends no counts or other data anywhere.`;
482
+ async function main() {
483
+ const { values, positionals } = parseArgs({
484
+ allowPositionals: true,
485
+ options: { site: { type: "boolean" }, pages: { type: "string" }, width: { type: "string" }, out: { type: "string" }, copy: { type: "boolean" }, help: { type: "boolean", short: "h" }, version: { type: "boolean", short: "v" } }
486
+ });
487
+ if (values.version) return console.log("0.1.0");
488
+ if (positionals[0] === "mcp") return (await Promise.resolve().then(() => (init_mcp(), mcp_exports))).serve();
489
+ if (values.help || positionals.length !== 1) {
490
+ console.log(HELP);
491
+ return void (process.exitCode = values.help ? 0 : 1);
492
+ }
493
+ const number = (v, name, fallback) => {
494
+ if (v === void 0) return fallback;
495
+ if (!/^\d+$/.test(v) || +v < 1) throw new Error(`--${name} takes a whole number, not "${v}".`);
496
+ return +v;
497
+ };
498
+ const options = { site: !!values.site, pages: number(values.pages, "pages", 10), width: number(values.width, "width", 1440), progress: (t) => console.error(t) };
499
+ const url = checkUrl(positionals[0]);
500
+ const started = performance.now();
501
+ console.error(options.site ? `Finding the pages of ${new URL(url).host}\u2026` : `Copying ${url}\u2026`);
502
+ const result = await copy(url, options);
503
+ const text = summary(result, (performance.now() - started) / 1e3);
504
+ let saved = values.out && resolve(values.out);
505
+ if (saved) writeFileSync3(saved, result.html);
506
+ if (!saved || values.copy) {
507
+ try {
508
+ writeClipboard(result.html);
509
+ console.log(`${text}
510
+ Paste into Figma with ${pasteKeys}.`);
511
+ } catch (err) {
512
+ saved ??= resolve(`lofting-${new URL(result.url ?? url).hostname}.html`);
513
+ writeFileSync3(saved, result.html);
514
+ console.log(`${text}
515
+ ${err.message} Saved the copy to ${saved} instead.`);
516
+ process.exitCode = 3;
517
+ }
518
+ } else console.log(text);
519
+ if (saved && process.exitCode !== 3) console.log(`Saved the copy to ${saved}.`);
520
+ }
521
+ main().catch((err) => {
522
+ console.error(String(err?.message ?? err));
523
+ process.exitCode = 1;
524
+ });