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.
- package/LICENSE +21 -0
- package/README.md +65 -2
- package/bin/inkless.js +10 -0
- package/console-dist/assets/BlueprintTool-CLWuM21a.js +4226 -0
- package/console-dist/assets/index-CIqLZU6s.js +33 -0
- package/console-dist/assets/index-Dv7Gg9qm.css +1 -0
- package/console-dist/favicon.svg +11 -0
- package/console-dist/index.html +18 -0
- package/native/linux/rfcomm.py +84 -0
- package/native/macos/build/InklessBluetooth.app/Contents/Info.plist +26 -0
- package/native/macos/build/InklessBluetooth.app/Contents/MacOS/InklessBluetooth +0 -0
- package/native/macos/build/InklessBluetooth.app/Contents/_CodeSignature/CodeResources +115 -0
- package/package.json +60 -4
- package/skills/inkless/SKILL.md +213 -0
- package/src/core/bits.js +143 -0
- package/src/core/blueprint/demos.js +119 -0
- package/src/core/blueprint/geometry.js +232 -0
- package/src/core/blueprint/index.js +100 -0
- package/src/core/blueprint/layout.js +210 -0
- package/src/core/blueprint/mesh.js +101 -0
- package/src/core/blueprint/methods.js +95 -0
- package/src/core/blueprint/remesh.js +250 -0
- package/src/core/blueprint/slice.js +134 -0
- package/src/core/blueprint/unfold.js +185 -0
- package/src/core/design/codes.js +39 -0
- package/src/core/design/filters.js +109 -0
- package/src/core/design/render.js +317 -0
- package/src/core/design/schema.js +132 -0
- package/src/core/formats/fit.js +46 -0
- package/src/core/formats/index.js +210 -0
- package/src/core/formats/library.js +341 -0
- package/src/core/formats/share.js +65 -0
- package/src/core/index.js +15 -0
- package/src/core/printers/hp6.js +160 -0
- package/src/core/printers/index.js +14 -0
- package/src/core/printers/pm290.js +115 -0
- package/src/core/session.js +56 -0
- package/src/node/artwork.js +33 -0
- package/src/node/cli.js +430 -0
- package/src/node/console/actions.js +30 -0
- package/src/node/console/client.js +68 -0
- package/src/node/console/paths.js +8 -0
- package/src/node/console/server.js +286 -0
- package/src/node/design.js +99 -0
- package/src/node/formats.js +39 -0
- package/src/node/frames.js +93 -0
- package/src/node/index.js +6 -0
- package/src/node/kit.js +12 -0
- package/src/node/skill.js +44 -0
- package/src/node/transports/index.js +21 -0
- package/src/node/transports/linux.js +52 -0
- package/src/node/transports/macos.js +81 -0
package/src/node/cli.js
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
5
|
+
import { printers, getPrinter } from "../core/printers/index.js";
|
|
6
|
+
import { runSession } from "../core/session.js";
|
|
7
|
+
import { DEMO_MODELS, LABELS, MODEL_TYPES, demoModel, loadModel, makeBlueprint } from "../core/blueprint/index.js";
|
|
8
|
+
import { previewPng } from "./artwork.js";
|
|
9
|
+
import { designFor, printPages, readDesignFile, renderPages } from "./design.js";
|
|
10
|
+
import { openTransport, pairedDevices } from "./transports/index.js";
|
|
11
|
+
import { startConsoleServer } from "./console/server.js";
|
|
12
|
+
import { printerActions } from "./console/actions.js";
|
|
13
|
+
import { ask, call, findServer, openBrowser, requireServer, startBackground } from "./console/client.js";
|
|
14
|
+
import { manageSkill } from "./skill.js";
|
|
15
|
+
import { fillFormat, formatFromDesign, listFormats } from "../core/formats/index.js";
|
|
16
|
+
import { SITE_URL, shareLink } from "../core/formats/share.js";
|
|
17
|
+
import { findFormat, saveFormat, savedFormats } from "./formats.js";
|
|
18
|
+
|
|
19
|
+
const USAGE = `inkless: print stickers and labels on Bluetooth thermal printers
|
|
20
|
+
|
|
21
|
+
inkless print <design.json|image|text|-> print it
|
|
22
|
+
inkless preview <design.json|image|text|-> save the exact black-and-white result as PNG
|
|
23
|
+
inkless check is the printer there? prints nothing
|
|
24
|
+
inkless printers supported printers, and which are paired
|
|
25
|
+
inkless blueprint <model> cut a 3D model (stl, obj, glb, gltf, vox) into flat pieces for a 3D pen
|
|
26
|
+
inkless console [design.json|image|text] open the console: design with an agent, approve, print
|
|
27
|
+
inkless formats ready-made label formats to fill in (and the ones you saved)
|
|
28
|
+
inkless skill install teach your coding agent to use inkless
|
|
29
|
+
|
|
30
|
+
A design file is JSON with "version": 1 (see the skill for the format). A design can have
|
|
31
|
+
several pages; print makes one label per page and preview writes preview-1.png, preview-2.png...
|
|
32
|
+
|
|
33
|
+
Options for print and preview:
|
|
34
|
+
--printer pm290|hp6 which printer (default pm290; a design file names its own)
|
|
35
|
+
--style floyd|atkinson|ordered|threshold
|
|
36
|
+
how a photo's grays become dots (default floyd)
|
|
37
|
+
--level <0-255> lightness cut-off (default 128)
|
|
38
|
+
--size <W>x<H> label size in mm on the PM290 roll, e.g. 48x30
|
|
39
|
+
--width <dots> PM290 print width, 1-384 (default 384)
|
|
40
|
+
--invert swap black and white
|
|
41
|
+
--dark | --light burn harder or softer
|
|
42
|
+
--out <file.png> preview: base name to save to (default /tmp/inkless/preview.png; several pages add -1, -2...)
|
|
43
|
+
--format <id> start from a label format instead of a file (see inkless formats)
|
|
44
|
+
--set key=value fill a format field; repeat it for each field (\\n makes a new line)
|
|
45
|
+
--export-job <file> print: save the printer bytes instead of printing (one page)
|
|
46
|
+
|
|
47
|
+
Connection (print, check, console):
|
|
48
|
+
--address <MAC> pick the printer by Bluetooth address
|
|
49
|
+
--name <text> pick a paired printer by name
|
|
50
|
+
|
|
51
|
+
Blueprint:
|
|
52
|
+
--method slotted|stacked|radial|unfold
|
|
53
|
+
interlocking cross sections, level layers, fins held by rings,
|
|
54
|
+
or folded nets with numbered edges (default slotted)
|
|
55
|
+
--fill outline|solid|ribs how each piece is drawn for the pen (default outline)
|
|
56
|
+
--size <mm> real size of the finished object's largest side (default 120)
|
|
57
|
+
--height <mm> or its real height instead
|
|
58
|
+
--label roll|48x48|48x30|hp6
|
|
59
|
+
labels to print on: the PM290 roll at any length, fixed PM290
|
|
60
|
+
labels, or HP6-C 36x12 mm (default roll, hp6 with --printer hp6)
|
|
61
|
+
--demo duck|rocket|chair|dino|vase use a built-in model instead of a file
|
|
62
|
+
--out <design.json> where to save the labels (default blueprint.json)
|
|
63
|
+
--preview <dir> also save a PNG of every label there
|
|
64
|
+
--console open the result in the console
|
|
65
|
+
|
|
66
|
+
Console:
|
|
67
|
+
inkless console start the console in the foreground and open the browser
|
|
68
|
+
inkless console show <design> agent: push a design (starts a console in the background if needed)
|
|
69
|
+
inkless console say "<text>" agent: post a chat message
|
|
70
|
+
inkless console wait agent: block until the human approves; prints one JSON line
|
|
71
|
+
inkless console get agent: print the current design (--out <file> to save it)
|
|
72
|
+
inkless console stop stop the console
|
|
73
|
+
inkless console link [design] print a website link with the design in it (or --format ... --set ...)
|
|
74
|
+
--port <n> port (default 4380, or the next free one)
|
|
75
|
+
--no-open do not open the browser
|
|
76
|
+
--until approved|any wait: stop on approval (default) or on any change
|
|
77
|
+
--timeout <seconds> wait: give up after this long (default 600, exit code 2)
|
|
78
|
+
--since <rev> wait: only changes after this revision
|
|
79
|
+
--as <name> show, say: the agent's name in the chat
|
|
80
|
+
|
|
81
|
+
Formats:
|
|
82
|
+
inkless formats [--printer hp6] list them: id, size, printers, fields
|
|
83
|
+
inkless formats show <id> [--json] its fields and examples (--json: the whole format)
|
|
84
|
+
inkless formats save <design.json> --name "My label" [--description ...]
|
|
85
|
+
save a design as your own format in ~/.inkless/formats
|
|
86
|
+
Fill one anywhere a design goes: inkless preview --format parts-bin --set name="M4 NUTS" --set bin=12
|
|
87
|
+
Fields you leave out keep their example. INKLESS_SITE changes the site console link uses.
|
|
88
|
+
|
|
89
|
+
Skill:
|
|
90
|
+
inkless skill install [--agent claude|codex|all] copy the skill into the agent's skills folder
|
|
91
|
+
inkless skill uninstall [--agent ...] remove it
|
|
92
|
+
|
|
93
|
+
Pair the printer first and close its phone app; only one of them can hold it.
|
|
94
|
+
`;
|
|
95
|
+
|
|
96
|
+
const OPTIONS = /** @type {const} */ ({
|
|
97
|
+
printer: { type: "string" },
|
|
98
|
+
style: { type: "string" },
|
|
99
|
+
level: { type: "string" },
|
|
100
|
+
size: { type: "string" },
|
|
101
|
+
width: { type: "string" },
|
|
102
|
+
invert: { type: "boolean", default: false },
|
|
103
|
+
dark: { type: "boolean", default: false },
|
|
104
|
+
light: { type: "boolean", default: false },
|
|
105
|
+
out: { type: "string" },
|
|
106
|
+
"export-job": { type: "string" },
|
|
107
|
+
address: { type: "string" },
|
|
108
|
+
name: { type: "string" },
|
|
109
|
+
method: { type: "string" },
|
|
110
|
+
fill: { type: "string" },
|
|
111
|
+
height: { type: "string" },
|
|
112
|
+
label: { type: "string" },
|
|
113
|
+
demo: { type: "string" },
|
|
114
|
+
preview: { type: "string" },
|
|
115
|
+
console: { type: "boolean", default: false },
|
|
116
|
+
port: { type: "string" },
|
|
117
|
+
"no-open": { type: "boolean", default: false },
|
|
118
|
+
until: { type: "string" },
|
|
119
|
+
timeout: { type: "string" },
|
|
120
|
+
since: { type: "string" },
|
|
121
|
+
as: { type: "string" },
|
|
122
|
+
agent: { type: "string" },
|
|
123
|
+
dest: { type: "string" },
|
|
124
|
+
format: { type: "string" },
|
|
125
|
+
set: { type: "string", multiple: true },
|
|
126
|
+
description: { type: "string" },
|
|
127
|
+
json: { type: "boolean", default: false },
|
|
128
|
+
help: { type: "boolean", short: "h", default: false },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const ART = ["printer", "style", "level", "size", "width", "invert"];
|
|
132
|
+
const CONNECT = ["address", "name"];
|
|
133
|
+
const FORMAT = ["format", "set"];
|
|
134
|
+
|
|
135
|
+
/** Per command: the options it accepts and how many words follow it, so a typo never silently does nothing. */
|
|
136
|
+
const COMMANDS = {
|
|
137
|
+
print: { accepts: [...ART, "dark", "light", "export-job", ...CONNECT, ...FORMAT], args: [0, 1] },
|
|
138
|
+
preview: { accepts: [...ART, "out", ...FORMAT], args: [0, 1] },
|
|
139
|
+
check: { accepts: ["printer", ...CONNECT], args: [0, 0] },
|
|
140
|
+
printers: { accepts: [], args: [0, 0] },
|
|
141
|
+
blueprint: { accepts: ["method", "fill", "size", "height", "label", "demo", "out", "preview", "console", "printer", "port", "no-open"], args: [0, 1] },
|
|
142
|
+
console: { accepts: ["port", "no-open", "printer", ...CONNECT], args: [0, 1] },
|
|
143
|
+
"console show": { accepts: ["port", "no-open", "printer", "as", ...CONNECT, ...FORMAT], args: [0, 1] },
|
|
144
|
+
"console say": { accepts: ["as"], args: [1, 1] },
|
|
145
|
+
"console wait": { accepts: ["until", "timeout", "since"], args: [0, 0] },
|
|
146
|
+
"console get": { accepts: ["out"], args: [0, 0] },
|
|
147
|
+
"console stop": { accepts: [], args: [0, 0] },
|
|
148
|
+
"console link": { accepts: ["printer", ...FORMAT], args: [0, 1] },
|
|
149
|
+
formats: { accepts: ["printer"], args: [0, 0] },
|
|
150
|
+
"formats show": { accepts: ["json"], args: [1, 1] },
|
|
151
|
+
"formats save": { accepts: ["name", "description"], args: [1, 1] },
|
|
152
|
+
"skill install": { accepts: ["agent", "dest"], args: [0, 0] },
|
|
153
|
+
"skill uninstall": { accepts: ["agent", "dest"], args: [0, 0] },
|
|
154
|
+
};
|
|
155
|
+
const SUBCOMMANDS = { console: ["show", "say", "wait", "get", "stop", "link"], skill: ["install", "uninstall"], formats: ["show", "save"] };
|
|
156
|
+
|
|
157
|
+
const fail = (message) => {
|
|
158
|
+
throw Object.assign(new Error(message), { usage: true });
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
function parse(argv) {
|
|
162
|
+
const { values, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
|
|
163
|
+
const [first, ...rest] = positionals;
|
|
164
|
+
if (values.help || !first || first === "help") return { command: "help" };
|
|
165
|
+
if (!(first in COMMANDS) && !(first in SUBCOMMANDS)) fail(`unknown command ${first}`);
|
|
166
|
+
if (first === "skill" && !SUBCOMMANDS.skill.includes(rest[0])) fail("skill needs install or uninstall");
|
|
167
|
+
const command = SUBCOMMANDS[first]?.includes(rest[0]) ? `${first} ${rest.shift()}` : first;
|
|
168
|
+
const spec = COMMANDS[command];
|
|
169
|
+
const given = argv.filter((a) => a.startsWith("--")).map((a) => a.slice(2).split("=")[0]);
|
|
170
|
+
const stray = given.find((name) => name !== "help" && !spec.accepts.includes(name));
|
|
171
|
+
if (stray) fail(`${command} does not take --${stray}`);
|
|
172
|
+
const [min, max] = spec.args;
|
|
173
|
+
if (rest.length < min || rest.length > max) {
|
|
174
|
+
fail(max === 0 ? `${command} takes no arguments` : `${command} needs ${min === max ? "one" : "at most one"} ${/^(console|formats)/.test(command) ? "argument" : "image, design, text or '-'"}`);
|
|
175
|
+
}
|
|
176
|
+
return { command, input: rest[0], values };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function intOption(value, name, min, max) {
|
|
180
|
+
if (value === undefined) return undefined;
|
|
181
|
+
const n = Number(value);
|
|
182
|
+
if (!Number.isInteger(n) || n < min || n > max) fail(`--${name} needs a whole number from ${min} to ${max}`);
|
|
183
|
+
return n;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** --set key=value pairs as an object; a typed \n is a new line, as in plain text. */
|
|
187
|
+
function setValues(pairs = []) {
|
|
188
|
+
return Object.fromEntries(pairs.map((pair) => {
|
|
189
|
+
const at = pair.indexOf("=");
|
|
190
|
+
if (at < 1) fail(`--set looks like key=value, not ${pair}`);
|
|
191
|
+
return [pair.slice(0, at), pair.slice(at + 1).replace(/\\n/g, "\n")];
|
|
192
|
+
}));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A format filled from --format and --set, or null when the command names a file instead. */
|
|
196
|
+
async function formatDesign(input, values) {
|
|
197
|
+
if (!values.format) {
|
|
198
|
+
if (values.set) fail("--set fills a format; add --format <id>");
|
|
199
|
+
if (!input) fail("give an image, a design, some text or --format <id>");
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
if (input) fail("give either a file or --format, not both");
|
|
203
|
+
return fillFormat(await findFormat(values.format), setValues(values.set), { printer: values.printer });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The design a command works on: a format, a design file, or plain artwork. */
|
|
207
|
+
const designOf = async (input, values) => (await formatDesign(input, values)) ?? designFor(input, { printer: values.printer });
|
|
208
|
+
|
|
209
|
+
/** The design to print or preview: a format, a design file as written, or plain artwork shaped by the options. */
|
|
210
|
+
async function designFromInput(input, values, printer) {
|
|
211
|
+
const filled = await formatDesign(input, values);
|
|
212
|
+
if (filled) return filled;
|
|
213
|
+
const sizeMatch = values.size ? /^(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)$/.exec(values.size) : null;
|
|
214
|
+
if (values.size && !sizeMatch) fail("--size looks like 48x30 (millimetres)");
|
|
215
|
+
const widthDots = intOption(values.width, "width", 1, 384);
|
|
216
|
+
if ((values.size || widthDots) && printer.media.kind === "label") {
|
|
217
|
+
fail(`${printer.name} labels are a fixed ${printer.media.widthMm}x${printer.media.heightMm} mm; drop --size and --width`);
|
|
218
|
+
}
|
|
219
|
+
const sizeMm = sizeMatch ? { width: Number(sizeMatch[1]), height: Number(sizeMatch[2]) } : undefined;
|
|
220
|
+
if (sizeMm && sizeMm.width > printer.media.widthMm) fail(`${printer.name} prints at most ${printer.media.widthMm} mm wide; --size does not fit`);
|
|
221
|
+
const style = values.style ?? "floyd";
|
|
222
|
+
if (!["floyd", "atkinson", "ordered", "threshold"].includes(style)) fail("--style is floyd, atkinson, ordered or threshold");
|
|
223
|
+
const level = intOption(values.level, "level", 0, 255);
|
|
224
|
+
const filter = {
|
|
225
|
+
mode: style === "threshold" ? "threshold" : "dither",
|
|
226
|
+
...(style !== "threshold" && { style }),
|
|
227
|
+
...(level !== undefined && { level }),
|
|
228
|
+
...(values.invert && { invert: true }),
|
|
229
|
+
};
|
|
230
|
+
return designFor(input, { printer: printer.id, filter, invert: values.invert, sizeMm, widthMm: widthDots && widthDots / 8 });
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function save(path, bytes) {
|
|
234
|
+
const target = resolve(path);
|
|
235
|
+
await mkdir(dirname(target), { recursive: true });
|
|
236
|
+
await writeFile(target, bytes);
|
|
237
|
+
return target;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const describe = (printer, p) => `${printer.name} ${p.width}x${p.height} dots (${(p.width / 8).toFixed(1)}x${(p.height / 8).toFixed(1)} mm), ${p.ink} black`;
|
|
241
|
+
|
|
242
|
+
/** Pages as PNGs: the base path for one page, base-1.png, base-2.png... for several. */
|
|
243
|
+
async function savePreviews(pages, base, log) {
|
|
244
|
+
const ext = extname(base) || ".png";
|
|
245
|
+
const stem = base.slice(0, base.length - (extname(base) ? ext.length : 0));
|
|
246
|
+
for (const [i, page] of pages.entries()) {
|
|
247
|
+
const path = await save(pages.length === 1 ? base : `${stem}-${i + 1}${ext}`, previewPng(page));
|
|
248
|
+
log(`preview saved to ${path}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const withPrinter = async (printer, values, log, job) => {
|
|
253
|
+
const transport = await openTransport({ printer, address: values.address, name: values.name });
|
|
254
|
+
try {
|
|
255
|
+
log(`connected to ${transport.info.name || printer.name} ${transport.info.address ?? ""}`.trim());
|
|
256
|
+
await runSession({ transport, printer, job, onStatus: (m) => process.env.INKLESS_VERBOSE && log(m) });
|
|
257
|
+
} finally {
|
|
258
|
+
await transport.close();
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
async function listPrinters(log) {
|
|
263
|
+
for (const p of Object.values(printers)) {
|
|
264
|
+
const size = p.media.kind === "roll" ? `${p.media.widthMm} mm roll` : `${p.media.widthMm}x${p.media.heightMm} mm labels`;
|
|
265
|
+
log(`${p.id.padEnd(7)} ${p.name}${p.aliases.length ? ` (${p.aliases.join(", ")})` : ""}, ${size}`);
|
|
266
|
+
}
|
|
267
|
+
const devices = await pairedDevices().catch((e) => (log(`paired devices: ${e.message}`), []));
|
|
268
|
+
const known = devices.filter((d) => Object.values(printers).some((p) => d.name.toLowerCase().includes(p.bluetoothName.toLowerCase())));
|
|
269
|
+
log(known.length ? `\npaired:\n${known.map((d) => ` ${d.name} ${d.address}`).join("\n")}` : "\nno supported printer is paired");
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async function printOrPreview(command, input, values, log) {
|
|
273
|
+
const design = await designFromInput(input, values, getPrinter(values.printer));
|
|
274
|
+
const printer = getPrinter(design.printer);
|
|
275
|
+
if (values.printer && values.printer !== design.printer && input?.endsWith(".json")) fail(`the design is for ${design.printer}; drop --printer or edit the design`);
|
|
276
|
+
const pages = await renderPages(design);
|
|
277
|
+
pages.forEach((p) => log(describe(printer, p)));
|
|
278
|
+
if (command === "preview") return savePreviews(pages, values.out ?? "/tmp/inkless/preview.png", log);
|
|
279
|
+
|
|
280
|
+
const density = printer.density(values);
|
|
281
|
+
const empty = pages.findIndex((p) => p.ink < 80);
|
|
282
|
+
if (empty >= 0) fail(`${pages.length > 1 ? `label ${empty + 1}` : "the artwork"} is almost empty (${pages[empty].ink} black dots); nothing sent`);
|
|
283
|
+
await save("/tmp/inkless/last.png", previewPng(pages[0]));
|
|
284
|
+
if (values["export-job"]) {
|
|
285
|
+
if (pages.length > 1) fail("--export-job saves one label; this design has several pages");
|
|
286
|
+
const job = printer.buildJob({ ...pages[0], density: design.density ?? density });
|
|
287
|
+
return log(`saved ${job.length} printer bytes to ${await save(values["export-job"], job)}; nothing sent`);
|
|
288
|
+
}
|
|
289
|
+
const count = await printPages(design, pages, {
|
|
290
|
+
openTransport, address: values.address, name: values.name, density, log,
|
|
291
|
+
onStatus: (m) => process.env.INKLESS_VERBOSE && log(m),
|
|
292
|
+
});
|
|
293
|
+
log(`printed ${count} ${count === 1 ? "label" : "labels"}; the ${printer.name} confirmed it finished`);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Push a design to the console, starting one in the background if none runs. */
|
|
297
|
+
async function showDesign(design, values, log) {
|
|
298
|
+
let server = await findServer();
|
|
299
|
+
const started = !server;
|
|
300
|
+
server ??= await startBackground({ noOpen: values["no-open"], port: values.port, printer: design.printer, address: values.address, name: values.name });
|
|
301
|
+
await ask(server.port, "PUT", "/api/design", { design, from: "agent", agentName: values.as });
|
|
302
|
+
log(`${started ? "console started" : "console updated"}: http://127.0.0.1:${server.port}`);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async function runBlueprint(input, values, log) {
|
|
306
|
+
if (!input && !values.demo) fail(`blueprint needs a model file (${MODEL_TYPES.join(", ")}) or --demo ${DEMO_MODELS.join("|")}`);
|
|
307
|
+
if (values.demo && !DEMO_MODELS.includes(values.demo)) fail(`--demo is ${DEMO_MODELS.join(", ")}`);
|
|
308
|
+
const mesh = values.demo ? demoModel(values.demo) : loadModel(input, new Uint8Array(await readFile(input)));
|
|
309
|
+
const method = values.method ?? "slotted";
|
|
310
|
+
const fill = values.fill ?? "outline";
|
|
311
|
+
if (!["slotted", "stacked", "radial", "unfold"].includes(method)) fail("--method is slotted, stacked, radial or unfold");
|
|
312
|
+
if (!["outline", "solid", "ribs"].includes(fill)) fail("--fill is outline, solid or ribs");
|
|
313
|
+
if (values.size && values.height) fail("use --size or --height, not both");
|
|
314
|
+
const label = values.label ?? (values.printer === "hp6" ? "hp6" : "roll");
|
|
315
|
+
if (!LABELS[label]) fail(`--label is ${Object.keys(LABELS).join(", ")}`);
|
|
316
|
+
if (values.printer && values.printer !== LABELS[label].printer) fail(`--label ${label} is for the ${LABELS[label].printer} printer`);
|
|
317
|
+
const sizeMm = intOption(values.size ?? values.height, values.size ? "size" : "height", 10, 2000) ?? 120;
|
|
318
|
+
const blueprint = makeBlueprint(mesh, { method, fill, sizeMm, sizeBy: values.height ? "height" : "largest", penMm: 1.2, label });
|
|
319
|
+
const out = await save(values.out ?? "blueprint.json", JSON.stringify(blueprint.design, null, 2));
|
|
320
|
+
const [w, d, h] = blueprint.sizeMm.map(Math.round);
|
|
321
|
+
log(`${w} x ${d} x ${h} mm: ${blueprint.parts.length} pieces on ${blueprint.design.pages.length} labels (${label}), saved to ${out}`);
|
|
322
|
+
blueprint.assembly.forEach((s) => log(`${s.step}. ${s.text}${s.parts.length ? ` (${s.parts.join(", ")})` : ""}`));
|
|
323
|
+
if (values.preview) {
|
|
324
|
+
const pages = await renderPages(blueprint.design);
|
|
325
|
+
await savePreviews(pages, join(values.preview, "label.png"), log);
|
|
326
|
+
}
|
|
327
|
+
if (values.console) await showDesign(blueprint.design, values, log);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** `inkless console` in the foreground: serve until stopped. */
|
|
331
|
+
async function runConsole(input, values, log) {
|
|
332
|
+
const running = await findServer();
|
|
333
|
+
if (running) {
|
|
334
|
+
if (input) await showDesign(await designFor(input, { printer: values.printer }), values, log);
|
|
335
|
+
log(`console already running: http://127.0.0.1:${running.port}`);
|
|
336
|
+
if (!values["no-open"]) openBrowser(`http://127.0.0.1:${running.port}`);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
const printerId = getPrinter(values.printer).id;
|
|
340
|
+
const actions = printerActions({ address: values.address, name: values.name });
|
|
341
|
+
const server = await startConsoleServer({ port: intOption(values.port, "port", 0, 65535), printerId, ...actions });
|
|
342
|
+
if (input) {
|
|
343
|
+
const design = await designFor(input, { printer: printerId });
|
|
344
|
+
server.state.design = design;
|
|
345
|
+
server.state.printer.id = design.printer;
|
|
346
|
+
}
|
|
347
|
+
log(`inkless console: ${server.url} (Ctrl-C to stop)`);
|
|
348
|
+
if (!values["no-open"]) openBrowser(server.url);
|
|
349
|
+
await new Promise((done) => {
|
|
350
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, done);
|
|
351
|
+
});
|
|
352
|
+
await server.close();
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function consoleCommand(command, input, values, log) {
|
|
356
|
+
if (command === "console show") return showDesign(await designOf(input, values), values, log);
|
|
357
|
+
if (command === "console link") return log(await shareLink(await designOf(input, values), process.env.INKLESS_SITE || SITE_URL));
|
|
358
|
+
const { port, state, pid } = await requireServer();
|
|
359
|
+
if (command === "console say") {
|
|
360
|
+
await ask(port, "POST", "/api/messages", { from: "agent", text: input, agentName: values.as });
|
|
361
|
+
return log("sent");
|
|
362
|
+
}
|
|
363
|
+
if (command === "console get") {
|
|
364
|
+
if (!state.design) fail("the console has no design yet");
|
|
365
|
+
const text = JSON.stringify(state.design, null, 2);
|
|
366
|
+
return values.out ? log(`saved to ${await save(values.out, text)}`) : log(text);
|
|
367
|
+
}
|
|
368
|
+
if (command === "console stop") {
|
|
369
|
+
process.kill(pid, "SIGTERM");
|
|
370
|
+
return log("console stopped");
|
|
371
|
+
}
|
|
372
|
+
// wait: answer at once if the human has already approved, else long poll for the next change
|
|
373
|
+
const until = values.until ?? "approved";
|
|
374
|
+
if (!["approved", "any"].includes(until)) fail("--until is approved or any");
|
|
375
|
+
const seconds = intOption(values.timeout, "timeout", 1, 3600) ?? 600;
|
|
376
|
+
const since = intOption(values.since, "since", 0, 1e9) ?? (until === "approved" && ["approved", "printing", "printed", "error"].includes(state.status) ? 0 : state.rev);
|
|
377
|
+
const answer = await call(port, "GET", `/api/wait?since=${since}&until=${until}&timeout=${seconds}`, undefined, (seconds + 10) * 1000);
|
|
378
|
+
if (answer.status === 204) return 2;
|
|
379
|
+
const { event, rev, status, design, messages } = answer.body;
|
|
380
|
+
log(JSON.stringify({ event, rev, status, design, messages }));
|
|
381
|
+
return event === "error" ? 1 : 0;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async function formatsCommand(command, input, values, log) {
|
|
385
|
+
if (command === "formats save") {
|
|
386
|
+
const design = await readDesignFile(input);
|
|
387
|
+
if (!design) fail(`${input} is not a design file`);
|
|
388
|
+
const name = values.name ?? design.title;
|
|
389
|
+
if (!name) fail("formats save needs --name");
|
|
390
|
+
const format = await saveFormat(formatFromDesign(design, { name, description: values.description }));
|
|
391
|
+
return log(`saved ${format.id} with fields ${format.fields.map((f) => f.key).join(", ") || "(none)"}\nfill it with: inkless preview --format ${format.id} --set key=value`);
|
|
392
|
+
}
|
|
393
|
+
if (command === "formats show") {
|
|
394
|
+
const f = await findFormat(input);
|
|
395
|
+
if (values.json) return log(JSON.stringify(f, null, 2));
|
|
396
|
+
log(`${f.name} (${f.id}${f.saved ? ", saved" : ""}): ${f.size.widthMm}x${f.size.heightMm} mm, ${f.formFactor}, fits ${f.printers.join(", ")}`);
|
|
397
|
+
if (f.description) log(f.description);
|
|
398
|
+
log("\nfields:");
|
|
399
|
+
for (const field of f.fields) log(` ${field.key.padEnd(12)} ${field.label.padEnd(14)} e.g. ${JSON.stringify(field.example)}`);
|
|
400
|
+
const sets = f.fields.map((field) => `--set ${field.key}="${field.example.replace(/\n/g, "\\n")}"`).join(" ");
|
|
401
|
+
return log(`\ntry: inkless preview --format ${f.id} ${sets}`);
|
|
402
|
+
}
|
|
403
|
+
if (values.printer && !["pm290", "hp6"].includes(values.printer)) fail("--printer is pm290 or hp6");
|
|
404
|
+
const formats = [...listFormats(), ...(await savedFormats())].filter((f) => !values.printer || f.printers.includes(values.printer));
|
|
405
|
+
for (const f of formats) {
|
|
406
|
+
log(`${f.id.padEnd(18)} ${f.name.padEnd(18)} ${`${f.size.widthMm}x${f.size.heightMm} mm`.padEnd(10)} ${f.formFactor.padEnd(7)} ${f.printers.join(",").padEnd(10)} ${f.saved ? "saved " : ""}${f.fields.map((x) => x.key).join(" ")}`);
|
|
407
|
+
}
|
|
408
|
+
log("\ninkless formats show <id> for its fields; inkless preview --format <id> --set key=value to fill one");
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* @param {string[]} argv
|
|
413
|
+
* @returns {Promise<number | void>} an exit code when it is not 0
|
|
414
|
+
*/
|
|
415
|
+
export async function main(argv, { log = console.log } = {}) {
|
|
416
|
+
const { command, input, values } = parse(argv);
|
|
417
|
+
if (command === "help") return log(USAGE);
|
|
418
|
+
if (command === "printers") return listPrinters(log);
|
|
419
|
+
if (command === "check") {
|
|
420
|
+
const printer = getPrinter(values.printer);
|
|
421
|
+
await withPrinter(printer, values, log);
|
|
422
|
+
return log(`${printer.name} answered its ${printer.handshakeName}; nothing printed`);
|
|
423
|
+
}
|
|
424
|
+
if (command === "print" || command === "preview") return printOrPreview(command, input, values, log);
|
|
425
|
+
if (command === "blueprint") return runBlueprint(input, values, log);
|
|
426
|
+
if (command === "console") return runConsole(input, values, log);
|
|
427
|
+
if (command.startsWith("formats")) return formatsCommand(command, input, values, log);
|
|
428
|
+
if (command.startsWith("skill")) return manageSkill(/** @type {"install" | "uninstall"} */ (command.split(" ")[1]), { agent: values.agent, dest: values.dest, log });
|
|
429
|
+
return consoleCommand(command, input, values, log);
|
|
430
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// What the console server does with a real printer: print a design, check the link.
|
|
3
|
+
import { getPrinter } from "../../core/printers/index.js";
|
|
4
|
+
import { runSession } from "../../core/session.js";
|
|
5
|
+
import { printPages, renderPages } from "../design.js";
|
|
6
|
+
import { openTransport as realTransport } from "../transports/index.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {{ openTransport?: typeof realTransport, render?: typeof renderPages, address?: string, name?: string }} [options]
|
|
10
|
+
* openTransport and render can be swapped for fakes in tests.
|
|
11
|
+
*/
|
|
12
|
+
export function printerActions({ openTransport = realTransport, render = renderPages, address, name } = {}) {
|
|
13
|
+
return {
|
|
14
|
+
async print(design) {
|
|
15
|
+
const pages = await render(design);
|
|
16
|
+
const count = await printPages(design, pages, { openTransport, address, name });
|
|
17
|
+
return `Printed ${count} ${count === 1 ? "label" : "labels"}`;
|
|
18
|
+
},
|
|
19
|
+
async check({ printer: id, address: given }) {
|
|
20
|
+
const printer = getPrinter(id);
|
|
21
|
+
const transport = await openTransport({ printer, address: given ?? address, name });
|
|
22
|
+
try {
|
|
23
|
+
await runSession({ transport, printer });
|
|
24
|
+
} finally {
|
|
25
|
+
await transport.close();
|
|
26
|
+
}
|
|
27
|
+
return `${printer.name} answered its ${printer.handshakeName}`;
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The agent side of the console: find the running server and talk to it.
|
|
3
|
+
import { request } from "node:http";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { infoFile } from "./paths.js";
|
|
8
|
+
|
|
9
|
+
const BIN = fileURLToPath(new URL("../../../bin/inkless.js", import.meta.url));
|
|
10
|
+
|
|
11
|
+
/** One JSON call. Resolves { status, body }; a long poll can pass a long timeout. */
|
|
12
|
+
export function call(port, method, path, body, timeoutMs = 10000) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
15
|
+
const req = request({ host: "127.0.0.1", port, method, path, timeout: timeoutMs, headers: payload ? { "content-type": "application/json", "content-length": Buffer.byteLength(payload) } : {} }, (res) => {
|
|
16
|
+
const chunks = [];
|
|
17
|
+
res.on("data", (c) => chunks.push(c));
|
|
18
|
+
res.on("end", () => {
|
|
19
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
20
|
+
resolve({ status: res.statusCode ?? 0, body: text ? JSON.parse(text) : null });
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
req.on("timeout", () => req.destroy(new Error("the console server did not answer")));
|
|
24
|
+
req.on("error", reject);
|
|
25
|
+
req.end(payload);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The running server as { port, state }, or null. */
|
|
30
|
+
export async function findServer() {
|
|
31
|
+
const info = await readFile(infoFile(), "utf8").then(JSON.parse, () => null);
|
|
32
|
+
if (!info?.port) return null;
|
|
33
|
+
const state = await call(info.port, "GET", "/api/state", undefined, 2000).then((r) => r.body, () => null);
|
|
34
|
+
return state ? { ...info, state } : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function requireServer() {
|
|
38
|
+
const server = await findServer();
|
|
39
|
+
if (!server) throw new Error("no console is running; start one with: inkless console show <design.json>");
|
|
40
|
+
return server;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Ask the server for something and fail with its message if it refuses. */
|
|
44
|
+
export async function ask(port, method, path, body) {
|
|
45
|
+
const { status, body: answer } = await call(port, method, path, body);
|
|
46
|
+
if (status >= 400) throw new Error(answer?.error ?? `console server answered ${status}`);
|
|
47
|
+
return answer;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Start a console in the background and wait until it answers. */
|
|
51
|
+
export async function startBackground({ noOpen, port, printer, address, name }) {
|
|
52
|
+
const args = [BIN, "console"];
|
|
53
|
+
if (noOpen) args.push("--no-open");
|
|
54
|
+
for (const [flag, value] of [["--port", port], ["--printer", printer], ["--address", address], ["--name", name]]) if (value) args.push(flag, String(value));
|
|
55
|
+
spawn(process.execPath, args, { detached: true, stdio: "ignore" }).unref();
|
|
56
|
+
for (let i = 0; i < 80; i++) {
|
|
57
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
58
|
+
const server = await findServer();
|
|
59
|
+
if (server) return server;
|
|
60
|
+
}
|
|
61
|
+
throw new Error("the console server did not start");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Open a page in the default browser; failures are not worth stopping for. */
|
|
65
|
+
export function openBrowser(url) {
|
|
66
|
+
const [cmd, ...args] = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
|
|
67
|
+
spawn(cmd, args, { detached: true, stdio: "ignore" }).on("error", () => {}).unref();
|
|
68
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Where the console keeps its state, and where a running one is announced.
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
export const inklessHome = () => join(homedir(), ".inkless");
|
|
7
|
+
export const infoFile = () => join(inklessHome(), "console.json");
|
|
8
|
+
export const stateDir = () => join(inklessHome(), "console");
|