inkless 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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/bin/inkless.js +10 -0
  4. package/console-dist/assets/BlueprintTool-CLWuM21a.js +4226 -0
  5. package/console-dist/assets/index-CIqLZU6s.js +33 -0
  6. package/console-dist/assets/index-Dv7Gg9qm.css +1 -0
  7. package/console-dist/favicon.svg +11 -0
  8. package/console-dist/index.html +18 -0
  9. package/native/linux/rfcomm.py +84 -0
  10. package/native/macos/build/InklessBluetooth.app/Contents/Info.plist +26 -0
  11. package/native/macos/build/InklessBluetooth.app/Contents/MacOS/InklessBluetooth +0 -0
  12. package/native/macos/build/InklessBluetooth.app/Contents/_CodeSignature/CodeResources +115 -0
  13. package/package.json +60 -4
  14. package/skills/inkless/SKILL.md +213 -0
  15. package/src/core/bits.js +143 -0
  16. package/src/core/blueprint/demos.js +119 -0
  17. package/src/core/blueprint/geometry.js +232 -0
  18. package/src/core/blueprint/index.js +100 -0
  19. package/src/core/blueprint/layout.js +210 -0
  20. package/src/core/blueprint/mesh.js +101 -0
  21. package/src/core/blueprint/methods.js +95 -0
  22. package/src/core/blueprint/remesh.js +250 -0
  23. package/src/core/blueprint/slice.js +134 -0
  24. package/src/core/blueprint/unfold.js +185 -0
  25. package/src/core/design/codes.js +39 -0
  26. package/src/core/design/filters.js +109 -0
  27. package/src/core/design/render.js +317 -0
  28. package/src/core/design/schema.js +132 -0
  29. package/src/core/formats/fit.js +46 -0
  30. package/src/core/formats/index.js +210 -0
  31. package/src/core/formats/library.js +341 -0
  32. package/src/core/formats/share.js +65 -0
  33. package/src/core/index.js +15 -0
  34. package/src/core/printers/hp6.js +160 -0
  35. package/src/core/printers/index.js +14 -0
  36. package/src/core/printers/pm290.js +115 -0
  37. package/src/core/session.js +56 -0
  38. package/src/node/artwork.js +33 -0
  39. package/src/node/cli.js +430 -0
  40. package/src/node/console/actions.js +30 -0
  41. package/src/node/console/client.js +68 -0
  42. package/src/node/console/paths.js +8 -0
  43. package/src/node/console/server.js +286 -0
  44. package/src/node/design.js +99 -0
  45. package/src/node/formats.js +39 -0
  46. package/src/node/frames.js +93 -0
  47. package/src/node/index.js +6 -0
  48. package/src/node/kit.js +12 -0
  49. package/src/node/skill.js +44 -0
  50. package/src/node/transports/index.js +21 -0
  51. package/src/node/transports/linux.js +52 -0
  52. package/src/node/transports/macos.js +81 -0
@@ -0,0 +1,286 @@
1
+ // @ts-check
2
+ // The console server: one shared design, a chat, and a way to print it.
3
+ // Agents and the browser console both talk to it over localhost.
4
+ import { createServer } from "node:http";
5
+ import { EventEmitter } from "node:events";
6
+ import { existsSync } from "node:fs";
7
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
8
+ import { dirname, extname, join, normalize, resolve, sep } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { normalizeDesign } from "../../core/design/schema.js";
11
+ import { listFormats } from "../../core/formats/index.js";
12
+ import { formatsDir as defaultFormatsDir, saveFormat, savedFormats } from "../formats.js";
13
+ import { infoFile, stateDir } from "./paths.js";
14
+
15
+ export const DEFAULT_PORT = 4380;
16
+ const MAX_BODY = 64 * 1024 * 1024;
17
+ const MAX_WAIT_S = 3600;
18
+ const DONE = new Set(["approved", "printing", "printed", "error"]);
19
+ const TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".mjs": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".json": "application/json", ".woff2": "font/woff2", ".ico": "image/x-icon", ".webp": "image/webp" };
20
+ const MISSING_PAGE = `<!doctype html><meta charset="utf-8"><title>inkless console</title>
21
+ <body style="font:16px system-ui;background:#111;color:#eee;padding:3rem">
22
+ <h1>The console is not built yet</h1><p>Run <code>npm run build -w @inkless/console</code>, then reload.</p>`;
23
+
24
+ /** Built console: in the repo, or shipped inside the published package. */
25
+ export function consoleDist() {
26
+ const here = dirname(fileURLToPath(import.meta.url));
27
+ return [join(here, "../../../../console/dist"), join(here, "../../../console-dist")].find((d) => existsSync(join(d, "index.html")));
28
+ }
29
+
30
+ /** What a waiter is told happened. */
31
+ export const eventOf = (status) => (status === "editing" ? "changed" : status);
32
+
33
+ /**
34
+ * @param {{
35
+ * port?: number, printerId?: string, dir?: string, staticDir?: string | null,
36
+ * print: (design: any) => Promise<string>,
37
+ * check: (options: { printer?: string, address?: string }) => Promise<string>,
38
+ * agentName?: string, formatsDir?: string,
39
+ * }} options print resolves to the message to post; both reject with the printer's error.
40
+ */
41
+ export async function startConsoleServer({ port, printerId = "pm290", dir = stateDir(), staticDir = consoleDist(), print, check, agentName = "Agent", formatsDir = defaultFormatsDir() }) {
42
+ const state = {
43
+ rev: 1,
44
+ design: /** @type {any} */ (null),
45
+ messages: /** @type {any[]} */ ([]),
46
+ status: "editing",
47
+ printer: /** @type {any} */ ({ id: printerId, status: "disconnected" }),
48
+ agentName,
49
+ };
50
+ try {
51
+ state.design = JSON.parse(await readFile(join(dir, "design.json"), "utf8"));
52
+ state.messages = JSON.parse(await readFile(join(dir, "messages.json"), "utf8"));
53
+ if (state.design) state.printer.id = state.design.printer;
54
+ } catch {
55
+ // first run, or nothing worth resuming
56
+ }
57
+
58
+ const bus = new EventEmitter().setMaxListeners(0);
59
+ let saveTimer = null;
60
+ const save = async () => {
61
+ saveTimer = null;
62
+ await mkdir(dir, { recursive: true });
63
+ await writeFile(join(dir, "design.json"), JSON.stringify(state.design));
64
+ await writeFile(join(dir, "messages.json"), JSON.stringify(state.messages));
65
+ };
66
+ const commit = () => {
67
+ state.rev++;
68
+ saveTimer ??= setTimeout(() => save().catch(() => {}), 150);
69
+ bus.emit("state");
70
+ };
71
+ const say = (from, text) => state.messages.push({ id: `m${state.messages.length + 1}`, from, text: String(text), at: Date.now() });
72
+
73
+ const doPrint = async () => {
74
+ const design = state.design;
75
+ state.status = "printing";
76
+ state.printer = { id: design.printer, status: "printing" };
77
+ commit();
78
+ try {
79
+ const message = await print(design);
80
+ state.status = "printed";
81
+ state.printer = { id: design.printer, status: "connected" };
82
+ say("system", message);
83
+ } catch (error) {
84
+ state.status = "error";
85
+ state.printer = { id: design.printer, status: "error", message: error.message };
86
+ say("system", `Printing failed: ${error.message}`);
87
+ }
88
+ commit();
89
+ };
90
+
91
+ /** Run one API call. Returns [status, body]. */
92
+ const handle = async (method, path, query, body) => {
93
+ if (method === "GET" && path === "/api/state") return [200, state];
94
+ if (method === "PUT" && path === "/api/design") {
95
+ if (body.from !== "human" && body.from !== "agent") throw httpError(400, 'from must be "human" or "agent"');
96
+ let design;
97
+ try {
98
+ design = normalizeDesign(body.design);
99
+ } catch (e) {
100
+ throw httpError(400, e.message);
101
+ }
102
+ if (state.status === "printing") throw httpError(409, "a print is running; wait for it to finish");
103
+ state.design = design;
104
+ state.printer = { ...state.printer, id: design.printer };
105
+ state.status = "editing";
106
+ if (body.from === "agent" && body.agentName) state.agentName = String(body.agentName);
107
+ commit();
108
+ return [200, { rev: state.rev }];
109
+ }
110
+ if (method === "POST" && path === "/api/messages") {
111
+ if (!["agent", "human", "system"].includes(body.from) || !String(body.text ?? "").trim()) throw httpError(400, "a message needs from and text");
112
+ if (body.from === "agent" && body.agentName) state.agentName = String(body.agentName);
113
+ say(body.from, body.text);
114
+ commit();
115
+ return [200, { rev: state.rev }];
116
+ }
117
+ if (method === "POST" && path === "/api/approve") {
118
+ if (!state.design) throw httpError(409, "there is no design to approve");
119
+ if (state.status === "printing") throw httpError(409, "a print is already running");
120
+ state.status = "approved";
121
+ commit();
122
+ const rev = state.rev;
123
+ if (body.print) setImmediate(doPrint);
124
+ return [200, { rev }];
125
+ }
126
+ if (method === "POST" && path === "/api/printer/check") {
127
+ const id = body.printer ?? state.printer.id;
128
+ state.printer = { id, status: "connecting" };
129
+ commit();
130
+ try {
131
+ const message = await check({ printer: id, address: body.address });
132
+ state.printer = { id, status: "connected" };
133
+ commit();
134
+ return [200, { ok: true, message }];
135
+ } catch (error) {
136
+ state.printer = { id, status: "error", message: error.message };
137
+ commit();
138
+ return [200, { ok: false, message: error.message }];
139
+ }
140
+ }
141
+ if (method === "GET" && path === "/api/formats") return [200, { formats: [...listFormats(), ...(await savedFormats(formatsDir))] }];
142
+ if (method === "POST" && path === "/api/formats") {
143
+ let format;
144
+ try {
145
+ format = await saveFormat(body.format, formatsDir);
146
+ } catch (e) {
147
+ throw httpError(400, e.message);
148
+ }
149
+ say("system", `Saved the format "${format.name}" (${format.id}). Fill it with: inkless print --format ${format.id} --set key=value`);
150
+ commit();
151
+ return [200, { format, rev: state.rev }];
152
+ }
153
+ throw httpError(404, "no such call");
154
+ };
155
+
156
+ const wait = (req, res, query) => {
157
+ const since = Number(query.get("since") ?? 0);
158
+ const until = query.get("until") === "any" ? "any" : "approved";
159
+ const seconds = Math.min(MAX_WAIT_S, Math.max(1, Number(query.get("timeout")) || 600));
160
+ const ready = () => state.rev > since && (until === "any" || DONE.has(state.status));
161
+ const finish = (/** @type {boolean} */ answered) => {
162
+ clearTimeout(timer);
163
+ bus.off("state", onState);
164
+ req.off("close", abandon);
165
+ if (answered) send(res, 200, { event: eventOf(state.status), ...state });
166
+ else if (!res.destroyed) res.writeHead(204).end();
167
+ };
168
+ const onState = () => ready() && finish(true);
169
+ const abandon = () => {
170
+ clearTimeout(timer);
171
+ bus.off("state", onState);
172
+ };
173
+ const timer = setTimeout(() => finish(false), seconds * 1000);
174
+ req.on("close", abandon);
175
+ if (ready()) return finish(true);
176
+ bus.on("state", onState);
177
+ };
178
+
179
+ const events = (req, res) => {
180
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
181
+ const push = () => res.write(`event: state\ndata: ${JSON.stringify(state)}\n\n`);
182
+ const beat = setInterval(() => res.write(": ping\n\n"), 25000);
183
+ bus.on("state", push);
184
+ req.on("close", () => {
185
+ clearInterval(beat);
186
+ bus.off("state", push);
187
+ });
188
+ push();
189
+ };
190
+
191
+ const serveFile = async (res, path) => {
192
+ if (!staticDir) return res.writeHead(200, { "content-type": TYPES[".html"] }).end(MISSING_PAGE);
193
+ const root = resolve(staticDir);
194
+ const file = normalize(join(root, path === "/" ? "index.html" : path));
195
+ if (file !== root && !file.startsWith(root + sep)) return res.writeHead(403).end();
196
+ try {
197
+ const bytes = await readFile(file);
198
+ res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream" }).end(bytes);
199
+ } catch {
200
+ res.writeHead(404, { "content-type": "text/plain" }).end("not found");
201
+ }
202
+ };
203
+
204
+ let allowed = new Set();
205
+ const server = createServer(async (req, res) => {
206
+ try {
207
+ const url = new URL(req.url ?? "/", "http://localhost");
208
+ const method = req.method ?? "GET";
209
+ // A web page must not be able to drive a local printer: only our own host and origin.
210
+ if (!allowed.has(req.headers.host ?? "")) return send(res, 403, { error: "bad host" });
211
+ if (req.headers.origin && method !== "GET" && !allowed.has(req.headers.origin.replace(/^http:\/\//, ""))) {
212
+ return send(res, 403, { error: "cross-origin writes are not allowed" });
213
+ }
214
+ if (method === "GET" && url.pathname === "/api/events") return events(req, res);
215
+ if (method === "GET" && url.pathname === "/api/wait") return wait(req, res, url.searchParams);
216
+ if (url.pathname.startsWith("/api/")) {
217
+ const body = method === "GET" ? {} : await readBody(req);
218
+ const [status, payload] = await handle(method, url.pathname, url.searchParams, body);
219
+ return send(res, status, payload);
220
+ }
221
+ if (method !== "GET") return send(res, 405, { error: "method not allowed" });
222
+ await serveFile(res, decodeURIComponent(url.pathname));
223
+ } catch (error) {
224
+ send(res, error.status ?? 500, { error: error.message });
225
+ }
226
+ });
227
+
228
+ const tryListen = (p) => new Promise((ok, no) => {
229
+ server.once("error", no);
230
+ server.listen(p, "127.0.0.1", () => {
231
+ server.off("error", no);
232
+ ok(undefined);
233
+ });
234
+ });
235
+ let actual = port ?? DEFAULT_PORT;
236
+ for (let i = 0; ; i++) {
237
+ try {
238
+ await tryListen(actual);
239
+ break;
240
+ } catch (error) {
241
+ if (error.code !== "EADDRINUSE" || port !== undefined || i >= 50) throw error;
242
+ actual++;
243
+ }
244
+ }
245
+ actual = /** @type {any} */ (server.address()).port;
246
+ allowed = new Set([`127.0.0.1:${actual}`, `localhost:${actual}`]);
247
+ const info = { port: actual, pid: process.pid, startedAt: new Date().toISOString() };
248
+ await mkdir(dirname(infoFile()), { recursive: true });
249
+ await writeFile(infoFile(), JSON.stringify(info));
250
+
251
+ return {
252
+ port: actual,
253
+ url: `http://127.0.0.1:${actual}`,
254
+ state,
255
+ async close() {
256
+ if (saveTimer) clearTimeout(saveTimer);
257
+ await save().catch(() => {});
258
+ const mine = await readFile(infoFile(), "utf8").then((t) => JSON.parse(t).pid === process.pid, () => false);
259
+ if (mine) await rm(infoFile(), { force: true });
260
+ server.closeAllConnections();
261
+ await new Promise((ok) => server.close(ok));
262
+ },
263
+ };
264
+ }
265
+
266
+ const httpError = (status, message) => Object.assign(new Error(message), { status });
267
+
268
+ function send(res, status, body) {
269
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(body));
270
+ }
271
+
272
+ async function readBody(req) {
273
+ const chunks = [];
274
+ let size = 0;
275
+ for await (const chunk of req) {
276
+ size += chunk.length;
277
+ if (size > MAX_BODY) throw httpError(413, "request too large");
278
+ chunks.push(chunk);
279
+ }
280
+ if (!size) return {};
281
+ try {
282
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
283
+ } catch {
284
+ throw httpError(400, "body is not JSON");
285
+ }
286
+ }
@@ -0,0 +1,99 @@
1
+ // @ts-check
2
+ // Designs on the Node side: reading them, printing every page, previews.
3
+ import { readFile, stat } from "node:fs/promises";
4
+ import { dirname, resolve, extname } from "node:path";
5
+ import { loadImage } from "@napi-rs/canvas";
6
+ import { normalizeDesign } from "../core/design/schema.js";
7
+ import { renderDesign, designFromArtwork } from "../core/design/render.js";
8
+ import { getPrinter } from "../core/printers/index.js";
9
+ import { runSession } from "../core/session.js";
10
+ import { isImage, readStdin } from "./artwork.js";
11
+ import { kit } from "./kit.js";
12
+
13
+ const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml" };
14
+ const MIN_INK = 80;
15
+
16
+ /** Local image files named in a design become data URLs, so any viewer can show them. */
17
+ export async function inlineImages(design, baseDir = process.cwd()) {
18
+ for (const page of design.pages) {
19
+ for (const el of page.elements) {
20
+ if (el.type !== "image" || /^(data|https?):/i.test(el.src)) continue;
21
+ const path = resolve(baseDir, el.src);
22
+ const bytes = await readFile(path).catch(() => {
23
+ throw new Error(`image ${el.src} not found (looked for ${path})`);
24
+ });
25
+ el.src = `data:${MIME[extname(path).toLowerCase()] ?? "image/png"};base64,${bytes.toString("base64")}`;
26
+ }
27
+ }
28
+ return design;
29
+ }
30
+
31
+ /** A design file, or null when the path is not one. */
32
+ export async function readDesignFile(input) {
33
+ if (!(await stat(input).then((s) => s.isFile(), () => false))) return null;
34
+ const bytes = await readFile(input);
35
+ if (bytes[0] === 0 || isImage(bytes)) return null;
36
+ let json;
37
+ try {
38
+ json = JSON.parse(bytes.toString("utf8"));
39
+ } catch {
40
+ return null;
41
+ }
42
+ if (json?.version !== 1) return null;
43
+ return inlineImages(normalizeDesign(json), dirname(resolve(input)));
44
+ }
45
+
46
+ /**
47
+ * A design file, an image file, "-" (stdin) or text, as a design.
48
+ * @param {string} input
49
+ * @param {{ printer?: "pm290" | "hp6", filter?: object, invert?: boolean, sizeMm?: { width: number, height: number }, widthMm?: number }} [options]
50
+ * filter and invert shape plain artwork only; a design file is used as written.
51
+ */
52
+ export async function designFor(input, { printer, filter, invert, sizeMm, widthMm } = {}) {
53
+ const design = input === "-" ? null : await readDesignFile(input);
54
+ if (design) return design;
55
+ const bytes = input === "-" ? await readStdin() : await stat(input).then((s) => (s.isFile() ? readFile(input) : null), () => null);
56
+ let art, aspect;
57
+ if (bytes && isImage(bytes)) {
58
+ const image = await loadImage(bytes);
59
+ aspect = image.width / image.height;
60
+ art = { kind: "image", src: `data:${MIME[extname(input).toLowerCase()] ?? "image/png"};base64,${bytes.toString("base64")}` };
61
+ } else if (bytes?.includes(0)) {
62
+ throw new Error(`${input} is neither an image nor text`);
63
+ } else {
64
+ art = { kind: "text", text: bytes ? bytes.toString("utf8") : input.replace(/\\n/g, "\n") };
65
+ }
66
+ const made = designFromArtwork(art, { printer, aspect, filter: art.kind === "image" ? filter : undefined, heightMm: sizeMm?.height });
67
+ if (sizeMm) made.size = { widthMm: sizeMm.width, heightMm: sizeMm.height };
68
+ else if (widthMm) made.size.widthMm = widthMm;
69
+ const [element] = made.pages[0].elements;
70
+ element.w = made.size.widthMm;
71
+ element.h = made.size.heightMm;
72
+ if (invert && art.kind === "text") element.invert = true;
73
+ return normalizeDesign(made);
74
+ }
75
+
76
+ /** Render every page of a design to the dots the printer will burn. */
77
+ export const renderPages = (design) => renderDesign(normalizeDesign(design), kit);
78
+
79
+ /**
80
+ * Print the rendered pages of a design, one label each, over one connection.
81
+ * @returns {Promise<number>} labels printed
82
+ */
83
+ export async function printPages(design, pages, { openTransport, address, name, density, onStatus, log = () => {} }) {
84
+ const printer = getPrinter(design.printer);
85
+ pages.forEach((p, i) => {
86
+ if (p.ink < MIN_INK) throw new Error(`label ${i + 1} is almost empty (${p.ink} black dots); nothing sent`);
87
+ });
88
+ const transport = await openTransport({ printer, address, name });
89
+ try {
90
+ log(`connected to ${transport.info?.name || printer.name} ${transport.info?.address ?? ""}`.trim());
91
+ for (const page of pages) {
92
+ const job = printer.buildJob({ ...page, density: design.density ?? density ?? printer.density({}) });
93
+ await runSession({ transport, printer, job, onStatus });
94
+ }
95
+ } finally {
96
+ await transport.close();
97
+ }
98
+ return pages.length;
99
+ }
@@ -0,0 +1,39 @@
1
+ // @ts-check
2
+ // Saved label formats live in ~/.inkless/formats/<id>.json, next to the built-in library.
3
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { getFormat, validateFormat } from "../core/formats/index.js";
6
+ import { inklessHome } from "./console/paths.js";
7
+
8
+ export const formatsDir = () => join(inklessHome(), "formats");
9
+
10
+ /** Every saved format; files that no longer validate are skipped. */
11
+ export async function savedFormats(dir = formatsDir()) {
12
+ const names = await readdir(dir).catch(() => []);
13
+ const formats = [];
14
+ for (const name of names.filter((n) => n.endsWith(".json")).sort()) {
15
+ try {
16
+ formats.push(validateFormat({ ...JSON.parse(await readFile(join(dir, name), "utf8")), saved: true }));
17
+ } catch {
18
+ // a broken file should not hide the others
19
+ }
20
+ }
21
+ return formats;
22
+ }
23
+
24
+ /** Save (or replace) a format. Built-in ids are taken. */
25
+ export async function saveFormat(input, dir = formatsDir()) {
26
+ const format = validateFormat({ ...input, saved: true });
27
+ if (getFormat(format.id)) throw new Error(`${format.id} is a built-in format; save it under another name`);
28
+ await mkdir(dir, { recursive: true });
29
+ await writeFile(join(dir, `${format.id}.json`), `${JSON.stringify(format, null, 2)}\n`);
30
+ return format;
31
+ }
32
+
33
+ /** A built-in or saved format by id. Throws with the ids there are. */
34
+ export async function findFormat(id, dir = formatsDir()) {
35
+ const saved = await savedFormats(dir);
36
+ const found = getFormat(id) ?? saved.find((f) => f.id === id);
37
+ if (!found) throw new Error(`no format "${id}"; see the list with: inkless formats`);
38
+ return found;
39
+ }
@@ -0,0 +1,93 @@
1
+ // @ts-check
2
+ // Length-prefixed frames between the CLI and a Bluetooth helper:
3
+ // [type: 1 byte][length: uint32 big-endian][payload]. Helpers are byte pipes;
4
+ // every printer protocol decision lives in the shared core.
5
+ // to helper: W write bytes, Q quit
6
+ // from helper: O opened (JSON {mtu, name, address}), A write acknowledged,
7
+ // D bytes from the printer, L device list (JSON), E error text
8
+
9
+ export function encodeFrame(type, payload = new Uint8Array(0)) {
10
+ const body = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
11
+ const out = new Uint8Array(5 + body.length);
12
+ out[0] = type.charCodeAt(0);
13
+ new DataView(out.buffer).setUint32(1, body.length);
14
+ out.set(body, 5);
15
+ return out;
16
+ }
17
+
18
+ /** Incremental decoder: feed chunks, get whole frames. */
19
+ export class FrameDecoder {
20
+ constructor() {
21
+ this.buffer = new Uint8Array(0);
22
+ }
23
+
24
+ /** @returns {{ type: string, payload: Uint8Array }[]} */
25
+ push(chunk) {
26
+ const joined = new Uint8Array(this.buffer.length + chunk.length);
27
+ joined.set(this.buffer);
28
+ joined.set(chunk, this.buffer.length);
29
+ const frames = [];
30
+ let at = 0;
31
+ while (joined.length - at >= 5) {
32
+ const length = new DataView(joined.buffer, joined.byteOffset + at + 1, 4).getUint32(0);
33
+ if (joined.length - at - 5 < length) break;
34
+ frames.push({ type: String.fromCharCode(joined[at]), payload: joined.slice(at + 5, at + 5 + length) });
35
+ at += 5 + length;
36
+ }
37
+ this.buffer = joined.slice(at);
38
+ return frames;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Wrap a duplex byte stream that speaks frames into a core Transport.
44
+ * @param {{ write(bytes: Uint8Array): void, on(event: string, fn: Function): void }} stream
45
+ */
46
+ export function framedTransport(stream, { label = "helper" } = {}) {
47
+ const decoder = new FrameDecoder();
48
+ let listener = (_bytes) => {};
49
+ let failure = null;
50
+ const acks = [];
51
+ let opened;
52
+ let openedReject;
53
+ const ready = new Promise((resolve, reject) => {
54
+ opened = resolve;
55
+ openedReject = reject;
56
+ });
57
+ const fail = (error) => {
58
+ if (failure) return;
59
+ failure = error;
60
+ openedReject(error);
61
+ for (const ack of acks.splice(0)) ack.reject(error);
62
+ };
63
+ stream.on("data", (chunk) => {
64
+ for (const { type, payload } of decoder.push(new Uint8Array(chunk))) {
65
+ const text = () => new TextDecoder().decode(payload);
66
+ if (type === "O") opened(JSON.parse(text()));
67
+ else if (type === "L") opened({ devices: JSON.parse(text()) });
68
+ else if (type === "A") acks.shift()?.resolve();
69
+ else if (type === "D") listener(payload);
70
+ else if (type === "E") fail(new Error(text()));
71
+ }
72
+ });
73
+ const closed = () => fail(new Error(`${label} closed the connection`));
74
+ stream.on("end", closed);
75
+ stream.on("close", closed);
76
+ stream.on("error", (error) => fail(error));
77
+
78
+ return {
79
+ ready,
80
+ mtu: 512,
81
+ onData: (fn) => (listener = fn),
82
+ write(bytes) {
83
+ if (failure) return Promise.reject(failure);
84
+ return new Promise((resolve, reject) => {
85
+ acks.push({ resolve, reject });
86
+ stream.write(encodeFrame("W", bytes));
87
+ });
88
+ },
89
+ quit() {
90
+ if (!failure) stream.write(encodeFrame("Q"));
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,6 @@
1
+ // @ts-check
2
+ // Node-only helpers: artwork loading, previews and Bluetooth transports.
3
+ export { previewPng } from "./artwork.js";
4
+ export { readDesignFile, designFor, renderPages, printPages } from "./design.js";
5
+ export { openTransport, pairedDevices } from "./transports/index.js";
6
+ export { main } from "./cli.js";
@@ -0,0 +1,12 @@
1
+ // @ts-check
2
+ // The canvas kit the shared design renderer needs, backed by @napi-rs/canvas.
3
+ import { readFile } from "node:fs/promises";
4
+ import { createCanvas, loadImage, Path2D } from "@napi-rs/canvas";
5
+
6
+ /** Image sources: data and http(s) URLs as usual, anything else is a file path. */
7
+ export const kit = {
8
+ createCanvas,
9
+ Path2D,
10
+ loadImage: async (/** @type {string} */ src) =>
11
+ /^(data|https?):/i.test(src) ? loadImage(src) : loadImage(await readFile(src)),
12
+ };
@@ -0,0 +1,44 @@
1
+ // @ts-check
2
+ // Put the inkless skill where coding agents look for skills.
3
+ import { existsSync } from "node:fs";
4
+ import { cp, readFile, rm, mkdir } from "node:fs/promises";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const here = dirname(fileURLToPath(import.meta.url));
10
+
11
+ /** The skill folder: in the repo (skills/inkless) or shipped in the package. */
12
+ const source = () =>
13
+ [join(here, "../../../../skills/inkless"), join(here, "../../skills/inkless")].find((d) => existsSync(join(d, "SKILL.md")));
14
+
15
+ const homes = {
16
+ claude: () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "skills"),
17
+ codex: () => join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "skills"),
18
+ };
19
+
20
+ /**
21
+ * @param {"install" | "uninstall"} action
22
+ * @param {{ agent?: string, dest?: string, log?: (m: string) => void }} options
23
+ */
24
+ export async function manageSkill(action, { agent = "all", dest, log = console.log }) {
25
+ if (!dest && agent !== "all" && !(agent in homes)) throw new Error("--agent is claude, codex or all");
26
+ const roots = dest ? [resolve(dest)] : (agent === "all" ? Object.keys(homes) : [agent]).map((a) => homes[a]());
27
+ const from = source();
28
+ if (action === "install" && !from) throw new Error("the skill folder is missing from this install");
29
+ for (const root of roots) {
30
+ const target = join(root, "inkless");
31
+ if (action === "install") {
32
+ await mkdir(root, { recursive: true });
33
+ await rm(target, { recursive: true, force: true });
34
+ await cp(from, target, { recursive: true });
35
+ log(`installed the inkless skill to ${target}`);
36
+ } else if (await readFile(join(target, "SKILL.md"), "utf8").then((t) => /^name: inkless$/m.test(t), () => false)) {
37
+ await rm(target, { recursive: true, force: true });
38
+ log(`removed ${target}`);
39
+ } else {
40
+ log(`no inkless skill at ${target}`);
41
+ }
42
+ }
43
+ if (action === "install") log("start a new agent session to use it");
44
+ }
@@ -0,0 +1,21 @@
1
+ // @ts-check
2
+ import { openMacTransport } from "./macos.js";
3
+ import { openLinuxTransport, linuxDevices } from "./linux.js";
4
+
5
+ /** Open a byte transport to the printer on this platform. */
6
+ export function openTransport(options) {
7
+ if (process.platform === "darwin") return openMacTransport(options);
8
+ if (process.platform === "linux") return openLinuxTransport(options);
9
+ throw new Error(`Bluetooth printing from ${process.platform} is not supported yet; use the website in Chrome`);
10
+ }
11
+
12
+ /** Paired Bluetooth devices: [{ address, name }]. */
13
+ export async function pairedDevices() {
14
+ if (process.platform === "darwin") {
15
+ const transport = await openMacTransport({ list: true });
16
+ await transport.close();
17
+ return transport.info.devices;
18
+ }
19
+ if (process.platform === "linux") return linuxDevices();
20
+ return [];
21
+ }
@@ -0,0 +1,52 @@
1
+ // @ts-check
2
+ // Linux: Python's standard socket module speaks RFCOMM natively, so a small
3
+ // script pipes bytes over stdio. Pair the printer with bluetoothctl first.
4
+ import { spawn, execFileSync } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ import { framedTransport } from "../frames.js";
7
+
8
+ const SCRIPT = fileURLToPath(new URL("../../../native/linux/rfcomm.py", import.meta.url));
9
+
10
+ /** Paired devices from bluetoothctl, as [{ address, name }]. */
11
+ export function linuxDevices() {
12
+ let out = "";
13
+ try {
14
+ out = execFileSync("bluetoothctl", ["devices", "Paired"], { encoding: "utf8", timeout: 5000 });
15
+ } catch {
16
+ throw new Error("bluetoothctl is not available; install BlueZ and pair the printer first");
17
+ }
18
+ return out.split("\n").map((line) => /^Device ([0-9A-F:]{17}) (.*)$/i.exec(line.trim()))
19
+ .filter(Boolean).map((m) => ({ address: m[1], name: m[2] }));
20
+ }
21
+
22
+ /** @param {{ printer: any, address?: string, name?: string, channel?: number, launch?: (args: string[]) => any }} options */
23
+ export async function openLinuxTransport({ printer, address, name, channel = 1, launch }) {
24
+ if (!address) {
25
+ const wanted = (name ?? printer.bluetoothName).toLowerCase();
26
+ const matches = linuxDevices().filter((d) => d.name.toLowerCase().includes(wanted));
27
+ if (matches.length !== 1) {
28
+ throw new Error(matches.length ? `several paired devices match ${wanted}; pass --address` : `no paired device matches ${wanted}; pair it with bluetoothctl or pass --address`);
29
+ }
30
+ address = matches[0].address;
31
+ }
32
+ const args = [SCRIPT, "--address", address, "--channel", String(channel)];
33
+ const child = launch ? launch(args) : spawn("python3", args, { stdio: ["pipe", "pipe", "inherit"] });
34
+ const stream = {
35
+ write: (bytes) => child.stdin.write(bytes),
36
+ on: (event, fn) => (event === "data" ? child.stdout.on("data", fn) : child.stdout.on(event, fn)),
37
+ };
38
+ const transport = framedTransport(stream, { label: "RFCOMM helper" });
39
+ const close = async () => {
40
+ transport.quit();
41
+ child.stdin.end();
42
+ await new Promise((resolve) => (child.exitCode !== null ? resolve(undefined) : child.once("exit", resolve)));
43
+ };
44
+ try {
45
+ const info = await transport.ready;
46
+ if (info.mtu) transport.mtu = info.mtu;
47
+ return { ...transport, info, close, mtu: transport.mtu };
48
+ } catch (error) {
49
+ child.kill();
50
+ throw error;
51
+ }
52
+ }