@aivax/cli 0.0.0-stage → 1.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/src/input.js ADDED
@@ -0,0 +1,120 @@
1
+ import { openAsBlob } from "node:fs";
2
+ import { basename, extname } from "node:path";
3
+ import { text } from "node:stream/consumers";
4
+ import mime from "mime";
5
+ import { UsageError } from "./errors.js";
6
+
7
+ export const isUrl = value => /^https?:\/\//i.test(value);
8
+
9
+ const fileType = path => mime.getType(path) ?? "application/octet-stream";
10
+
11
+ export async function openFile(path) {
12
+ try {
13
+ return await openAsBlob(path, { type: fileType(path) });
14
+ }
15
+ catch {
16
+ throw new UsageError(`File not found: ${path}`);
17
+ }
18
+ }
19
+
20
+ export async function readSource(value) {
21
+ if (value === "-" || value === "@-") {
22
+ return await text(process.stdin);
23
+ }
24
+
25
+ if (value.startsWith("@")) {
26
+ return await (await openFile(value.slice(1))).text();
27
+ }
28
+
29
+ return value;
30
+ }
31
+
32
+ export async function readJson(value, flag = "--data") {
33
+ const text = await readSource(value);
34
+
35
+ try {
36
+ return JSON.parse(text);
37
+ }
38
+ catch (error) {
39
+ throw new UsageError(`${flag} is not valid JSON: ${error.message}`);
40
+ }
41
+ }
42
+
43
+ export async function payload(ctx, fields = {}) {
44
+ const data = ctx.options.data === undefined ? {} : await readJson(ctx.options.data);
45
+ const defined = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
46
+
47
+ return Object.keys(defined).length ? { ...data, ...defined } : data;
48
+ }
49
+
50
+ export async function base64(path) {
51
+ const file = await openFile(path);
52
+ return Buffer.from(await file.arrayBuffer()).toString("base64");
53
+ }
54
+
55
+ export async function dataUrl(path) {
56
+ const file = await openFile(path);
57
+ return `data:${file.type};base64,${await base64(path)}`;
58
+ }
59
+
60
+ export async function contentPart(source) {
61
+ const remote = isUrl(source);
62
+ const type = fileType(remote ? new URL(source).pathname : source);
63
+ const kind = type.split("/")[0];
64
+ const url = remote ? source : await dataUrl(source);
65
+
66
+ if (kind === "image") {
67
+ return { type: "image_url", image_url: { url } };
68
+ }
69
+
70
+ if (kind === "video") {
71
+ return { type: "video_url", video_url: { url } };
72
+ }
73
+
74
+ if (kind === "audio" && !remote) {
75
+ return { type: "input_audio", input_audio: { data: await base64(source), format: extname(source).slice(1).toLowerCase() } };
76
+ }
77
+
78
+ if (kind === "text" && !remote) {
79
+ return { type: "text", text: await (await openFile(source)).text() };
80
+ }
81
+
82
+ return { type: "file", file: { filename: basename(remote ? new URL(source).pathname : source), file_data: url } };
83
+ }
84
+
85
+ export async function documentParts(ctx) {
86
+ const parts = [
87
+ ...await Promise.all((ctx.options.file ?? []).map(contentPart)),
88
+ ...(ctx.options.text ?? []).map(text => ({ type: "text", text }))
89
+ ];
90
+
91
+ if (!parts.length) {
92
+ throw new UsageError("Provide at least one document with -f <file|url> or --text <text>.");
93
+ }
94
+
95
+ return parts;
96
+ }
97
+
98
+ export async function textDocuments(ctx) {
99
+ const documents = [
100
+ ...await Promise.all((ctx.options.file ?? []).map(async path => (await openFile(path)).text())),
101
+ ...(ctx.options.document ?? [])
102
+ ];
103
+
104
+ if (!documents.length) {
105
+ throw new UsageError("Provide at least one document with -f <file> or --document <text>.");
106
+ }
107
+
108
+ return documents;
109
+ }
110
+
111
+ export const fileOption = description => ({ alias: "f", value: "<file>", list: true, description });
112
+
113
+ export const textOption = { value: "<text>", list: true, description: "Inline text document. Repeatable." };
114
+
115
+ export const dataOption = (required = false) => ({
116
+ alias: "d",
117
+ value: "<json>",
118
+ required,
119
+ description: "JSON request body, @file to read it from a file, or - for stdin."
120
+ });
package/src/pdf.js ADDED
@@ -0,0 +1,209 @@
1
+ import { crc32, deflateSync, inflateSync } from "node:zlib";
2
+ import { PDFArray, PDFBool, PDFDict, PDFDocument, PDFName, PDFNumber, PDFRawStream, decodePDFRawStream } from "@cantoo/pdf-lib";
3
+ import sharp from "sharp";
4
+
5
+ const MIN_IMAGE_BYTES = 64 * 1024;
6
+ const MAX_IMAGE_SIDE = 2400;
7
+ const JPEG_QUALITY = 75;
8
+ const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
9
+
10
+ const name = PDFName.of;
11
+ const latin1 = new TextDecoder("latin1");
12
+ const prunedGroups = new Set(["XObject", "Font", "ExtGState", "Pattern", "Shading", "ColorSpace", "Properties"].map(name));
13
+
14
+ const numberOf = (dict, key, fallback) => {
15
+ const value = dict?.lookup(name(key));
16
+ return value instanceof PDFNumber ? value.asNumber() : fallback;
17
+ };
18
+
19
+ function pngChunk(type, data) {
20
+ const chunk = Buffer.alloc(data.length + 12);
21
+ chunk.writeUInt32BE(data.length);
22
+ chunk.write(type, 4, "latin1");
23
+ chunk.set(data, 8);
24
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, data.length + 8)), data.length + 8);
25
+
26
+ return chunk;
27
+ }
28
+
29
+ function colorComponents(dict) {
30
+ const space = dict.lookup(name("ColorSpace"));
31
+
32
+ if (space === name("DeviceRGB")) return 3;
33
+ if (space === name("DeviceGray")) return 1;
34
+
35
+ if (space instanceof PDFArray && space.lookup(0) === name("ICCBased")) {
36
+ const components = numberOf(space.lookup(1)?.dict, "N", 0);
37
+ return components === 1 || components === 3 ? components : null;
38
+ }
39
+
40
+ return null;
41
+ }
42
+
43
+ // Returns the image as JPEG or PNG bytes that sharp can decode, or null when it is not supported.
44
+ function encodedImage(dict, contents) {
45
+ const filters = dict.lookup(name("Filter"));
46
+ const filter = filters instanceof PDFArray ? (filters.size() === 1 ? filters.lookup(0) : null) : filters;
47
+ const components = colorComponents(dict);
48
+
49
+ if (!components || dict.has(name("Decode")) || filter === null) {
50
+ return null;
51
+ }
52
+
53
+ if (filter === name("DCTDecode")) {
54
+ return contents;
55
+ }
56
+
57
+ if ((filter && filter !== name("FlateDecode")) || numberOf(dict, "BitsPerComponent", 0) !== 8) {
58
+ return null;
59
+ }
60
+
61
+ const width = numberOf(dict, "Width", 0);
62
+ const height = numberOf(dict, "Height", 0);
63
+ const rowBytes = width * components;
64
+ const parms = dict.lookup(name("DecodeParms"));
65
+ const params = parms instanceof PDFArray ? parms.lookup(0) : parms;
66
+ const predictor = numberOf(params, "Predictor", 1);
67
+ let idat;
68
+
69
+ if (filter && predictor >= 10) {
70
+ // PNG predictors: the Flate data already is a PNG IDAT stream.
71
+ const matches = numberOf(params, "Colors", 1) === components
72
+ && numberOf(params, "BitsPerComponent", 8) === 8
73
+ && numberOf(params, "Columns", 1) === width;
74
+
75
+ if (!matches) return null;
76
+ idat = contents;
77
+ }
78
+ else if (predictor === 1) {
79
+ const pixels = filter ? inflateSync(contents) : contents;
80
+ if (pixels.length < rowBytes * height) return null;
81
+
82
+ const rows = Buffer.alloc((rowBytes + 1) * height);
83
+ for (let row = 0; row < height; row++) {
84
+ rows.set(pixels.subarray(row * rowBytes, (row + 1) * rowBytes), row * (rowBytes + 1) + 1);
85
+ }
86
+
87
+ idat = deflateSync(rows, { level: 1 });
88
+ }
89
+ else {
90
+ return null;
91
+ }
92
+
93
+ const header = Buffer.alloc(13);
94
+ header.writeUInt32BE(width);
95
+ header.writeUInt32BE(height, 4);
96
+ header[8] = 8;
97
+ header[9] = components === 3 ? 2 : 0;
98
+
99
+ return Buffer.concat([PNG_SIGNATURE, pngChunk("IHDR", header), pngChunk("IDAT", idat), pngChunk("IEND", new Uint8Array())]);
100
+ }
101
+
102
+ export async function openPdf(data) {
103
+ try {
104
+ return await PDFDocument.load(data, { password: "", updateMetadata: false });
105
+ }
106
+ catch (error) {
107
+ throw new Error(/password/i.test(error.message)
108
+ ? "Password-protected PDFs are not supported."
109
+ : `The file is not a valid PDF document (${error.message}).`);
110
+ }
111
+ }
112
+
113
+ export async function compressImages(doc) {
114
+ let images = 0;
115
+ let saved = 0;
116
+
117
+ for (const [, object] of doc.context.enumerateIndirectObjects()) {
118
+ if (!(object instanceof PDFRawStream) || object.dict.lookup(name("Subtype")) !== name("Image")) {
119
+ continue;
120
+ }
121
+
122
+ const { dict, contents } = object;
123
+
124
+ if (contents.length < MIN_IMAGE_BYTES || dict.lookup(name("ImageMask")) === PDFBool.True) {
125
+ continue;
126
+ }
127
+
128
+ try {
129
+ const source = encodedImage(dict, contents);
130
+ if (!source) continue;
131
+
132
+ const { data: jpeg, info: image } = await sharp(source)
133
+ .resize(MAX_IMAGE_SIDE, MAX_IMAGE_SIDE, { fit: "inside", withoutEnlargement: true })
134
+ .jpeg({ quality: JPEG_QUALITY })
135
+ .toBuffer({ resolveWithObject: true });
136
+
137
+ if (jpeg.length >= contents.length * 0.8) continue;
138
+
139
+ saved += contents.length - jpeg.length;
140
+ object.updateContents(jpeg);
141
+ dict.set(name("Filter"), name("DCTDecode"));
142
+ dict.set(name("ColorSpace"), name("DeviceRGB"));
143
+ dict.set(name("Width"), PDFNumber.of(image.width));
144
+ dict.set(name("Height"), PDFNumber.of(image.height));
145
+ dict.set(name("BitsPerComponent"), PDFNumber.of(8));
146
+ dict.delete(name("DecodeParms"));
147
+ images++;
148
+ }
149
+ catch {
150
+ continue;
151
+ }
152
+ }
153
+
154
+ return { images, saved };
155
+ }
156
+
157
+ export async function splitPages(doc, onProgress) {
158
+ const total = doc.getPageCount();
159
+ const pages = [];
160
+
161
+ for (let index = 0; index < total; index++) {
162
+ const leaf = doc.getPage(index).node;
163
+ const ownResources = leaf.get(name("Resources"));
164
+
165
+ try {
166
+ // Keep only the resources the page content uses, so pages of documents that share one
167
+ // resource dictionary across all pages do not carry every image and font of the file.
168
+ try {
169
+ const contents = leaf.Contents();
170
+ const streams = contents instanceof PDFArray ? contents.asArray().map(ref => doc.context.lookup(ref)) : [contents];
171
+ const used = new Set(streams.map(stream => latin1.decode(decodePDFRawStream(stream).decode())).join("\n").match(/\/[^\s/[\]()<>{}%]+/g));
172
+ const resources = leaf.Resources();
173
+ const pruned = doc.context.obj({});
174
+
175
+ for (const [key, value] of resources?.entries() ?? []) {
176
+ const group = prunedGroups.has(key) ? resources.lookup(key) : null;
177
+
178
+ if (!(group instanceof PDFDict)) {
179
+ pruned.set(key, value);
180
+ continue;
181
+ }
182
+
183
+ const kept = doc.context.obj({});
184
+ group.entries().filter(([entry]) => used.has(entry.asString())).forEach(([entry, ref]) => kept.set(entry, ref));
185
+ pruned.set(key, kept);
186
+ }
187
+
188
+ if (resources) leaf.set(name("Resources"), pruned);
189
+ }
190
+ catch { }
191
+
192
+ const single = await PDFDocument.create({ updateMetadata: false });
193
+ const [page] = await single.copyPages(doc, [index]);
194
+ single.addPage(page);
195
+ pages.push({ page: index + 1, bytes: await single.save({ useObjectStreams: true }), error: null });
196
+ }
197
+ catch (error) {
198
+ pages.push({ page: index + 1, bytes: null, error: `Split failed: ${error.message}` });
199
+ }
200
+ finally {
201
+ if (ownResources) leaf.set(name("Resources"), ownResources);
202
+ else leaf.delete(name("Resources"));
203
+ }
204
+
205
+ onProgress(index + 1, total);
206
+ }
207
+
208
+ return pages;
209
+ }
@@ -0,0 +1,67 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { Entry } from "@napi-rs/keyring";
5
+ import { UsageError } from "./errors.js";
6
+
7
+ const SERVICE = "aivax-cli";
8
+
9
+ const configHome = process.platform === "win32"
10
+ ? process.env.APPDATA ?? join(homedir(), "AppData", "Roaming")
11
+ : process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
12
+
13
+ const profilesFile = join(process.env.AIVAX_CLI_HOME ?? join(configHome, "aivax-cli"), "profiles.json");
14
+
15
+ export const defaultEndpoint = () => process.env.AIVAX_ENDPOINT ?? "https://inference.aivax.net";
16
+
17
+ export async function loadProfiles() {
18
+ try {
19
+ return JSON.parse(await readFile(profilesFile, "utf8"));
20
+ }
21
+ catch (error) {
22
+ if (error.code === "ENOENT") return { default: null, profiles: {} };
23
+ throw error;
24
+ }
25
+ }
26
+
27
+ export async function saveProfiles(data) {
28
+ await mkdir(dirname(profilesFile), { recursive: true });
29
+ await writeFile(profilesFile, JSON.stringify(data, null, 4));
30
+ }
31
+
32
+ export const slugify = text => text
33
+ .normalize("NFD")
34
+ .replace(/[\u0300-\u036f]/g, "")
35
+ .toLowerCase()
36
+ .replace(/[^a-z0-9]+/g, "-")
37
+ .replace(/^-+|-+$/g, "");
38
+
39
+ export function findProfile(data, name) {
40
+ if (!name || !data.profiles[name]) {
41
+ throw new UsageError(name
42
+ ? `Profile "${name}" not found. Run "aivax auth profiles" to list the saved profiles.`
43
+ : "No account profile found. Run \"aivax auth login\" first.");
44
+ }
45
+
46
+ return name;
47
+ }
48
+
49
+ export const storeToken = (name, value) => new Entry(SERVICE, name).setPassword(value);
50
+
51
+ export const deleteToken = name => new Entry(SERVICE, name).deletePassword();
52
+
53
+ export async function resolveSession(ctx) {
54
+ if (process.env.AIVAX_API_KEY && !ctx.options.profile) {
55
+ return { token: process.env.AIVAX_API_KEY, endpoint: defaultEndpoint() };
56
+ }
57
+
58
+ const data = await loadProfiles();
59
+ const name = findProfile(data, ctx.options.profile ?? data.default);
60
+ const profile = data.profiles[name];
61
+ const token = new Entry(SERVICE, name).getPassword();
62
+ if (!token) {
63
+ throw new UsageError(`The access key of profile "${name}" is missing from the system credential store. Run "aivax auth login" again.`);
64
+ }
65
+
66
+ return { name, token, endpoint: process.env.AIVAX_ENDPOINT ?? profile.endpoint };
67
+ }
package/src/prompt.js ADDED
@@ -0,0 +1,67 @@
1
+ import { UsageError } from "./errors.js";
2
+
3
+ export function ask(question, { hidden = false } = {}) {
4
+ if (!process.stdin.isTTY) {
5
+ throw new UsageError(`"${question.trim()}" requires an interactive terminal. Provide the value through its flag.`);
6
+ }
7
+
8
+ process.stderr.write(question);
9
+
10
+ return new Promise(resolve => {
11
+ const stdin = process.stdin;
12
+ let value = "";
13
+
14
+ const finish = () => {
15
+ stdin.setRawMode(false);
16
+ stdin.pause();
17
+ stdin.off("data", onData);
18
+ process.stderr.write("\n");
19
+ };
20
+
21
+ const onData = chunk => {
22
+ for (const char of chunk) {
23
+ if (char === "\r" || char === "\n") {
24
+ finish();
25
+ resolve(value.trim());
26
+ return;
27
+ }
28
+
29
+ if (char === "\u0003") {
30
+ finish();
31
+ process.exit(130);
32
+ }
33
+
34
+ if (char === "\u007f" || char === "\b") {
35
+ if (value) {
36
+ value = value.slice(0, -1);
37
+ if (!hidden) process.stderr.write("\b \b");
38
+ }
39
+ continue;
40
+ }
41
+
42
+ value += char;
43
+ if (!hidden) process.stderr.write(char);
44
+ }
45
+ };
46
+
47
+ stdin.setRawMode(true);
48
+ stdin.setEncoding("utf8");
49
+ stdin.on("data", onData);
50
+ stdin.resume();
51
+ });
52
+ }
53
+
54
+ export async function confirm(ctx, message) {
55
+ if (ctx.options.yes) {
56
+ return;
57
+ }
58
+
59
+ if (!process.stdin.isTTY) {
60
+ throw new UsageError(`${message} Pass --yes to confirm in non-interactive sessions.`);
61
+ }
62
+
63
+ const answer = await ask(`${message} [y/N] `);
64
+ if (!/^y(es)?$/i.test(answer)) {
65
+ throw new UsageError("Operation cancelled.");
66
+ }
67
+ }