nanoodle 0.2.0 → 0.5.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/README.md +68 -9
- package/bin/nanoodle.mjs +33 -5
- package/package.json +5 -1
- package/src/browser.mjs +38 -0
- package/src/catalog.mjs +22 -0
- package/src/client.mjs +116 -17
- package/src/graph.mjs +25 -9
- package/src/index.mjs +7 -2
- package/src/io.mjs +42 -2
- package/src/local-media.mjs +998 -0
- package/src/media.mjs +68 -16
- package/src/mp4cat.mjs +284 -0
- package/src/nodes.mjs +262 -37
- package/src/qr.mjs +385 -0
- package/src/share.mjs +20 -14
- package/src/workflow.mjs +102 -18
- package/src/x402.mjs +77 -0
- package/src/zlib.mjs +44 -0
package/src/workflow.mjs
CHANGED
|
@@ -1,14 +1,42 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
2
1
|
import { NanoodleError, RunError, UnsupportedNodeError } from "./errors.mjs";
|
|
3
|
-
import { NODE_TYPES, displayName, isInputPort, materialize, topoSort } from "./graph.mjs";
|
|
2
|
+
import { NODE_TYPES, displayName, isInputPort, materialize, topoSort, wiredFramesFloor, MAX_FRAMES } from "./graph.mjs";
|
|
4
3
|
import { deriveInputs, deriveOutputs, deriveSettings, resolveInputKey, resolveSettingKey } from "./io.mjs";
|
|
5
4
|
import { NanoClient } from "./client.mjs";
|
|
6
5
|
import { MediaRef, coerceMediaInput } from "./media.mjs";
|
|
7
|
-
import { RUNNERS
|
|
6
|
+
import { RUNNERS } from "./nodes.mjs";
|
|
8
7
|
import { decodeShareUrl, isShareRef } from "./share.mjs";
|
|
9
8
|
|
|
9
|
+
/** Env / process access — safe when `process` is missing (browsers, some workers). */
|
|
10
|
+
function envApiKey() {
|
|
11
|
+
try {
|
|
12
|
+
return typeof process !== "undefined" && process.env ? process.env.NANOGPT_API_KEY : undefined;
|
|
13
|
+
} catch {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function warnGraph(msg) {
|
|
19
|
+
try {
|
|
20
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
21
|
+
process.emitWarning(msg, { code: "NANOODLE_GRAPH" });
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
} catch { /* ignore */ }
|
|
25
|
+
if (typeof console !== "undefined" && console.warn) console.warn("[nanoodle]", msg);
|
|
26
|
+
}
|
|
27
|
+
|
|
10
28
|
const MEDIA_KINDS = new Set(["image", "audio", "video", "inpaint"]);
|
|
11
29
|
|
|
30
|
+
function abortReason(signal) {
|
|
31
|
+
const r = signal && signal.reason;
|
|
32
|
+
if (r instanceof Error) return r;
|
|
33
|
+
return new NanoodleError(r != null ? String(r) : "run aborted", { code: "aborted" });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function throwIfAborted(signal) {
|
|
37
|
+
if (signal && signal.aborted) throw abortReason(signal);
|
|
38
|
+
}
|
|
39
|
+
|
|
12
40
|
/** The outcome of Workflow.run(). Media values are MediaRef; text values plain strings. */
|
|
13
41
|
export class RunResult {
|
|
14
42
|
constructor({ outputs, nodes, errors, costUsd, costExact, remainingBalance }) {
|
|
@@ -47,19 +75,24 @@ function isPlainObject(v) {
|
|
|
47
75
|
export class Workflow {
|
|
48
76
|
/**
|
|
49
77
|
* @param {object} graphData parsed noodle-graph.json
|
|
50
|
-
* @param {{ apiKey?, baseUrl?, fetch?, pollIntervals?, timeouts?, quiet? }} [opts]
|
|
78
|
+
* @param {{ apiKey?, payment?, baseUrl?, fetch?, pollIntervals?, timeouts?, quiet?, catalog? }} [opts]
|
|
79
|
+
* catalog: opt-in raw model-catalog arrays ({ chat, image, video, audio }) enabling
|
|
80
|
+
* the same payload gates play RUNTIME_JS applies (see src/catalog.mjs) — data only,
|
|
81
|
+
* never fetched by the library
|
|
51
82
|
*/
|
|
52
83
|
constructor(graphData, opts = {}) {
|
|
53
84
|
const { nodes, links, warnings } = materialize(graphData);
|
|
54
85
|
this.graph = { nodes, links };
|
|
86
|
+
this.catalog = opts.catalog || null;
|
|
55
87
|
/** Load-time warnings (unknown / unsupported node types). load() only warns; run() fails fast. */
|
|
56
88
|
this.warnings = warnings;
|
|
57
89
|
this.client = new NanoClient({
|
|
58
|
-
apiKey: opts.apiKey !== undefined ? opts.apiKey :
|
|
90
|
+
apiKey: opts.apiKey !== undefined ? opts.apiKey : envApiKey(),
|
|
59
91
|
baseUrl: opts.baseUrl,
|
|
60
92
|
fetch: opts.fetch,
|
|
61
93
|
pollIntervals: opts.pollIntervals,
|
|
62
94
|
timeouts: opts.timeouts,
|
|
95
|
+
payment: opts.payment, // accountless x402: a callback that sends the Nano invoice (never a seed)
|
|
63
96
|
});
|
|
64
97
|
/** [{ key, nodeId, field, kind, label, optional, def, options? }] */
|
|
65
98
|
this.inputs = deriveInputs(this.graph);
|
|
@@ -68,7 +101,7 @@ export class Workflow {
|
|
|
68
101
|
/** [{ key, nodeId, field, kind, def, options? }] */
|
|
69
102
|
this.settings = deriveSettings(this.graph);
|
|
70
103
|
if (warnings.length && !opts.quiet) {
|
|
71
|
-
for (const w of warnings)
|
|
104
|
+
for (const w of warnings) warnGraph(w);
|
|
72
105
|
}
|
|
73
106
|
}
|
|
74
107
|
|
|
@@ -78,12 +111,19 @@ export class Workflow {
|
|
|
78
111
|
* short link) or a bare #g=/#j=/#a= fragment. Direct fragment links decode
|
|
79
112
|
* offline; only fragment-less short links touch the network (redirect-header
|
|
80
113
|
* reads, no credentials attached).
|
|
114
|
+
*
|
|
115
|
+
* File paths use Node's `fs` (dynamic import). In browsers, pass a parsed
|
|
116
|
+
* object / JSON string to `Workflow.fromJSON`, or a share URL/fragment.
|
|
81
117
|
*/
|
|
82
118
|
static async load(src, opts = {}) {
|
|
83
119
|
if (isShareRef(src)) {
|
|
84
120
|
const { graph } = await decodeShareUrl(src, { fetch: opts.fetch });
|
|
85
121
|
return new Workflow(graph, opts);
|
|
86
122
|
}
|
|
123
|
+
if (typeof src === "string" && /^\s*[\[{]/.test(src)) {
|
|
124
|
+
return Workflow.fromJSON(src, opts);
|
|
125
|
+
}
|
|
126
|
+
const { readFile } = await import("node:fs/promises");
|
|
87
127
|
return Workflow.fromJSON(await readFile(src, "utf8"), opts);
|
|
88
128
|
}
|
|
89
129
|
|
|
@@ -97,11 +137,14 @@ export class Workflow {
|
|
|
97
137
|
* Execute the whole graph.
|
|
98
138
|
* @param {object|string|Uint8Array|MediaRef} inputs friendly-keyed values, or a bare scalar
|
|
99
139
|
* when the workflow has exactly one required input
|
|
100
|
-
* @param {{ settings?, timeoutMs?, signal?, onProgress? }} [runOpts]
|
|
140
|
+
* @param {{ settings?, defaults?, timeoutMs?, signal?, onProgress? }} [runOpts]
|
|
141
|
+
* defaults: false treats graph fields as authoritative — no def backfill for
|
|
142
|
+
* unsupplied inputs (the play UI materializes defs into fields itself, so a
|
|
143
|
+
* deliberately blank field must stay blank when it delegates to this engine)
|
|
101
144
|
* @returns {Promise<RunResult>} rejects with RunError (carrying .result) when a sink failed
|
|
102
145
|
*/
|
|
103
146
|
async run(inputs = {}, runOpts = {}) {
|
|
104
|
-
const { settings = {}, timeoutMs, signal, onProgress } = runOpts;
|
|
147
|
+
const { settings = {}, defaults = true, timeoutMs, signal, onProgress } = runOpts;
|
|
105
148
|
const graph = this.graph;
|
|
106
149
|
|
|
107
150
|
// bare scalar → the single required input
|
|
@@ -127,18 +170,22 @@ export class Workflow {
|
|
|
127
170
|
settingAssignments.push({ entry, value });
|
|
128
171
|
}
|
|
129
172
|
|
|
130
|
-
//
|
|
173
|
+
// unknown node types fail fast — before any network call
|
|
131
174
|
for (const n of graph.nodes) {
|
|
132
175
|
if (n.unknown) {
|
|
133
176
|
throw new UnsupportedNodeError(
|
|
134
177
|
`node ${n.id}: unknown node type '${n.type}' — this graph needs a newer nanoodle library`,
|
|
135
178
|
{ nodeId: n.id, nodeType: n.type });
|
|
136
179
|
}
|
|
137
|
-
if (NODE_TYPES[n.type].unsupported) throw unsupportedNodeError(n);
|
|
138
180
|
}
|
|
139
181
|
|
|
140
182
|
const order = topoSort(graph); // throws naming cyclic nodes
|
|
141
183
|
|
|
184
|
+
// Local-only graphs never POST media — skip the ~4 MB inline cap on inputs.
|
|
185
|
+
// Mixed/network graphs keep the cap so we fail before spending on an oversize body.
|
|
186
|
+
const hasNetwork = graph.nodes.some((n) => NODE_TYPES[n.type] && NODE_TYPES[n.type].network);
|
|
187
|
+
const mediaCoerceOpts = { enforceInlineMax: hasNetwork };
|
|
188
|
+
|
|
142
189
|
// effective fields: graph fields + settings overrides + user inputs
|
|
143
190
|
const effFields = new Map(graph.nodes.map((n) => [n.id, { ...n.fields }]));
|
|
144
191
|
for (const { entry, value } of settingAssignments) {
|
|
@@ -146,9 +193,18 @@ export class Workflow {
|
|
|
146
193
|
}
|
|
147
194
|
const explicit = new Set();
|
|
148
195
|
for (const { entry, value } of inputAssignments) {
|
|
149
|
-
effFields.get(entry.nodeId)[entry.field] = this._coerceInput(entry, value);
|
|
196
|
+
effFields.get(entry.nodeId)[entry.field] = this._coerceInput(entry, value, mediaCoerceOpts);
|
|
150
197
|
explicit.add(entry);
|
|
151
198
|
}
|
|
199
|
+
// vframes: raise frames to highest wired frameK (play.html wiredFramesFloor) so a
|
|
200
|
+
// persisted frames=1 with frame3 wired doesn't starve the consumer after paid upstream.
|
|
201
|
+
for (const n of graph.nodes) {
|
|
202
|
+
if (n.type !== "vframes") continue;
|
|
203
|
+
const fields = effFields.get(n.id);
|
|
204
|
+
const floor = wiredFramesFloor(graph, n.id);
|
|
205
|
+
const cur = Math.max(1, Math.min(MAX_FRAMES, parseInt(fields.frames, 10) || 1));
|
|
206
|
+
if (floor > cur) fields.frames = String(floor);
|
|
207
|
+
}
|
|
152
208
|
// defaults + required check
|
|
153
209
|
for (const entry of this.inputs) {
|
|
154
210
|
const fields = effFields.get(entry.nodeId);
|
|
@@ -156,17 +212,17 @@ export class Workflow {
|
|
|
156
212
|
if (v == null || String(v).trim() === "") {
|
|
157
213
|
// an EXPLICIT empty value clears an optional input (e.g. run with no system prompt) —
|
|
158
214
|
// the def only backfills when the key wasn't supplied at all (the app's prefilled textarea)
|
|
159
|
-
if (entry.optional && explicit.has(entry)) continue;
|
|
160
|
-
if (entry.def != null && String(entry.def) !== "") fields[entry.field] = entry.def;
|
|
215
|
+
if (entry.optional && (explicit.has(entry) || !defaults)) continue;
|
|
216
|
+
if (defaults && entry.def != null && String(entry.def) !== "") fields[entry.field] = entry.def;
|
|
161
217
|
else if (!entry.optional) {
|
|
162
218
|
throw new NanoodleError(`missing required input "${entry.key}" (${entry.nodeId}.${entry.field})`);
|
|
163
219
|
}
|
|
164
220
|
}
|
|
165
221
|
}
|
|
166
222
|
|
|
167
|
-
// API key required only when the graph actually calls NanoGPT
|
|
168
|
-
if (!this.client.apiKey &&
|
|
169
|
-
throw new NanoodleError("no API key — pass { apiKey } to Workflow.load/fromJSON
|
|
223
|
+
// API key (or an x402 payment callback) required only when the graph actually calls NanoGPT
|
|
224
|
+
if (!this.client.apiKey && !this.client.payment && hasNetwork) {
|
|
225
|
+
throw new NanoodleError("no API key — pass { apiKey } to Workflow.load/fromJSON, set NANOGPT_API_KEY, or pass { payment } for accountless x402 runs (this workflow calls the NanoGPT API)");
|
|
170
226
|
}
|
|
171
227
|
|
|
172
228
|
// ---- execution ----
|
|
@@ -187,6 +243,7 @@ export class Workflow {
|
|
|
187
243
|
const cost = { total: 0, exact: true, balance: null };
|
|
188
244
|
const byId = new Map(graph.nodes.map((n) => [n.id, n]));
|
|
189
245
|
const promises = new Map();
|
|
246
|
+
const mediaFetch = this.client.fetch;
|
|
190
247
|
|
|
191
248
|
const ctxFor = (node, rec) => {
|
|
192
249
|
const onCost = (c) => {
|
|
@@ -205,12 +262,18 @@ export class Workflow {
|
|
|
205
262
|
audio: (model, input, extra) => this.client.audio(model, input, extra, io),
|
|
206
263
|
transcribe: (model, audioUrl, language) => this.client.transcribe(model, audioUrl, language, io),
|
|
207
264
|
fetchMedia: (url) => this.client.fetchMediaDataUrl(url, io),
|
|
265
|
+
// local media (resize/combine/…) — same fetch + signal as network I/O
|
|
266
|
+
fetch: mediaFetch,
|
|
267
|
+
signal: ac.signal,
|
|
268
|
+
catalog: this.catalog,
|
|
269
|
+
progress: (msg) => emit({ type: "node-progress", nodeId: node.id, name: displayName(node), message: msg }),
|
|
208
270
|
};
|
|
209
271
|
};
|
|
210
272
|
|
|
211
273
|
const execNode = async (n) => {
|
|
212
274
|
const rec = nodesRec[n.id];
|
|
213
275
|
try {
|
|
276
|
+
throwIfAborted(ac.signal);
|
|
214
277
|
const inbound = graph.links.filter((l) => l.to.node === n.id);
|
|
215
278
|
const inp = {};
|
|
216
279
|
let fields = effFields.get(n.id);
|
|
@@ -226,9 +289,11 @@ export class Workflow {
|
|
|
226
289
|
else if (v != null) fields = { ...fields, [l.to.port]: v };
|
|
227
290
|
}
|
|
228
291
|
if (upstreamFail) throw new NanoodleError("upstream failed: " + upstreamFail);
|
|
292
|
+
throwIfAborted(ac.signal);
|
|
229
293
|
emit({ type: "node-start", nodeId: n.id, name: displayName(n) });
|
|
230
294
|
const t0 = Date.now();
|
|
231
295
|
const out = await RUNNERS[n.type]({ ...n, fields }, inp, ctxFor(n, rec));
|
|
296
|
+
throwIfAborted(ac.signal);
|
|
232
297
|
rec.status = "done";
|
|
233
298
|
rec.out = out;
|
|
234
299
|
rec.ms = Date.now() - t0;
|
|
@@ -274,6 +339,25 @@ export class Workflow {
|
|
|
274
339
|
remainingBalance: cost.balance,
|
|
275
340
|
});
|
|
276
341
|
|
|
342
|
+
// timeout/abort must fail the run even when local media finished after the deadline
|
|
343
|
+
// (or nodes never observed the signal). Prefer the abort reason when present.
|
|
344
|
+
if (ac.signal.aborted) {
|
|
345
|
+
const reason = abortReason(ac.signal);
|
|
346
|
+
const msg = reason.message || "run aborted";
|
|
347
|
+
// mark any still-pending nodes so result.errors is complete
|
|
348
|
+
for (const n of order) {
|
|
349
|
+
const rec = nodesRec[n.id];
|
|
350
|
+
if (rec && rec.status === "pending") {
|
|
351
|
+
rec.status = "error";
|
|
352
|
+
rec.error = msg;
|
|
353
|
+
if (!errors.some((e) => e.nodeId === n.id)) {
|
|
354
|
+
errors.push({ nodeId: n.id, name: displayName(n), message: msg });
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
throw new RunError(msg, result, reason.code ? { code: reason.code } : {});
|
|
359
|
+
}
|
|
360
|
+
|
|
277
361
|
const failedSinks = this.outputs.filter((o) => nodesRec[o.nodeId] && nodesRec[o.nodeId].status === "error");
|
|
278
362
|
if (failedSinks.length) {
|
|
279
363
|
const detail = failedSinks.map((o) => `"${o.key}": ${nodesRec[o.nodeId].error}`).join("; ");
|
|
@@ -282,9 +366,9 @@ export class Workflow {
|
|
|
282
366
|
return result;
|
|
283
367
|
}
|
|
284
368
|
|
|
285
|
-
_coerceInput(entry, value) {
|
|
369
|
+
_coerceInput(entry, value, mediaOpts) {
|
|
286
370
|
if (MEDIA_KINDS.has(entry.kind)) {
|
|
287
|
-
return coerceMediaInput(value, `input "${entry.key}"
|
|
371
|
+
return coerceMediaInput(value, `input "${entry.key}"`, mediaOpts);
|
|
288
372
|
}
|
|
289
373
|
if (entry.kind === "choice") {
|
|
290
374
|
const v = String(value);
|
package/src/x402.mjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { NanoodleError } from "./errors.mjs";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* x402 accountless payments (NanoGPT) — request with `x-x402: true` and no key,
|
|
5
|
+
* get HTTP 402 with payment options, pay in Nano (XNO), call the complete URL,
|
|
6
|
+
* receive the original response.
|
|
7
|
+
*
|
|
8
|
+
* The library NEVER holds funds or keys: the actual send happens inside the
|
|
9
|
+
* user-supplied `payment` callback (their own wallet, signer, or a human
|
|
10
|
+
* scanning a QR). Wire shape live-verified against nano-gpt.com 2026-07-12
|
|
11
|
+
* (tests/fixtures/x402/402.json is a real captured response).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Reject anything that isn't a callback — a seed/private key must never reach this library. */
|
|
15
|
+
export function assertPaymentOption(payment) {
|
|
16
|
+
if (payment == null) return;
|
|
17
|
+
if (typeof payment !== "function") {
|
|
18
|
+
throw new NanoodleError(
|
|
19
|
+
"payment must be a callback function — nanoodle never accepts wallet seeds or private keys. " +
|
|
20
|
+
"Do the send inside your callback with your own wallet/signer (it receives the invoice: " +
|
|
21
|
+
"{ payTo, amountRaw, uri, ... }).", { code: "x402" });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** ISO string or unix seconds → epoch ms (null when absent/unparsable). */
|
|
26
|
+
function toMs(v) {
|
|
27
|
+
if (v == null) return null;
|
|
28
|
+
if (typeof v === "number") return v < 1e12 ? v * 1000 : v; // seconds vs ms
|
|
29
|
+
const t = Date.parse(v);
|
|
30
|
+
return isNaN(t) ? null : t;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Pull the Nano payment option out of a 402 response body.
|
|
35
|
+
* Looks in the x402-standard `accepts` array first, then the NanoGPT
|
|
36
|
+
* `payment.accepted` list. Returns a frozen invoice for the payment callback.
|
|
37
|
+
*/
|
|
38
|
+
export function parseNanoInvoice(body, baseUrl) {
|
|
39
|
+
const pay = body && body.payment;
|
|
40
|
+
const pool = [
|
|
41
|
+
...(Array.isArray(body && body.accepts) ? body.accepts : []),
|
|
42
|
+
...(Array.isArray(pay && pay.accepted) ? pay.accepted : []),
|
|
43
|
+
];
|
|
44
|
+
const nano = pool.find((a) => a && a.scheme === "nano" && /^nano_[a-z0-9]+$/.test(String(a.payTo || "")));
|
|
45
|
+
if (!nano) return null;
|
|
46
|
+
const paymentId = nano.paymentId || (pay && pay.paymentId) || null;
|
|
47
|
+
const abs = (u) => (u ? new URL(u, baseUrl).href : null);
|
|
48
|
+
const amountRaw = String(nano.maxAmountRequired || nano.amount || "");
|
|
49
|
+
const usd = nano.maxAmountRequiredUSD != null ? Number(nano.maxAmountRequiredUSD)
|
|
50
|
+
: nano.amountUsd != null ? Number(nano.amountUsd)
|
|
51
|
+
: pay && pay.amountUsd != null ? Number(pay.amountUsd) : null;
|
|
52
|
+
return Object.freeze({
|
|
53
|
+
scheme: "nano",
|
|
54
|
+
paymentId,
|
|
55
|
+
payTo: nano.payTo,
|
|
56
|
+
/** integer raw units (1 XNO = 10^30 raw), as a string */
|
|
57
|
+
amountRaw,
|
|
58
|
+
/** human string, e.g. "0.00018406 XNO" */
|
|
59
|
+
amount: nano.maxAmountRequiredFormatted || nano.amountFormatted || null,
|
|
60
|
+
amountUsd: usd != null && isFinite(usd) ? usd : null,
|
|
61
|
+
/** ready-to-scan/click nano: URI */
|
|
62
|
+
uri: "nano:" + nano.payTo + (amountRaw ? "?amount=" + amountRaw : ""),
|
|
63
|
+
expiresAt: toMs(nano.expiresAt != null ? nano.expiresAt : pay && pay.expiresAt),
|
|
64
|
+
statusUrl: abs(nano.statusUrl || nano.callbackUrl || (pay && pay.statusUrl) || (paymentId && "/api/x402/status/" + paymentId)),
|
|
65
|
+
completeUrl: abs(nano.completeUrl || (pay && pay.completeUrl) || (paymentId && "/api/x402/complete/" + paymentId)),
|
|
66
|
+
explorerUrl: (nano.extra && nano.extra.explorerUrl) || null,
|
|
67
|
+
description: nano.description || null,
|
|
68
|
+
requestHash: (pay && pay.requestHash) || body.requestHash || null,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const RESULT_KEYS = ["choices", "data", "output", "runId", "url", "audioUrl", "transcription", "text"];
|
|
73
|
+
|
|
74
|
+
/** Does a complete-endpoint body already carry the replayed API result? */
|
|
75
|
+
export function looksLikeResult(j) {
|
|
76
|
+
return !!j && typeof j === "object" && RESULT_KEYS.some((k) => j[k] != null);
|
|
77
|
+
}
|
package/src/zlib.mjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Env-adaptive zlib: node:zlib in Node (dynamic import, cached), Compression/
|
|
3
|
+
* DecompressionStream in the browser. Everything is async because browsers have
|
|
4
|
+
* no synchronous form — callers (PNG codec, share links) are async paths anyway.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
let _zlib; // undefined = untried, null = unavailable (browser)
|
|
8
|
+
async function nodeZlib() {
|
|
9
|
+
if (_zlib === undefined) {
|
|
10
|
+
try { _zlib = await import("node:zlib"); } catch { _zlib = null; }
|
|
11
|
+
}
|
|
12
|
+
return _zlib;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function pipeThrough(bytes, stream) {
|
|
16
|
+
const out = new Blob([bytes]).stream().pipeThrough(stream);
|
|
17
|
+
return new Uint8Array(await new Response(out).arrayBuffer());
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function inflate(bytes) {
|
|
21
|
+
const z = await nodeZlib();
|
|
22
|
+
if (z) return new Uint8Array(z.inflateSync(bytes));
|
|
23
|
+
return streamZlib.inflate(bytes);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function deflate(bytes, { level = 9 } = {}) {
|
|
27
|
+
const z = await nodeZlib();
|
|
28
|
+
if (z) return new Uint8Array(z.deflateSync(bytes, { level }));
|
|
29
|
+
return streamZlib.deflate(bytes); // level is a Node-only hint
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function gunzip(bytes) {
|
|
33
|
+
const z = await nodeZlib();
|
|
34
|
+
if (z) return new Uint8Array(z.gunzipSync(bytes));
|
|
35
|
+
return streamZlib.gunzip(bytes);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The browser implementations, exported so tests can exercise them in Node
|
|
39
|
+
// (which also ships Compression/DecompressionStream) without hiding node:zlib.
|
|
40
|
+
export const streamZlib = {
|
|
41
|
+
inflate: (b) => pipeThrough(b, new DecompressionStream("deflate")),
|
|
42
|
+
deflate: (b) => pipeThrough(b, new CompressionStream("deflate")),
|
|
43
|
+
gunzip: (b) => pipeThrough(b, new DecompressionStream("gzip")),
|
|
44
|
+
};
|