@nodetool-ai/image-nodes 0.8.1

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 (87) hide show
  1. package/README.md +94 -0
  2. package/dist/.nodetool-build-stamp +1 -0
  3. package/dist/index.d.ts +19 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +19 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/nodes/game.d.ts +68 -0
  8. package/dist/nodes/game.d.ts.map +1 -0
  9. package/dist/nodes/game.js +551 -0
  10. package/dist/nodes/game.js.map +1 -0
  11. package/dist/nodes/gpu-device.d.ts +59 -0
  12. package/dist/nodes/gpu-device.d.ts.map +1 -0
  13. package/dist/nodes/gpu-device.js +144 -0
  14. package/dist/nodes/gpu-device.js.map +1 -0
  15. package/dist/nodes/image-io.d.ts +122 -0
  16. package/dist/nodes/image-io.d.ts.map +1 -0
  17. package/dist/nodes/image-io.js +381 -0
  18. package/dist/nodes/image-io.js.map +1 -0
  19. package/dist/nodes/image.d.ts +649 -0
  20. package/dist/nodes/image.d.ts.map +1 -0
  21. package/dist/nodes/image.js +2827 -0
  22. package/dist/nodes/image.js.map +1 -0
  23. package/dist/nodes/lib-grid.d.ts +19 -0
  24. package/dist/nodes/lib-grid.d.ts.map +1 -0
  25. package/dist/nodes/lib-grid.js +134 -0
  26. package/dist/nodes/lib-grid.js.map +1 -0
  27. package/dist/nodes/lib-image-channel.d.ts +38 -0
  28. package/dist/nodes/lib-image-channel.d.ts.map +1 -0
  29. package/dist/nodes/lib-image-channel.js +55 -0
  30. package/dist/nodes/lib-image-channel.js.map +1 -0
  31. package/dist/nodes/lib-image-color-grading.d.ts +3 -0
  32. package/dist/nodes/lib-image-color-grading.d.ts.map +1 -0
  33. package/dist/nodes/lib-image-color-grading.js +1080 -0
  34. package/dist/nodes/lib-image-color-grading.js.map +1 -0
  35. package/dist/nodes/lib-image-color.d.ts +96 -0
  36. package/dist/nodes/lib-image-color.d.ts.map +1 -0
  37. package/dist/nodes/lib-image-color.js +150 -0
  38. package/dist/nodes/lib-image-color.js.map +1 -0
  39. package/dist/nodes/lib-image-draw.d.ts +4 -0
  40. package/dist/nodes/lib-image-draw.d.ts.map +1 -0
  41. package/dist/nodes/lib-image-draw.js +464 -0
  42. package/dist/nodes/lib-image-draw.js.map +1 -0
  43. package/dist/nodes/lib-image-effects.d.ts +72 -0
  44. package/dist/nodes/lib-image-effects.d.ts.map +1 -0
  45. package/dist/nodes/lib-image-effects.js +123 -0
  46. package/dist/nodes/lib-image-effects.js.map +1 -0
  47. package/dist/nodes/lib-image-enhance.d.ts +3 -0
  48. package/dist/nodes/lib-image-enhance.d.ts.map +1 -0
  49. package/dist/nodes/lib-image-enhance.js +442 -0
  50. package/dist/nodes/lib-image-enhance.js.map +1 -0
  51. package/dist/nodes/lib-image-filter-extras.d.ts +72 -0
  52. package/dist/nodes/lib-image-filter-extras.d.ts.map +1 -0
  53. package/dist/nodes/lib-image-filter-extras.js +110 -0
  54. package/dist/nodes/lib-image-filter-extras.js.map +1 -0
  55. package/dist/nodes/lib-image-filter.d.ts +3 -0
  56. package/dist/nodes/lib-image-filter.d.ts.map +1 -0
  57. package/dist/nodes/lib-image-filter.js +588 -0
  58. package/dist/nodes/lib-image-filter.js.map +1 -0
  59. package/dist/nodes/lib-image-generators.d.ts +71 -0
  60. package/dist/nodes/lib-image-generators.d.ts.map +1 -0
  61. package/dist/nodes/lib-image-generators.js +158 -0
  62. package/dist/nodes/lib-image-generators.js.map +1 -0
  63. package/dist/nodes/lib-image-keyer.d.ts +34 -0
  64. package/dist/nodes/lib-image-keyer.d.ts.map +1 -0
  65. package/dist/nodes/lib-image-keyer.js +61 -0
  66. package/dist/nodes/lib-image-keyer.js.map +1 -0
  67. package/dist/nodes/lib-image-mask.d.ts +47 -0
  68. package/dist/nodes/lib-image-mask.d.ts.map +1 -0
  69. package/dist/nodes/lib-image-mask.js +59 -0
  70. package/dist/nodes/lib-image-mask.js.map +1 -0
  71. package/dist/nodes/lib-image-utils.d.ts +16 -0
  72. package/dist/nodes/lib-image-utils.d.ts.map +1 -0
  73. package/dist/nodes/lib-image-utils.js +61 -0
  74. package/dist/nodes/lib-image-utils.js.map +1 -0
  75. package/dist/nodes/lib-image-warp.d.ts +112 -0
  76. package/dist/nodes/lib-image-warp.d.ts.map +1 -0
  77. package/dist/nodes/lib-image-warp.js +236 -0
  78. package/dist/nodes/lib-image-warp.js.map +1 -0
  79. package/dist/nodes/lib-shader-utils.d.ts +105 -0
  80. package/dist/nodes/lib-shader-utils.d.ts.map +1 -0
  81. package/dist/nodes/lib-shader-utils.js +452 -0
  82. package/dist/nodes/lib-shader-utils.js.map +1 -0
  83. package/dist/nodes/sketch.d.ts +62 -0
  84. package/dist/nodes/sketch.d.ts.map +1 -0
  85. package/dist/nodes/sketch.js +325 -0
  86. package/dist/nodes/sketch.js.map +1 -0
  87. package/package.json +83 -0
@@ -0,0 +1,2827 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseNode, prop } from "@nodetool-ai/node-sdk";
8
+ import { blendModeGpuId, coerceBlendMode } from "@nodetool-ai/gpu";
9
+ import { compositeImageLayers } from "@nodetool-ai/gpu/node";
10
+ // Import from browser-safe subpaths (not the runtime barrel, which drags in the
11
+ // provider / python-bridge stack) so this module can bundle for the browser.
12
+ import { resolveEntities } from "@nodetool-ai/runtime/entities";
13
+ import { loadMediaRefBytes } from "@nodetool-ai/runtime/media-ref-bytes";
14
+ import { mapPromptAssetsToInputs } from "@nodetool-ai/runtime/prompt-asset-refs";
15
+ // node:fs / node:path / node:url are loaded lazily (only by the node-only
16
+ // Load/Save/Folder nodes below) so a workers/edge bundle of this module never
17
+ // statically resolves a Node built-in. The nodes that reach these are tagged
18
+ // `static platforms = NODE_ONLY`.
19
+ import { loadNodeFsPromises, loadNodePath, loadNodeUrl } from "@nodetool-ai/nodes-utils";
20
+ import { tagAsBrowserGpu, tagAsServer, tagAsContentCard, saveFilename, writeSavedFile, VISIBLE_WHEN_NOT_SAVING_TO_WORKSPACE, SAVE_TO_WORKSPACE_DESCRIPTION, SAVE_TO_WORKSPACE_TITLE } from "@nodetool-ai/nodes-utils";
21
+ import * as d from "typegpu/data";
22
+ import { transformCropV1, transformResizeV1, transformPadV1, transformRotate90V1, transformMirrorV1, transformAffineV1, blurGaussianV1, filtersBlurSeparableV1, colorGrayscaleV1, colorChannelShuffleV1, colorLevelsV1, mixerOverV1 } from "@nodetool-ai/gpu/pool";
23
+ import { IS_NODE } from "@nodetool-ai/config";
24
+ import { runShaderNode, runRecipeNode, colorValueToVec4, premultiplyVec4 } from "./lib-shader-utils.js";
25
+ import { decodeRgba, rawRgbaImageRef, loadSharp, SHARP_UNAVAILABLE_MESSAGE } from "./image-io.js";
26
+ import { isFiniteNumber, isNonEmptyString, isNumber, isObjectLike, isString } from "@nodetool-ai/node-sdk";
27
+ /** Filesystem / sharp-bound nodes that only run on a full Node runtime. */
28
+ const NODE_ONLY = ["node"];
29
+ function toBytes(data) {
30
+ if (!data)
31
+ return new Uint8Array();
32
+ if (data instanceof Uint8Array)
33
+ return data;
34
+ // Strip data URI prefix if present (e.g. "data:image/png;base64,...").
35
+ const comma = data.startsWith("data:") ? data.indexOf(",") : -1;
36
+ const b64 = comma >= 0 ? data.slice(comma + 1) : data;
37
+ return Uint8Array.from(Buffer.from(b64, "base64"));
38
+ }
39
+ async function imageBytesAsync(image, context) {
40
+ if (!isObjectLike(image))
41
+ return new Uint8Array();
42
+ const bytes = await loadMediaRefBytes(image, context);
43
+ return bytes ?? new Uint8Array();
44
+ }
45
+ /**
46
+ * Whether an image ref already points at a source (a wired-in upstream image,
47
+ * a stored asset, or inline bytes) rather than the empty default. Used to
48
+ * decide if an inline `asset://` mention in the prompt should supply the input.
49
+ */
50
+ function imageRefHasSource(image) {
51
+ if (!isObjectLike(image))
52
+ return false;
53
+ const ref = image;
54
+ if (isString(ref.uri) && ref.uri.trim() !== "")
55
+ return true;
56
+ if (ref.data != null && ref.data !== "")
57
+ return true;
58
+ return ref.asset_id != null && ref.asset_id !== "";
59
+ }
60
+ /**
61
+ * Normalize an image input that may be a single ImageRef (legacy single-image
62
+ * wiring) or a list of refs into an array, dropping non-object entries.
63
+ */
64
+ function normalizeImageList(value) {
65
+ const items = Array.isArray(value) ? value : value != null ? [value] : [];
66
+ return items.filter((item) => !!item && typeof item === "object");
67
+ }
68
+ async function filePath(uriOrPath) {
69
+ if (uriOrPath.startsWith("file://")) {
70
+ try {
71
+ const { fileURLToPath } = await loadNodeUrl();
72
+ return fileURLToPath(new URL(uriOrPath));
73
+ }
74
+ catch {
75
+ // Fallback for non-standard URIs like file://C:\path
76
+ return uriOrPath.slice("file://".length);
77
+ }
78
+ }
79
+ return uriOrPath;
80
+ }
81
+ function dateName(name) {
82
+ const now = new Date();
83
+ const pad = (v) => String(v).padStart(2, "0");
84
+ return name
85
+ .replaceAll("%Y", String(now.getFullYear()))
86
+ .replaceAll("%m", pad(now.getMonth() + 1))
87
+ .replaceAll("%d", pad(now.getDate()))
88
+ .replaceAll("%H", pad(now.getHours()))
89
+ .replaceAll("%M", pad(now.getMinutes()))
90
+ .replaceAll("%S", pad(now.getSeconds()));
91
+ }
92
+ function imageRef(data, extras = {}) {
93
+ return {
94
+ type: "image",
95
+ data: Buffer.from(data).toString("base64"),
96
+ ...extras
97
+ };
98
+ }
99
+ // `decodeRgba` and `rawRgbaImageRef` are the env-aware (sharp-free) codec
100
+ // helpers from ./image-io — re-exported so existing importers keep resolving
101
+ // them from this module.
102
+ export { decodeRgba, rawRgbaImageRef };
103
+ // Kept in sync by hand with `sniffImageMime` in @nodetool-ai/runtime: this
104
+ // module bundles for the browser, so it may not import the runtime barrel.
105
+ // "unknown" stays a state of its own — `guessAssetMime` reads it as undeclared
106
+ // and re-sniffs at the storage boundary.
107
+ function inferImageMime(uri, bytes) {
108
+ const lower = (uri ?? "").toLowerCase();
109
+ if (lower.endsWith(".jpg") || lower.endsWith(".jpeg"))
110
+ return "image/jpeg";
111
+ if (lower.endsWith(".webp"))
112
+ return "image/webp";
113
+ if (lower.endsWith(".gif"))
114
+ return "image/gif";
115
+ if (lower.endsWith(".bmp"))
116
+ return "image/bmp";
117
+ if (bytes.length < 4)
118
+ return "image/unknown";
119
+ if (bytes[0] === 0xff && bytes[1] === 0xd8)
120
+ return "image/jpeg";
121
+ if (bytes[0] === 0x47 && bytes[1] === 0x49)
122
+ return "image/gif";
123
+ if (bytes[0] === 0x42 && bytes[1] === 0x4d)
124
+ return "image/bmp";
125
+ if (bytes.length >= 12 &&
126
+ bytes[0] === 0x52 && // "R"
127
+ bytes[1] === 0x49 && // "I"
128
+ bytes[2] === 0x46 && // "F"
129
+ bytes[3] === 0x46 && // "F"
130
+ bytes[8] === 0x57 && // "W"
131
+ bytes[9] === 0x45 && // "E"
132
+ bytes[10] === 0x42 && // "B"
133
+ bytes[11] === 0x50 // "P"
134
+ )
135
+ return "image/webp";
136
+ if (bytes[0] === 0x89 &&
137
+ bytes[1] === 0x50 &&
138
+ bytes[2] === 0x4e &&
139
+ bytes[3] === 0x47) {
140
+ return "image/png";
141
+ }
142
+ return "image/unknown";
143
+ }
144
+ /** The extension the bytes themselves say this image should carry. */
145
+ function imageExtension(bytes) {
146
+ switch (inferImageMime(undefined, bytes)) {
147
+ case "image/jpeg":
148
+ return ".jpg";
149
+ case "image/webp":
150
+ return ".webp";
151
+ case "image/gif":
152
+ return ".gif";
153
+ case "image/bmp":
154
+ return ".bmp";
155
+ default:
156
+ return ".png";
157
+ }
158
+ }
159
+ function getModelConfig(props) {
160
+ const model = (props.model ?? {});
161
+ return {
162
+ providerId: isString(model.provider) ? model.provider : "",
163
+ modelId: isString(model.id) ? model.id : ""
164
+ };
165
+ }
166
+ const IMAGE_ASPECT_RATIOS = {
167
+ "21:9": [21, 9],
168
+ "16:9": [16, 9],
169
+ "3:2": [3, 2],
170
+ "7:5": [7, 5],
171
+ "4:3": [4, 3],
172
+ "5:4": [5, 4],
173
+ "1:1": [1, 1],
174
+ "9:16": [9, 16],
175
+ "2:3": [2, 3],
176
+ "5:7": [5, 7],
177
+ "3:4": [3, 4],
178
+ "4:5": [4, 5]
179
+ };
180
+ const IMAGE_RESOLUTION_PX = {
181
+ "1K": 1024,
182
+ "2K": 2048,
183
+ "4K": 4096
184
+ };
185
+ function resolveImageSize(resolution, aspectRatio) {
186
+ const base = IMAGE_RESOLUTION_PX[resolution] ?? 1024;
187
+ const [aw, ah] = IMAGE_ASPECT_RATIOS[aspectRatio] ?? [1, 1];
188
+ if (aw >= ah) {
189
+ const height = base;
190
+ const width = Math.round((height * aw) / ah);
191
+ return { width, height };
192
+ }
193
+ const width = base;
194
+ const height = Math.round((width * ah) / aw);
195
+ return { width, height };
196
+ }
197
+ const IMAGE_ASPECT_RATIO_VALUES = Object.keys(IMAGE_ASPECT_RATIOS);
198
+ const IMAGE_RESOLUTION_VALUES = Object.keys(IMAGE_RESOLUTION_PX);
199
+ const IMAGE_EDIT_STRENGTH_VALUES = [0.25, 0.5, 0.65, 0.75, 0.85, 1.0];
200
+ function hasProviderSupport(context, providerId, modelId) {
201
+ return (!!context &&
202
+ typeof context.runProviderPrediction === "function" &&
203
+ !!providerId &&
204
+ !!modelId);
205
+ }
206
+ async function metadataFor(bytes) {
207
+ try {
208
+ const sharp = await loadSharp();
209
+ if (!sharp)
210
+ throw new Error(SHARP_UNAVAILABLE_MESSAGE);
211
+ const md = await sharp(bytes).metadata();
212
+ return {
213
+ width: md.width ?? undefined,
214
+ height: md.height ?? undefined
215
+ };
216
+ }
217
+ catch {
218
+ return { width: undefined, height: undefined };
219
+ }
220
+ }
221
+ export class LoadImageFileNode extends BaseNode {
222
+ static nodeType = "nodetool.image.LoadImageFile";
223
+ static title = "Load Image File";
224
+ static description = "Read an image file from disk.\n image, input, load, file";
225
+ static metadataOutputTypes = {
226
+ output: "image"
227
+ };
228
+ static inlineFields = ["path"];
229
+ static inputFields = [];
230
+ static platforms = NODE_ONLY;
231
+ async process() {
232
+ const fs = await loadNodeFsPromises();
233
+ const p = await filePath(this.path);
234
+ const data = new Uint8Array(await fs.readFile(p));
235
+ const meta = await metadataFor(data);
236
+ return {
237
+ output: imageRef(data, {
238
+ uri: `file://${p}`,
239
+ mimeType: inferImageMime(p, data),
240
+ width: meta.width,
241
+ height: meta.height
242
+ })
243
+ };
244
+ }
245
+ }
246
+ __decorate([
247
+ prop({
248
+ type: "str",
249
+ default: "",
250
+ title: "Path",
251
+ description: "Path to the image file to read"
252
+ })
253
+ ], LoadImageFileNode.prototype, "path", void 0);
254
+ export class LoadImageFolderNode extends BaseNode {
255
+ static nodeType = "nodetool.image.LoadImageFolder";
256
+ static title = "Load Image Folder";
257
+ static description = "Load all images from a folder, optionally including subfolders.\n image, load, folder, files";
258
+ static metadataOutputTypes = {
259
+ image: "image",
260
+ path: "str",
261
+ images: "list"
262
+ };
263
+ static inlineFields = ["folder"];
264
+ static inputFields = [];
265
+ static inputMode = "buffered";
266
+ static outputCorrelation = {
267
+ image: { kind: "iteration", source: "__execution__", group: "items" },
268
+ path: { kind: "iteration", source: "__execution__", group: "items" },
269
+ images: { kind: "single", source: "__execution__" }
270
+ };
271
+ static platforms = NODE_ONLY;
272
+ async process() {
273
+ const collected = [];
274
+ let firstPath = "";
275
+ for await (const item of this._loadImages()) {
276
+ if (collected.length === 0)
277
+ firstPath = String(item.path ?? "");
278
+ collected.push(item.image);
279
+ }
280
+ return {
281
+ image: collected[0] ?? {},
282
+ path: firstPath,
283
+ images: collected
284
+ };
285
+ }
286
+ async *_loadImages() {
287
+ const fs = await loadNodeFsPromises();
288
+ const path = await loadNodePath();
289
+ const raw = this.folder;
290
+ const rawUri = isNonEmptyString(raw) ? raw : (raw.uri ?? "");
291
+ const folder = rawUri.startsWith("file:") ? await filePath(rawUri) : rawUri;
292
+ if (!folder)
293
+ return;
294
+ const extensions = this.extensions.map((e) => e.toLowerCase());
295
+ const patternStr = this.pattern;
296
+ const patternRegex = patternStr
297
+ ? new RegExp("^" +
298
+ patternStr
299
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
300
+ .replace(/\*/g, ".*")
301
+ .replace(/\?/g, ".") +
302
+ "$", "i")
303
+ : null;
304
+ const files = [];
305
+ const collect = async (dir) => {
306
+ let entries;
307
+ try {
308
+ entries = await fs.readdir(dir, { withFileTypes: true });
309
+ }
310
+ catch {
311
+ // directory does not exist or is not accessible
312
+ return;
313
+ }
314
+ for (const entry of entries) {
315
+ if (entry.isDirectory() && this.include_subdirectories) {
316
+ await collect(path.join(dir, entry.name));
317
+ }
318
+ else if (entry.isFile()) {
319
+ files.push({ fullPath: path.join(dir, entry.name), name: entry.name });
320
+ }
321
+ }
322
+ };
323
+ await collect(folder);
324
+ for (const file of files) {
325
+ const ext = path.extname(file.name).toLowerCase();
326
+ if (!extensions.includes(ext))
327
+ continue;
328
+ if (patternRegex && !patternRegex.test(file.name))
329
+ continue;
330
+ const data = new Uint8Array(await fs.readFile(file.fullPath));
331
+ const meta = await metadataFor(data);
332
+ yield {
333
+ image: imageRef(data, {
334
+ uri: `file://${file.fullPath}`,
335
+ mimeType: inferImageMime(file.fullPath, data),
336
+ width: meta.width,
337
+ height: meta.height
338
+ }),
339
+ path: file.fullPath
340
+ };
341
+ }
342
+ }
343
+ async *genProcess() {
344
+ const collected = [];
345
+ for await (const item of this._loadImages()) {
346
+ collected.push(item.image);
347
+ yield item;
348
+ }
349
+ yield { images: collected };
350
+ }
351
+ }
352
+ __decorate([
353
+ prop({
354
+ type: "str",
355
+ default: "",
356
+ title: "Folder",
357
+ description: "Folder to scan for images"
358
+ })
359
+ ], LoadImageFolderNode.prototype, "folder", void 0);
360
+ __decorate([
361
+ prop({
362
+ type: "bool",
363
+ default: false,
364
+ title: "Include Subdirectories",
365
+ description: "Include images in subfolders"
366
+ })
367
+ ], LoadImageFolderNode.prototype, "include_subdirectories", void 0);
368
+ __decorate([
369
+ prop({
370
+ type: "list[str]",
371
+ default: [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".tiff"],
372
+ title: "Extensions",
373
+ description: "Image file extensions to include"
374
+ })
375
+ ], LoadImageFolderNode.prototype, "extensions", void 0);
376
+ __decorate([
377
+ prop({
378
+ type: "str",
379
+ default: "",
380
+ title: "Pattern",
381
+ description: "Pattern to match image files"
382
+ })
383
+ ], LoadImageFolderNode.prototype, "pattern", void 0);
384
+ export class SaveImageFileImageNode extends BaseNode {
385
+ static nodeType = "nodetool.image.SaveImageFile";
386
+ static title = "Save Image File";
387
+ static description = "Write an image to disk.\n image, output, save, file";
388
+ static metadataOutputTypes = {
389
+ output: "image",
390
+ path: "str"
391
+ };
392
+ static inlineFields = ["save_to_workspace", "filename"];
393
+ static inputFields = ["image"];
394
+ static platforms = NODE_ONLY;
395
+ async process(context) {
396
+ const bytes = await imageBytesAsync(this.image, context);
397
+ // An empty name used to resolve to the destination folder itself, so the
398
+ // image landed one level up named after the folder; a name typed without
399
+ // an extension produced a file nothing would open.
400
+ const filename = saveFilename({
401
+ filename: dateName(this.filename),
402
+ fallback: dateName("image_%Y-%m-%d_%H-%M-%S"),
403
+ extension: imageExtension(bytes)
404
+ });
405
+ const p = await writeSavedFile({
406
+ folder: this.folder,
407
+ filename,
408
+ saveToWorkspace: this.save_to_workspace,
409
+ workspace: context?.workspace,
410
+ workspaceDir: context?.workspaceDir,
411
+ overwrite: this.overwrite,
412
+ bytes
413
+ });
414
+ const meta = await metadataFor(bytes);
415
+ return {
416
+ output: imageRef(bytes, {
417
+ uri: `file://${p}`,
418
+ mimeType: inferImageMime(p, bytes),
419
+ width: meta.width,
420
+ height: meta.height
421
+ }),
422
+ path: p
423
+ };
424
+ }
425
+ }
426
+ __decorate([
427
+ prop({
428
+ type: "image",
429
+ default: {
430
+ type: "image",
431
+ uri: "",
432
+ asset_id: null,
433
+ data: null,
434
+ metadata: null
435
+ },
436
+ title: "Image",
437
+ description: "The image to save"
438
+ })
439
+ ], SaveImageFileImageNode.prototype, "image", void 0);
440
+ __decorate([
441
+ prop({
442
+ type: "bool",
443
+ default: true,
444
+ title: SAVE_TO_WORKSPACE_TITLE,
445
+ description: SAVE_TO_WORKSPACE_DESCRIPTION
446
+ })
447
+ ], SaveImageFileImageNode.prototype, "save_to_workspace", void 0);
448
+ __decorate([
449
+ prop({
450
+ type: "str",
451
+ default: "",
452
+ title: "Folder",
453
+ description: "Folder where the file will be saved",
454
+ json_schema_extra: VISIBLE_WHEN_NOT_SAVING_TO_WORKSPACE
455
+ })
456
+ ], SaveImageFileImageNode.prototype, "folder", void 0);
457
+ __decorate([
458
+ prop({
459
+ type: "str",
460
+ default: "",
461
+ title: "Filename",
462
+ description: "\n The name of the image file.\n You can use time and date variables to create unique names:\n %Y - Year\n %m - Month\n %d - Day\n %H - Hour\n %M - Minute\n %S - Second\n "
463
+ })
464
+ ], SaveImageFileImageNode.prototype, "filename", void 0);
465
+ __decorate([
466
+ prop({
467
+ type: "bool",
468
+ default: false,
469
+ title: "Overwrite",
470
+ description: "Overwrite the file if it already exists, otherwise file will be renamed"
471
+ })
472
+ ], SaveImageFileImageNode.prototype, "overwrite", void 0);
473
+ export class LoadImageAssetsNode extends BaseNode {
474
+ static nodeType = "nodetool.image.LoadImageAssets";
475
+ static title = "Load Image Assets";
476
+ static description = "Load images from an asset folder.\n load, image, file, import";
477
+ static metadataOutputTypes = {
478
+ image: "image",
479
+ name: "str",
480
+ images: "list"
481
+ };
482
+ static inlineFields = [];
483
+ static inputFields = [];
484
+ static inputMode = "buffered";
485
+ static outputCorrelation = {
486
+ image: { kind: "iteration", source: "__execution__", group: "items" },
487
+ name: { kind: "iteration", source: "__execution__", group: "items" },
488
+ images: { kind: "single", source: "__execution__" }
489
+ };
490
+ static platforms = NODE_ONLY;
491
+ async process() {
492
+ const loader = new LoadImageFolderNode();
493
+ loader.assign({ folder: this.folder });
494
+ const result = await loader.process();
495
+ return result;
496
+ }
497
+ async *genProcess() {
498
+ const loader = new LoadImageFolderNode();
499
+ loader.assign({ folder: this.folder });
500
+ for await (const item of loader.genProcess()) {
501
+ yield item;
502
+ }
503
+ }
504
+ }
505
+ __decorate([
506
+ prop({
507
+ type: "folder",
508
+ default: {
509
+ type: "folder",
510
+ uri: "",
511
+ asset_id: null,
512
+ data: null,
513
+ metadata: null
514
+ },
515
+ title: "Folder",
516
+ description: "The asset folder to load the images from."
517
+ })
518
+ ], LoadImageAssetsNode.prototype, "folder", void 0);
519
+ export class SaveImageNode extends BaseNode {
520
+ static nodeType = "nodetool.image.SaveImage";
521
+ static title = "Save Image Asset";
522
+ static description = "Save an image to specified asset folder with customizable name format.\n save, image, folder, naming";
523
+ static metadataOutputTypes = {
524
+ output: "image"
525
+ };
526
+ static inlineFields = ["name"];
527
+ static inputFields = ["image"];
528
+ static platforms = NODE_ONLY;
529
+ async process(context) {
530
+ const bytes = await imageBytesAsync(this.image, context);
531
+ if (bytes.length === 0)
532
+ throw new Error("The input image is not connected.");
533
+ const name = dateName(this.name);
534
+ const mime = inferImageMime(undefined, bytes);
535
+ const meta = await metadataFor(bytes);
536
+ // Create asset via context (persists to DB + storage)
537
+ // `createAsset` is a method on every context, wired or not — checking
538
+ // for the function always passed and the fallback below was unreachable,
539
+ // so a host without asset persistence threw instead of writing a file.
540
+ if (context?.hasModelInterface?.("createAsset")) {
541
+ const parentId = isString(this.folder)
542
+ ? null
543
+ : (this.folder.asset_id ?? null);
544
+ const asset = (await context.createAsset({
545
+ name,
546
+ contentType: mime === "image/unknown" ? "image/png" : mime,
547
+ content: bytes,
548
+ parentId,
549
+ nodeId: this.__node_id || null
550
+ }));
551
+ const assetId = asset.id;
552
+ const ext = name.includes(".") ? name.slice(name.lastIndexOf(".")) : ".png";
553
+ return {
554
+ output: imageRef(bytes, {
555
+ uri: `asset://${assetId}${ext}`,
556
+ mimeType: mime,
557
+ width: meta.width,
558
+ height: meta.height
559
+ })
560
+ };
561
+ }
562
+ // Fallback: write to filesystem
563
+ const fs = await loadNodeFsPromises();
564
+ const path = await loadNodePath();
565
+ const folder = isString(this.folder) ? this.folder : ".";
566
+ const full = path.resolve(folder, name);
567
+ await fs.mkdir(path.dirname(full), { recursive: true });
568
+ await fs.writeFile(full, bytes);
569
+ return {
570
+ output: imageRef(bytes, {
571
+ uri: `file://${full}`,
572
+ mimeType: mime,
573
+ width: meta.width,
574
+ height: meta.height
575
+ })
576
+ };
577
+ }
578
+ }
579
+ __decorate([
580
+ prop({
581
+ type: "image",
582
+ default: {
583
+ type: "image",
584
+ uri: "",
585
+ asset_id: null,
586
+ data: null,
587
+ metadata: null
588
+ },
589
+ title: "Image",
590
+ description: "The image to save."
591
+ })
592
+ ], SaveImageNode.prototype, "image", void 0);
593
+ __decorate([
594
+ prop({
595
+ type: "folder",
596
+ default: {
597
+ type: "folder",
598
+ uri: "",
599
+ asset_id: null,
600
+ data: null,
601
+ metadata: null
602
+ },
603
+ title: "Folder",
604
+ description: "The asset folder to save the image in."
605
+ })
606
+ ], SaveImageNode.prototype, "folder", void 0);
607
+ __decorate([
608
+ prop({
609
+ type: "str",
610
+ default: "%Y-%m-%d_%H-%M-%S.png",
611
+ title: "Name",
612
+ description: "\n Name of the output file.\n You can use time and date variables to create unique names:\n %Y - Year\n %m - Month\n %d - Day\n %H - Hour\n %M - Minute\n %S - Second\n "
613
+ })
614
+ ], SaveImageNode.prototype, "name", void 0);
615
+ export class GetMetadataNode extends BaseNode {
616
+ static nodeType = "nodetool.image.GetMetadata";
617
+ static title = "Get Metadata";
618
+ static description = "Get metadata about the input image.\n metadata, properties, analysis, information";
619
+ static metadataOutputTypes = {
620
+ format: "str",
621
+ mode: "str",
622
+ width: "int",
623
+ height: "int",
624
+ channels: "int"
625
+ };
626
+ static inlineFields = [];
627
+ static inputFields = ["image"];
628
+ static platforms = NODE_ONLY;
629
+ async process(context) {
630
+ const image = this.image;
631
+ const bytes = await imageBytesAsync(image, context);
632
+ try {
633
+ const sharp = await loadSharp();
634
+ if (!sharp)
635
+ throw new Error(SHARP_UNAVAILABLE_MESSAGE);
636
+ const md = await sharp(bytes).metadata();
637
+ const formatMap = {
638
+ jpeg: "JPEG",
639
+ png: "PNG",
640
+ webp: "WEBP",
641
+ gif: "GIF",
642
+ tiff: "TIFF",
643
+ svg: "SVG",
644
+ heif: "HEIF",
645
+ avif: "AVIF",
646
+ raw: "RAW"
647
+ };
648
+ const channelsToMode = {
649
+ 1: "L",
650
+ 2: "LA",
651
+ 3: "RGB",
652
+ 4: "RGBA"
653
+ };
654
+ return {
655
+ format: formatMap[md.format ?? ""] ?? (md.format ?? "unknown").toUpperCase(),
656
+ mode: channelsToMode[md.channels ?? 3] ?? "RGB",
657
+ width: md.width ?? 0,
658
+ height: md.height ?? 0,
659
+ channels: md.channels ?? 0
660
+ };
661
+ }
662
+ catch {
663
+ return {
664
+ format: "unknown",
665
+ mode: "RGB",
666
+ width: image.width ?? 0,
667
+ height: image.height ?? 0,
668
+ channels: 0
669
+ };
670
+ }
671
+ }
672
+ }
673
+ __decorate([
674
+ prop({
675
+ type: "image",
676
+ default: {
677
+ type: "image",
678
+ uri: "",
679
+ asset_id: null,
680
+ data: null,
681
+ metadata: null
682
+ },
683
+ title: "Image",
684
+ description: "The input image."
685
+ })
686
+ ], GetMetadataNode.prototype, "image", void 0);
687
+ export class BatchToListNode extends BaseNode {
688
+ static nodeType = "nodetool.image.BatchToList";
689
+ static title = "Batch To List";
690
+ static description = "Convert an image batch to a list of image references.\n batch, list, images, processing";
691
+ static metadataOutputTypes = {
692
+ output: "list[image]"
693
+ };
694
+ static inlineFields = [];
695
+ static inputFields = ["batch"];
696
+ async process() {
697
+ const batch = this.batch;
698
+ if (!batch) {
699
+ throw new Error("Batch input is empty.");
700
+ }
701
+ const batchObj = batch;
702
+ if (batchObj.data == null) {
703
+ throw new Error("Batch data is null.");
704
+ }
705
+ if (!Array.isArray(batchObj.data)) {
706
+ // Single image ref — wrap in list
707
+ return { output: [batch] };
708
+ }
709
+ // Unwrap batch data into individual ImageRefs
710
+ const output = batchObj.data.map((item) => {
711
+ if (item instanceof Uint8Array || isString(item)) {
712
+ return imageRef(toBytes(item));
713
+ }
714
+ return item;
715
+ });
716
+ return { output };
717
+ }
718
+ }
719
+ __decorate([
720
+ prop({
721
+ type: "image",
722
+ default: {
723
+ type: "image",
724
+ uri: "",
725
+ asset_id: null,
726
+ data: null,
727
+ metadata: null
728
+ },
729
+ title: "Batch",
730
+ description: "The batch of images to convert."
731
+ })
732
+ ], BatchToListNode.prototype, "batch", void 0);
733
+ export class ImagesToListNode extends BaseNode {
734
+ static nodeType = "nodetool.image.ImagesToList";
735
+ static title = "Images To List";
736
+ static description = "Convert all dynamic properties to a list of image references.\n list, images, processing";
737
+ static metadataOutputTypes = {
738
+ output: "list[image]"
739
+ };
740
+ static supportsDynamicInputs = true;
741
+ static inlineFields = [];
742
+ static inputFields = [];
743
+ async process() {
744
+ const out = [];
745
+ for (const [, value] of this.dynamicProps) {
746
+ if (value == null)
747
+ continue;
748
+ if (Array.isArray(value)) {
749
+ for (const item of value) {
750
+ if (item != null)
751
+ out.push(item);
752
+ }
753
+ }
754
+ else {
755
+ out.push(value);
756
+ }
757
+ }
758
+ return { output: out };
759
+ }
760
+ }
761
+ export class PasteNode extends BaseNode {
762
+ static nodeType = "nodetool.image.Paste";
763
+ static title = "Paste";
764
+ static description = "Paste one image onto another at specified coordinates.\n paste, composite, positioning, overlay";
765
+ static metadataOutputTypes = {
766
+ output: "image"
767
+ };
768
+ static inlineFields = [];
769
+ static inputFields = ["image", "paste"];
770
+ async process(context) {
771
+ const image = this.image;
772
+ const paste = this.paste;
773
+ const left = Math.max(0, this.left);
774
+ const top = Math.max(0, this.top);
775
+ const base = await decodeRgba(image, context);
776
+ if (!base.width || !base.height)
777
+ return { output: image };
778
+ const over = await decodeRgba(paste, context);
779
+ if (!over.width || !over.height) {
780
+ return { output: rawRgbaImageRef(base.rgba, base.width, base.height) };
781
+ }
782
+ // Place the overlay into a base-sized canvas at (left, top): pad in UV
783
+ // relative to the overlay, but force the output to the base dimensions so
784
+ // an overlay overhanging the base edge is clipped (mirrors sharp.composite).
785
+ const placed = await runShaderNode(transformPadV1, {
786
+ left: left / over.width,
787
+ top: top / over.height,
788
+ right: Math.max(0, base.width - over.width - left) / over.width,
789
+ bottom: Math.max(0, base.height - over.height - top) / over.height,
790
+ color: d.vec4f(0, 0, 0, 0)
791
+ }, paste, { outputWidth: base.width, outputHeight: base.height }, context);
792
+ // Source-over composite the placed overlay onto the base.
793
+ const output = await runShaderNode(mixerOverV1, { opacity: 1 }, image, { extraInputs: { over: placed } }, context);
794
+ return { output };
795
+ }
796
+ }
797
+ __decorate([
798
+ prop({
799
+ type: "image",
800
+ default: {
801
+ type: "image",
802
+ uri: "",
803
+ asset_id: null,
804
+ data: null,
805
+ metadata: null
806
+ },
807
+ title: "Image",
808
+ description: "The image to paste into."
809
+ })
810
+ ], PasteNode.prototype, "image", void 0);
811
+ __decorate([
812
+ prop({
813
+ type: "image",
814
+ default: {
815
+ type: "image",
816
+ uri: "",
817
+ asset_id: null,
818
+ data: null,
819
+ metadata: null
820
+ },
821
+ title: "Paste",
822
+ description: "The image to paste."
823
+ })
824
+ ], PasteNode.prototype, "paste", void 0);
825
+ __decorate([
826
+ prop({
827
+ type: "int",
828
+ default: 0,
829
+ title: "Left",
830
+ description: "The left coordinate.",
831
+ min: 0,
832
+ max: 8192
833
+ })
834
+ ], PasteNode.prototype, "left", void 0);
835
+ __decorate([
836
+ prop({
837
+ type: "int",
838
+ default: 0,
839
+ title: "Top",
840
+ description: "The top coordinate.",
841
+ min: 0,
842
+ max: 8192
843
+ })
844
+ ], PasteNode.prototype, "top", void 0);
845
+ const RESIZE_IMAGE_NODE_TYPE = "nodetool.image.ResizeImage";
846
+ function deprecatedResizeDescription(body) {
847
+ return `Deprecated — use Resize Image (${RESIZE_IMAGE_NODE_TYPE}) instead.\n${body}`;
848
+ }
849
+ export class ResizeImageNode extends BaseNode {
850
+ static nodeType = RESIZE_IMAGE_NODE_TYPE;
851
+ static title = "Resize Image";
852
+ static description = "Scale, set exact dimensions, or fit inside a box. In dimensions mode, set width or height to 0 to preserve that axis.\n image, resize, scale, fit, dimensions";
853
+ static metadataOutputTypes = {
854
+ output: "image"
855
+ };
856
+ static inlineFields = ["mode", "scale", "width", "height"];
857
+ static inputFields = ["image"];
858
+ async process(context) {
859
+ const image = this.image;
860
+ const { width: srcW, height: srcH } = await decodeRgba(image, context);
861
+ if (!srcW || !srcH)
862
+ return { output: image };
863
+ // A graph saved before a value was removed can still carry it, so the
864
+ // mode is normalized rather than trusted.
865
+ const mode = this.mode === "scale" || this.mode === "fit" ? this.mode : "dimensions";
866
+ let outputWidth;
867
+ let outputHeight;
868
+ if (mode === "scale") {
869
+ const scale = this.scale > 0 ? this.scale : 1;
870
+ outputWidth = Math.max(1, Math.round(srcW * scale));
871
+ outputHeight = Math.max(1, Math.round(srcH * scale));
872
+ }
873
+ else if (mode === "fit") {
874
+ const targetW = Math.max(1, this.width);
875
+ const targetH = Math.max(1, this.height);
876
+ const ratio = Math.min(targetW / srcW, targetH / srcH);
877
+ outputWidth = Math.max(1, Math.round(srcW * ratio));
878
+ outputHeight = Math.max(1, Math.round(srcH * ratio));
879
+ }
880
+ else {
881
+ let w = this.width;
882
+ let h = this.height;
883
+ if (w <= 0 && h <= 0) {
884
+ w = srcW;
885
+ h = srcH;
886
+ }
887
+ else if (w <= 0) {
888
+ w = Math.max(1, Math.round((srcW / srcH) * h));
889
+ }
890
+ else if (h <= 0) {
891
+ h = Math.max(1, Math.round((srcH / srcW) * w));
892
+ }
893
+ outputWidth = Math.round(w);
894
+ outputHeight = Math.round(h);
895
+ }
896
+ const output = await runShaderNode(transformResizeV1, { mode: 1 }, image, { outputWidth, outputHeight }, context);
897
+ return { output };
898
+ }
899
+ }
900
+ __decorate([
901
+ prop({
902
+ type: "image",
903
+ default: {
904
+ type: "image",
905
+ uri: "",
906
+ asset_id: null,
907
+ data: null,
908
+ metadata: null
909
+ },
910
+ title: "Image",
911
+ description: "The image to resize."
912
+ })
913
+ ], ResizeImageNode.prototype, "image", void 0);
914
+ __decorate([
915
+ prop({
916
+ type: "enum",
917
+ default: "dimensions",
918
+ values: ["scale", "dimensions", "fit"],
919
+ title: "Mode",
920
+ description: "Scale multiplies pixel size; Dimensions sets exact W×H; Fit preserves aspect inside a box."
921
+ })
922
+ ], ResizeImageNode.prototype, "mode", void 0);
923
+ __decorate([
924
+ prop({
925
+ type: "float",
926
+ default: 1,
927
+ title: "Scale",
928
+ description: "Scale factor (scale mode).",
929
+ min: 0.1,
930
+ max: 10
931
+ })
932
+ ], ResizeImageNode.prototype, "scale", void 0);
933
+ __decorate([
934
+ prop({
935
+ type: "int",
936
+ default: 512,
937
+ title: "Width",
938
+ description: "Target width (dimensions / fit modes). Use 0 in dimensions mode to preserve aspect on this axis.",
939
+ min: 0,
940
+ max: 8192
941
+ })
942
+ ], ResizeImageNode.prototype, "width", void 0);
943
+ __decorate([
944
+ prop({
945
+ type: "int",
946
+ default: 512,
947
+ title: "Height",
948
+ description: "Target height (dimensions / fit modes). Use 0 in dimensions mode to preserve aspect on this axis.",
949
+ min: 0,
950
+ max: 8192
951
+ })
952
+ ], ResizeImageNode.prototype, "height", void 0);
953
+ export class ScaleNode extends BaseNode {
954
+ static nodeType = "nodetool.image.Scale";
955
+ static title = "Scale";
956
+ static deprecated = true;
957
+ static replacedBy = RESIZE_IMAGE_NODE_TYPE;
958
+ static description = deprecatedResizeDescription("Enlarge or shrink an image by a scale factor.\n image, resize, scale");
959
+ static metadataOutputTypes = {
960
+ output: "image"
961
+ };
962
+ static inlineFields = [];
963
+ static inputFields = ["image"];
964
+ async process(context) {
965
+ const image = this.image;
966
+ const scale = this.scale > 0 ? this.scale : 1;
967
+ const { width: srcW, height: srcH } = await decodeRgba(image, context);
968
+ if (!srcW || !srcH)
969
+ return { output: image };
970
+ const output = await runShaderNode(transformResizeV1, { mode: 1 }, image, {
971
+ outputWidth: Math.max(1, Math.round(srcW * scale)),
972
+ outputHeight: Math.max(1, Math.round(srcH * scale))
973
+ }, context);
974
+ return { output };
975
+ }
976
+ }
977
+ __decorate([
978
+ prop({
979
+ type: "image",
980
+ default: {
981
+ type: "image",
982
+ uri: "",
983
+ asset_id: null,
984
+ data: null,
985
+ metadata: null
986
+ },
987
+ title: "Image",
988
+ description: "The image to scale."
989
+ })
990
+ ], ScaleNode.prototype, "image", void 0);
991
+ __decorate([
992
+ prop({
993
+ type: "float",
994
+ default: 1,
995
+ title: "Scale",
996
+ description: "The scale factor.",
997
+ min: 0,
998
+ max: 10
999
+ })
1000
+ ], ScaleNode.prototype, "scale", void 0);
1001
+ export class ResizeNode extends BaseNode {
1002
+ static nodeType = "nodetool.image.Resize";
1003
+ static title = "Resize";
1004
+ static deprecated = true;
1005
+ static replacedBy = RESIZE_IMAGE_NODE_TYPE;
1006
+ static description = deprecatedResizeDescription("Change image dimensions to specified width and height.\n image, resize");
1007
+ static metadataOutputTypes = {
1008
+ output: "image"
1009
+ };
1010
+ static inlineFields = [];
1011
+ static inputFields = ["image"];
1012
+ async process(context) {
1013
+ const image = this.image;
1014
+ const { width: srcW, height: srcH } = await decodeRgba(image, context);
1015
+ if (!srcW || !srcH)
1016
+ return { output: image };
1017
+ let w = this.width;
1018
+ let h = this.height;
1019
+ // A zero dimension means "preserve aspect from the other" (matches the old
1020
+ // sharp behaviour where one undefined dimension is derived from the source).
1021
+ if (w <= 0 && h <= 0) {
1022
+ w = srcW;
1023
+ h = srcH;
1024
+ }
1025
+ else if (w <= 0) {
1026
+ w = Math.max(1, Math.round((srcW / srcH) * h));
1027
+ }
1028
+ else if (h <= 0) {
1029
+ h = Math.max(1, Math.round((srcH / srcW) * w));
1030
+ }
1031
+ const output = await runShaderNode(transformResizeV1, { mode: 1 }, image, { outputWidth: Math.round(w), outputHeight: Math.round(h) }, context);
1032
+ return { output };
1033
+ }
1034
+ }
1035
+ __decorate([
1036
+ prop({
1037
+ type: "image",
1038
+ default: {
1039
+ type: "image",
1040
+ uri: "",
1041
+ asset_id: null,
1042
+ data: null,
1043
+ metadata: null
1044
+ },
1045
+ title: "Image",
1046
+ description: "The image to resize."
1047
+ })
1048
+ ], ResizeNode.prototype, "image", void 0);
1049
+ __decorate([
1050
+ prop({
1051
+ type: "int",
1052
+ default: 512,
1053
+ title: "Width",
1054
+ description: "The target width.",
1055
+ min: 0,
1056
+ max: 8192
1057
+ })
1058
+ ], ResizeNode.prototype, "width", void 0);
1059
+ __decorate([
1060
+ prop({
1061
+ type: "int",
1062
+ default: 512,
1063
+ title: "Height",
1064
+ description: "The target height.",
1065
+ min: 0,
1066
+ max: 8192
1067
+ })
1068
+ ], ResizeNode.prototype, "height", void 0);
1069
+ function anchorOffset(anchor, canvasW, canvasH, srcW, srcH) {
1070
+ let x;
1071
+ let y;
1072
+ if (anchor.includes("left"))
1073
+ x = 0;
1074
+ else if (anchor.includes("right"))
1075
+ x = canvasW - srcW;
1076
+ else
1077
+ x = Math.floor((canvasW - srcW) / 2);
1078
+ if (anchor.includes("top"))
1079
+ y = 0;
1080
+ else if (anchor.includes("bottom"))
1081
+ y = canvasH - srcH;
1082
+ else
1083
+ y = Math.floor((canvasH - srcH) / 2);
1084
+ return [x, y];
1085
+ }
1086
+ export class CanvasResizeNode extends BaseNode {
1087
+ static nodeType = "nodetool.image.CanvasResize";
1088
+ static title = "Canvas Resize";
1089
+ static description = "Expand the canvas around an image without scaling its pixels.\n canvas, resize, pad, outpaint, expand, anchor";
1090
+ static metadataOutputTypes = {
1091
+ output: "image"
1092
+ };
1093
+ static inlineFields = [
1094
+ "mode",
1095
+ "anchor",
1096
+ "width",
1097
+ "height",
1098
+ "scale",
1099
+ "padding_unit",
1100
+ "top",
1101
+ "bottom",
1102
+ "left",
1103
+ "right",
1104
+ "color"
1105
+ ];
1106
+ static inputFields = ["image"];
1107
+ async process(context) {
1108
+ const image = this.image;
1109
+ const { width: srcW, height: srcH } = await decodeRgba(image, context);
1110
+ if (!srcW || !srcH)
1111
+ return { output: image };
1112
+ const mode = this.mode;
1113
+ const anchor = this.anchor;
1114
+ let canvasW;
1115
+ let canvasH;
1116
+ let offsetX;
1117
+ let offsetY;
1118
+ if (mode === "fixed") {
1119
+ canvasW = Math.max(1, Math.floor(this.width));
1120
+ canvasH = Math.max(1, Math.floor(this.height));
1121
+ [offsetX, offsetY] = anchorOffset(anchor, canvasW, canvasH, srcW, srcH);
1122
+ }
1123
+ else if (mode === "scale") {
1124
+ const scale = this.scale > 0 ? this.scale : 1;
1125
+ canvasW = Math.max(1, Math.round(srcW * scale));
1126
+ canvasH = Math.max(1, Math.round(srcH * scale));
1127
+ [offsetX, offsetY] = anchorOffset(anchor, canvasW, canvasH, srcW, srcH);
1128
+ }
1129
+ else {
1130
+ const unit = this.padding_unit;
1131
+ const toPx = (val, dim) => unit === "percent"
1132
+ ? Math.max(0, Math.round((dim * val) / 100))
1133
+ : Math.max(0, Math.floor(val));
1134
+ const left = toPx(this.left, srcW);
1135
+ const right = toPx(this.right, srcW);
1136
+ const top = toPx(this.top, srcH);
1137
+ const bottom = toPx(this.bottom, srcH);
1138
+ canvasW = Math.max(1, srcW + left + right);
1139
+ canvasH = Math.max(1, srcH + top + bottom);
1140
+ offsetX = left;
1141
+ offsetY = top;
1142
+ }
1143
+ const [cr, cg, cb, ca] = premultiplyVec4(colorValueToVec4(this.color, [0, 0, 0, 0]));
1144
+ const fillColor = d.vec4f(cr, cg, cb, ca);
1145
+ // When the requested canvas is smaller than the source on an axis, crop
1146
+ // the source to fit, anchored according to the anchor setting.
1147
+ let source = image;
1148
+ let baseW = srcW;
1149
+ let baseH = srcH;
1150
+ const cropW = Math.min(srcW, canvasW);
1151
+ const cropH = Math.min(srcH, canvasH);
1152
+ if (cropW < srcW || cropH < srcH) {
1153
+ const [cropOffX, cropOffY] = anchorOffset(anchor, srcW, srcH, cropW, cropH);
1154
+ const cropX = cropOffX;
1155
+ const cropY = cropOffY;
1156
+ source = await runShaderNode(transformCropV1, {
1157
+ originX: cropX / srcW,
1158
+ originY: cropY / srcH,
1159
+ width: cropW / srcW,
1160
+ height: cropH / srcH
1161
+ }, image, { outputWidth: cropW, outputHeight: cropH }, context);
1162
+ baseW = cropW;
1163
+ baseH = cropH;
1164
+ [offsetX, offsetY] = anchorOffset(anchor, canvasW, canvasH, baseW, baseH);
1165
+ }
1166
+ const leftPad = Math.max(0, offsetX);
1167
+ const topPad = Math.max(0, offsetY);
1168
+ const rightPad = Math.max(0, canvasW - baseW - offsetX);
1169
+ const bottomPad = Math.max(0, canvasH - baseH - offsetY);
1170
+ const output = await runShaderNode(transformPadV1, {
1171
+ left: leftPad / baseW,
1172
+ top: topPad / baseH,
1173
+ right: rightPad / baseW,
1174
+ bottom: bottomPad / baseH,
1175
+ color: fillColor
1176
+ }, source, {
1177
+ outputWidth: baseW + leftPad + rightPad,
1178
+ outputHeight: baseH + topPad + bottomPad
1179
+ }, context);
1180
+ return { output };
1181
+ }
1182
+ }
1183
+ __decorate([
1184
+ prop({
1185
+ type: "image",
1186
+ default: {
1187
+ type: "image",
1188
+ uri: "",
1189
+ asset_id: null,
1190
+ data: null,
1191
+ metadata: null
1192
+ },
1193
+ title: "Image",
1194
+ description: "The image to place on the expanded canvas."
1195
+ })
1196
+ ], CanvasResizeNode.prototype, "image", void 0);
1197
+ __decorate([
1198
+ prop({
1199
+ type: "enum",
1200
+ default: "padding",
1201
+ values: ["fixed", "scale", "padding"],
1202
+ title: "Mode",
1203
+ description: "How to resize the canvas."
1204
+ })
1205
+ ], CanvasResizeNode.prototype, "mode", void 0);
1206
+ __decorate([
1207
+ prop({
1208
+ type: "enum",
1209
+ default: "center",
1210
+ values: [
1211
+ "top-left",
1212
+ "top",
1213
+ "top-right",
1214
+ "left",
1215
+ "center",
1216
+ "right",
1217
+ "bottom-left",
1218
+ "bottom",
1219
+ "bottom-right"
1220
+ ],
1221
+ title: "Anchor",
1222
+ description: "Where to place the original image on the new canvas (fixed/scale modes)."
1223
+ })
1224
+ ], CanvasResizeNode.prototype, "anchor", void 0);
1225
+ __decorate([
1226
+ prop({
1227
+ type: "int",
1228
+ default: 512,
1229
+ title: "Width",
1230
+ description: "Target canvas width (fixed mode).",
1231
+ min: 1,
1232
+ max: 8192
1233
+ })
1234
+ ], CanvasResizeNode.prototype, "width", void 0);
1235
+ __decorate([
1236
+ prop({
1237
+ type: "int",
1238
+ default: 512,
1239
+ title: "Height",
1240
+ description: "Target canvas height (fixed mode).",
1241
+ min: 1,
1242
+ max: 8192
1243
+ })
1244
+ ], CanvasResizeNode.prototype, "height", void 0);
1245
+ __decorate([
1246
+ prop({
1247
+ type: "float",
1248
+ default: 1.25,
1249
+ title: "Scale",
1250
+ description: "Canvas scale factor relative to the source image.",
1251
+ min: 0.01,
1252
+ max: 10
1253
+ })
1254
+ ], CanvasResizeNode.prototype, "scale", void 0);
1255
+ __decorate([
1256
+ prop({
1257
+ type: "enum",
1258
+ default: "px",
1259
+ values: ["px", "percent"],
1260
+ title: "Padding unit",
1261
+ description: "Whether padding values are pixels or percent of source size."
1262
+ })
1263
+ ], CanvasResizeNode.prototype, "padding_unit", void 0);
1264
+ __decorate([
1265
+ prop({
1266
+ type: "float",
1267
+ default: 0,
1268
+ title: "Top",
1269
+ description: "Padding above the image.",
1270
+ min: 0,
1271
+ max: 8192
1272
+ })
1273
+ ], CanvasResizeNode.prototype, "top", void 0);
1274
+ __decorate([
1275
+ prop({
1276
+ type: "float",
1277
+ default: 0,
1278
+ title: "Bottom",
1279
+ description: "Padding below the image.",
1280
+ min: 0,
1281
+ max: 8192
1282
+ })
1283
+ ], CanvasResizeNode.prototype, "bottom", void 0);
1284
+ __decorate([
1285
+ prop({
1286
+ type: "float",
1287
+ default: 0,
1288
+ title: "Left",
1289
+ description: "Padding to the left of the image.",
1290
+ min: 0,
1291
+ max: 8192
1292
+ })
1293
+ ], CanvasResizeNode.prototype, "left", void 0);
1294
+ __decorate([
1295
+ prop({
1296
+ type: "float",
1297
+ default: 0,
1298
+ title: "Right",
1299
+ description: "Padding to the right of the image.",
1300
+ min: 0,
1301
+ max: 8192
1302
+ })
1303
+ ], CanvasResizeNode.prototype, "right", void 0);
1304
+ __decorate([
1305
+ prop({
1306
+ type: "color",
1307
+ default: { type: "color", value: "#00000000" },
1308
+ title: "Fill Color",
1309
+ description: "Background color for the expanded canvas area."
1310
+ })
1311
+ ], CanvasResizeNode.prototype, "color", void 0);
1312
+ export class CropNode extends BaseNode {
1313
+ static nodeType = "nodetool.image.Crop";
1314
+ static title = "Crop";
1315
+ static description = "Crop an image to specified coordinates.\n image, crop";
1316
+ static metadataOutputTypes = {
1317
+ output: "image"
1318
+ };
1319
+ static inlineFields = [];
1320
+ static inputFields = ["image"];
1321
+ async process(context) {
1322
+ const image = this.image;
1323
+ // Crop is defined in pixels; the GPU crop shader samples a normalized-UV
1324
+ // sub-rectangle, so resolve source dims first to convert px → UV.
1325
+ const { width: srcW, height: srcH } = await decodeRgba(image, context);
1326
+ if (!srcW || !srcH)
1327
+ return { output: image };
1328
+ const left = Math.max(0, Math.min(srcW - 1, this.left));
1329
+ const top = Math.max(0, Math.min(srcH - 1, this.top));
1330
+ const right = Math.max(left + 1, Math.min(srcW, this.right));
1331
+ const bottom = Math.max(top + 1, Math.min(srcH, this.bottom));
1332
+ const cropW = right - left;
1333
+ const cropH = bottom - top;
1334
+ const output = await runShaderNode(transformCropV1, {
1335
+ originX: left / srcW,
1336
+ originY: top / srcH,
1337
+ width: cropW / srcW,
1338
+ height: cropH / srcH
1339
+ }, image, { outputWidth: cropW, outputHeight: cropH }, context);
1340
+ return { output };
1341
+ }
1342
+ }
1343
+ __decorate([
1344
+ prop({
1345
+ type: "image",
1346
+ default: {
1347
+ type: "image",
1348
+ uri: "",
1349
+ asset_id: null,
1350
+ data: null,
1351
+ metadata: null
1352
+ },
1353
+ title: "Image",
1354
+ description: "The image to crop."
1355
+ })
1356
+ ], CropNode.prototype, "image", void 0);
1357
+ __decorate([
1358
+ prop({
1359
+ type: "int",
1360
+ default: 0,
1361
+ title: "Left",
1362
+ description: "The left coordinate.",
1363
+ min: 0,
1364
+ max: 8192
1365
+ })
1366
+ ], CropNode.prototype, "left", void 0);
1367
+ __decorate([
1368
+ prop({
1369
+ type: "int",
1370
+ default: 0,
1371
+ title: "Top",
1372
+ description: "The top coordinate.",
1373
+ min: 0,
1374
+ max: 8192
1375
+ })
1376
+ ], CropNode.prototype, "top", void 0);
1377
+ __decorate([
1378
+ prop({
1379
+ type: "int",
1380
+ default: 512,
1381
+ title: "Right",
1382
+ description: "The right coordinate.",
1383
+ min: 0,
1384
+ max: 8192
1385
+ })
1386
+ ], CropNode.prototype, "right", void 0);
1387
+ __decorate([
1388
+ prop({
1389
+ type: "int",
1390
+ default: 512,
1391
+ title: "Bottom",
1392
+ description: "The bottom coordinate.",
1393
+ min: 0,
1394
+ max: 8192
1395
+ })
1396
+ ], CropNode.prototype, "bottom", void 0);
1397
+ export class FitNode extends BaseNode {
1398
+ static nodeType = "nodetool.image.Fit";
1399
+ static title = "Fit";
1400
+ static deprecated = true;
1401
+ static replacedBy = RESIZE_IMAGE_NODE_TYPE;
1402
+ static description = deprecatedResizeDescription("Resize an image to fit within specified dimensions while preserving aspect ratio.\n image, resize, fit");
1403
+ static metadataOutputTypes = {
1404
+ output: "image"
1405
+ };
1406
+ static inlineFields = [];
1407
+ static inputFields = ["image"];
1408
+ async process(context) {
1409
+ const image = this.image;
1410
+ const targetW = Math.max(1, this.width);
1411
+ const targetH = Math.max(1, this.height);
1412
+ const { width: srcW, height: srcH } = await decodeRgba(image, context);
1413
+ if (!srcW || !srcH)
1414
+ return { output: image };
1415
+ // Fit inside the target box, preserving aspect ratio (never upscale past
1416
+ // the box on either axis).
1417
+ const ratio = Math.min(targetW / srcW, targetH / srcH);
1418
+ const output = await runShaderNode(transformResizeV1, { mode: 1 }, image, {
1419
+ outputWidth: Math.max(1, Math.round(srcW * ratio)),
1420
+ outputHeight: Math.max(1, Math.round(srcH * ratio))
1421
+ }, context);
1422
+ return { output };
1423
+ }
1424
+ }
1425
+ __decorate([
1426
+ prop({
1427
+ type: "image",
1428
+ default: {
1429
+ type: "image",
1430
+ uri: "",
1431
+ asset_id: null,
1432
+ data: null,
1433
+ metadata: null
1434
+ },
1435
+ title: "Image",
1436
+ description: "The image to fit."
1437
+ })
1438
+ ], FitNode.prototype, "image", void 0);
1439
+ __decorate([
1440
+ prop({
1441
+ type: "int",
1442
+ default: 512,
1443
+ title: "Width",
1444
+ description: "Width to fit to.",
1445
+ min: 1,
1446
+ max: 8192
1447
+ })
1448
+ ], FitNode.prototype, "width", void 0);
1449
+ __decorate([
1450
+ prop({
1451
+ type: "int",
1452
+ default: 512,
1453
+ title: "Height",
1454
+ description: "Height to fit to.",
1455
+ min: 1,
1456
+ max: 8192
1457
+ })
1458
+ ], FitNode.prototype, "height", void 0);
1459
+ export class TextToImageNode extends BaseNode {
1460
+ static nodeType = "nodetool.image.TextToImage";
1461
+ static body = "content_card";
1462
+ static title = "Text To Image";
1463
+ static description = "Generate images from text prompts using any supported image provider. Automatically routes to the appropriate backend (HuggingFace, FAL, MLX).\n image, generation, AI, text-to-image, t2i";
1464
+ static metadataOutputTypes = {
1465
+ output: "image"
1466
+ };
1467
+ static inlineFields = [];
1468
+ static inputFields = ["prompt"];
1469
+ static autoSaveAsset = true;
1470
+ async process(context) {
1471
+ const prompt = this.prompt;
1472
+ const aspectRatio = this.aspect_ratio;
1473
+ const resolution = this.resolution;
1474
+ const { width, height } = resolveImageSize(resolution, aspectRatio);
1475
+ const { providerId, modelId } = getModelConfig(this.serialize());
1476
+ if (!hasProviderSupport(context, providerId, modelId)) {
1477
+ throw new Error("No provider available for text-to-image generation.");
1478
+ }
1479
+ const output = (await context.runProviderPrediction({
1480
+ provider: providerId,
1481
+ capability: "text_to_image",
1482
+ model: modelId,
1483
+ params: {
1484
+ prompt,
1485
+ width,
1486
+ height,
1487
+ aspect_ratio: aspectRatio,
1488
+ resolution,
1489
+ negative_prompt: this.negative_prompt,
1490
+ entities: await resolveEntities(this.entities, context)
1491
+ }
1492
+ }));
1493
+ const meta = await metadataFor(output);
1494
+ return {
1495
+ output: imageRef(output, {
1496
+ mimeType: inferImageMime(undefined, output),
1497
+ width: meta.width ?? width,
1498
+ height: meta.height ?? height
1499
+ })
1500
+ };
1501
+ }
1502
+ }
1503
+ __decorate([
1504
+ prop({
1505
+ type: "image_model",
1506
+ default: {
1507
+ type: "image_model",
1508
+ provider: "fal_ai",
1509
+ id: "fal-ai/flux/schnell",
1510
+ name: "FLUX.1 Schnell",
1511
+ path: null,
1512
+ supported_tasks: []
1513
+ },
1514
+ title: "Model",
1515
+ description: "The image generation model to use"
1516
+ })
1517
+ ], TextToImageNode.prototype, "model", void 0);
1518
+ __decorate([
1519
+ prop({
1520
+ type: "str",
1521
+ default: "A cat holding a sign that says hello world",
1522
+ title: "Prompt",
1523
+ description: "Text prompt describing the desired image"
1524
+ })
1525
+ ], TextToImageNode.prototype, "prompt", void 0);
1526
+ __decorate([
1527
+ prop({
1528
+ type: "str",
1529
+ default: "",
1530
+ title: "Negative Prompt",
1531
+ description: "Text prompt describing what to avoid in the image"
1532
+ })
1533
+ ], TextToImageNode.prototype, "negative_prompt", void 0);
1534
+ __decorate([
1535
+ prop({
1536
+ type: "list[entity]",
1537
+ default: [],
1538
+ title: "Entities",
1539
+ description: "Consistency entities (characters, styles, locations) whose descriptors are injected into the prompt"
1540
+ })
1541
+ ], TextToImageNode.prototype, "entities", void 0);
1542
+ __decorate([
1543
+ prop({
1544
+ type: "str",
1545
+ default: "1:1",
1546
+ title: "Aspect Ratio",
1547
+ description: "Aspect ratio of the generated image",
1548
+ values: IMAGE_ASPECT_RATIO_VALUES,
1549
+ json_schema_extra: { type: "media_aspect_ratio_image" }
1550
+ })
1551
+ ], TextToImageNode.prototype, "aspect_ratio", void 0);
1552
+ __decorate([
1553
+ prop({
1554
+ type: "str",
1555
+ default: "1K",
1556
+ title: "Resolution",
1557
+ description: "Output resolution (short edge in pixels)",
1558
+ values: IMAGE_RESOLUTION_VALUES,
1559
+ json_schema_extra: { type: "media_resolution_image" }
1560
+ })
1561
+ ], TextToImageNode.prototype, "resolution", void 0);
1562
+ export class ImageToImageNode extends BaseNode {
1563
+ static nodeType = "nodetool.image.ImageToImage";
1564
+ static body = "content_card";
1565
+ static title = "Image To Image";
1566
+ static description = "Transform images using text prompts with any supported image provider. Automatically routes to the appropriate backend (HuggingFace, FAL, MLX).\n image, transformation, AI, image-to-image, i2i";
1567
+ static metadataOutputTypes = {
1568
+ output: "image"
1569
+ };
1570
+ static inlineFields = [];
1571
+ static inputFields = ["prompt", "image"];
1572
+ static autoSaveAsset = true;
1573
+ async process(context) {
1574
+ let images = normalizeImageList(this.image);
1575
+ let prompt = this.prompt;
1576
+ // Inline asset mentions (e.g. from the Prompt composer's @-mention) carry
1577
+ // an `asset://<id>.<ext>` image reference in the prompt string. Text tasks
1578
+ // expand these into image inputs; do the same here via the shared mapper —
1579
+ // route the first referenced image into the transform input when none is
1580
+ // wired in, and strip the mention out of the textual instruction.
1581
+ const overrides = await mapPromptAssetsToInputs([{ name: "prompt", value: prompt }], [
1582
+ {
1583
+ name: "image",
1584
+ kind: "image",
1585
+ hasSource: images.some(imageRefHasSource)
1586
+ }
1587
+ ], context);
1588
+ if (isString(overrides.prompt))
1589
+ prompt = overrides.prompt;
1590
+ if (overrides.image && images.length === 0) {
1591
+ images = [overrides.image];
1592
+ }
1593
+ const bytesList = (await Promise.all(images.map((img) => imageBytesAsync(img, context)))).filter((b) => b.length > 0);
1594
+ // Entities may supply the source images: their reference images are
1595
+ // appended to the list at the provider layer, so an empty wired input is
1596
+ // fine as long as an entity carries an image.
1597
+ const entities = Array.isArray(this.entities) ? this.entities : [];
1598
+ const entityHasImage = entities.some((e) => !!e?.image || (e?.reference_images?.length ?? 0) > 0);
1599
+ if (bytesList.length === 0 && !entityHasImage) {
1600
+ throw new Error("The input image is empty.");
1601
+ }
1602
+ const aspectRatio = this.aspect_ratio;
1603
+ const resolution = this.resolution;
1604
+ const { width, height } = resolveImageSize(resolution, aspectRatio);
1605
+ const { providerId, modelId } = getModelConfig(this.serialize());
1606
+ if (!hasProviderSupport(context, providerId, modelId)) {
1607
+ throw new Error("No provider available for image-to-image generation.");
1608
+ }
1609
+ const output = (await context.runProviderPrediction({
1610
+ provider: providerId,
1611
+ capability: "image_to_image",
1612
+ model: modelId,
1613
+ params: {
1614
+ images: bytesList,
1615
+ prompt,
1616
+ negative_prompt: this.negative_prompt,
1617
+ entities,
1618
+ target_width: width,
1619
+ target_height: height,
1620
+ aspect_ratio: aspectRatio,
1621
+ resolution,
1622
+ strength: this.strength,
1623
+ scheduler: this.scheduler
1624
+ }
1625
+ }));
1626
+ const meta = await metadataFor(output);
1627
+ // The output is freshly generated content — do not carry the source image's
1628
+ // uri onto it (a stale uri shadows `data` wherever a uri is preferred, so
1629
+ // the preview would render the input, not the result). Infer mime from the
1630
+ // output bytes alone.
1631
+ return {
1632
+ output: imageRef(output, {
1633
+ mimeType: inferImageMime(undefined, output),
1634
+ width: meta.width,
1635
+ height: meta.height
1636
+ })
1637
+ };
1638
+ }
1639
+ }
1640
+ __decorate([
1641
+ prop({
1642
+ type: "image_model",
1643
+ default: {
1644
+ type: "image_model",
1645
+ provider: "fal_ai",
1646
+ id: "fal-ai/flux/dev",
1647
+ name: "FLUX.1 Dev",
1648
+ path: null,
1649
+ supported_tasks: []
1650
+ },
1651
+ title: "Model",
1652
+ description: "The image generation model to use"
1653
+ })
1654
+ ], ImageToImageNode.prototype, "model", void 0);
1655
+ __decorate([
1656
+ prop({
1657
+ type: "list[image]",
1658
+ default: [],
1659
+ title: "Images",
1660
+ description: "Input image(s) to transform. The first image is the primary subject; additional images are used as references by providers that support multi-image editing."
1661
+ })
1662
+ ], ImageToImageNode.prototype, "image", void 0);
1663
+ __decorate([
1664
+ prop({
1665
+ type: "str",
1666
+ default: "A photorealistic version of the input image",
1667
+ title: "Prompt",
1668
+ description: "Text prompt describing the desired transformation"
1669
+ })
1670
+ ], ImageToImageNode.prototype, "prompt", void 0);
1671
+ __decorate([
1672
+ prop({
1673
+ type: "str",
1674
+ default: "",
1675
+ title: "Negative Prompt",
1676
+ description: "Text prompt describing what to avoid"
1677
+ })
1678
+ ], ImageToImageNode.prototype, "negative_prompt", void 0);
1679
+ __decorate([
1680
+ prop({
1681
+ type: "list[dict]",
1682
+ default: [],
1683
+ title: "Entities",
1684
+ description: "Consistency entities (characters, styles, locations) whose descriptors are injected into the prompt and whose reference images are appended to the input images"
1685
+ })
1686
+ ], ImageToImageNode.prototype, "entities", void 0);
1687
+ __decorate([
1688
+ prop({
1689
+ type: "float",
1690
+ default: 0.65,
1691
+ title: "Strength",
1692
+ description: "How much to transform the input image (subtle = minor edit, strong = major edit)",
1693
+ values: IMAGE_EDIT_STRENGTH_VALUES,
1694
+ json_schema_extra: { type: "media_strength" }
1695
+ })
1696
+ ], ImageToImageNode.prototype, "strength", void 0);
1697
+ __decorate([
1698
+ prop({
1699
+ type: "str",
1700
+ default: "1:1",
1701
+ title: "Aspect Ratio",
1702
+ description: "Aspect ratio of the output image",
1703
+ values: IMAGE_ASPECT_RATIO_VALUES,
1704
+ json_schema_extra: { type: "media_aspect_ratio_image" }
1705
+ })
1706
+ ], ImageToImageNode.prototype, "aspect_ratio", void 0);
1707
+ __decorate([
1708
+ prop({
1709
+ type: "str",
1710
+ default: "1K",
1711
+ title: "Resolution",
1712
+ description: "Output resolution (short edge in pixels)",
1713
+ values: IMAGE_RESOLUTION_VALUES,
1714
+ json_schema_extra: { type: "media_resolution_image" }
1715
+ })
1716
+ ], ImageToImageNode.prototype, "resolution", void 0);
1717
+ __decorate([
1718
+ prop({
1719
+ type: "str",
1720
+ default: "",
1721
+ title: "Scheduler",
1722
+ description: "Scheduler to use (provider-specific)"
1723
+ })
1724
+ ], ImageToImageNode.prototype, "scheduler", void 0);
1725
+ export class RotateAndFlipNode extends BaseNode {
1726
+ static nodeType = "nodetool.image.RotateAndFlip";
1727
+ static title = "Rotate & Flip";
1728
+ static description = "Rotate and/or flip an image in a single step.\n image, rotate, flip, mirror, orientation, transform";
1729
+ static metadataOutputTypes = {
1730
+ output: "image"
1731
+ };
1732
+ static inlineFields = [];
1733
+ static inputFields = ["image"];
1734
+ async process(context) {
1735
+ const image = this.image;
1736
+ const angle = this.angle;
1737
+ const flipH = !!this.flip_horizontal;
1738
+ const flipV = !!this.flip_vertical;
1739
+ const { rgba, width: srcW, height: srcH } = await decodeRgba(image, context);
1740
+ if (!srcW || !srcH)
1741
+ return { output: image };
1742
+ const norm = ((angle % 360) + 360) % 360;
1743
+ if (norm === 0 && !flipH && !flipV) {
1744
+ return { output: rawRgbaImageRef(rgba, srcW, srcH) };
1745
+ }
1746
+ let current = image;
1747
+ const curW = srcW;
1748
+ const curH = srcH;
1749
+ // Mirror first (output is same size as source).
1750
+ if (flipH || flipV) {
1751
+ const axes = (flipH ? 1 : 0) + (flipV ? 2 : 0); // 1 H, 2 V, 3 both
1752
+ current = await runShaderNode(transformMirrorV1, { axes }, current, {}, context);
1753
+ }
1754
+ if (norm !== 0) {
1755
+ if (norm % 90 === 0) {
1756
+ const turns = (norm / 90) % 4; // 1=90°, 2=180°, 3=270° clockwise
1757
+ const swap = turns === 1 || turns === 3;
1758
+ const outW = swap ? curH : curW;
1759
+ const outH = swap ? curW : curH;
1760
+ current = await runShaderNode(transformRotate90V1, { turns }, current, { outputWidth: outW, outputHeight: outH }, context);
1761
+ }
1762
+ else {
1763
+ // Arbitrary angle: expand the canvas to the rotated bounding box and
1764
+ // feed the affine shader the UV-space inverse matrix (output uv → source
1765
+ // uv) for a clockwise rotation about the centre.
1766
+ const rad = (norm * Math.PI) / 180;
1767
+ const cos = Math.cos(rad);
1768
+ const sin = Math.sin(rad);
1769
+ const outW = Math.max(1, Math.round(Math.abs(curW * cos) + Math.abs(curH * sin)));
1770
+ const outH = Math.max(1, Math.round(Math.abs(curW * sin) + Math.abs(curH * cos)));
1771
+ current = await runShaderNode(transformAffineV1, {
1772
+ m00: (cos * outW) / curW,
1773
+ m01: (sin * outH) / curW,
1774
+ tx: (curW / 2 - (cos * outW) / 2 - (sin * outH) / 2) / curW,
1775
+ m10: (-sin * outW) / curH,
1776
+ m11: (cos * outH) / curH,
1777
+ ty: (curH / 2 + (sin * outW) / 2 - (cos * outH) / 2) / curH
1778
+ }, current, { outputWidth: outW, outputHeight: outH }, context);
1779
+ }
1780
+ }
1781
+ return { output: current };
1782
+ }
1783
+ }
1784
+ __decorate([
1785
+ prop({
1786
+ type: "image",
1787
+ default: {
1788
+ type: "image",
1789
+ uri: "",
1790
+ asset_id: null,
1791
+ data: null,
1792
+ metadata: null
1793
+ },
1794
+ title: "Image",
1795
+ description: "The image to rotate and flip."
1796
+ })
1797
+ ], RotateAndFlipNode.prototype, "image", void 0);
1798
+ __decorate([
1799
+ prop({
1800
+ type: "float",
1801
+ default: 0,
1802
+ title: "Angle",
1803
+ description: "Rotation angle in degrees (clockwise).",
1804
+ min: -360,
1805
+ max: 360
1806
+ })
1807
+ ], RotateAndFlipNode.prototype, "angle", void 0);
1808
+ __decorate([
1809
+ prop({
1810
+ type: "bool",
1811
+ default: false,
1812
+ title: "Flip Horizontal",
1813
+ description: "Mirror left/right."
1814
+ })
1815
+ ], RotateAndFlipNode.prototype, "flip_horizontal", void 0);
1816
+ __decorate([
1817
+ prop({
1818
+ type: "bool",
1819
+ default: false,
1820
+ title: "Flip Vertical",
1821
+ description: "Mirror top/bottom."
1822
+ })
1823
+ ], RotateAndFlipNode.prototype, "flip_vertical", void 0);
1824
+ export class ChannelsNode extends BaseNode {
1825
+ static nodeType = "nodetool.image.Channels";
1826
+ static title = "Channels";
1827
+ static description = "Extract a single channel from an image as a grayscale preview.\n image, channel, red, green, blue, alpha, luminance";
1828
+ static metadataOutputTypes = {
1829
+ output: "image"
1830
+ };
1831
+ static inlineFields = [];
1832
+ static inputFields = ["image"];
1833
+ async process(context) {
1834
+ const image = this.image;
1835
+ const channel = this.channel;
1836
+ if (channel === "luminance") {
1837
+ return {
1838
+ output: await runShaderNode(colorGrayscaleV1, { amount: 1 }, image, {}, context)
1839
+ };
1840
+ }
1841
+ const channelIndex = {
1842
+ red: 0,
1843
+ green: 1,
1844
+ blue: 2,
1845
+ alpha: 3
1846
+ };
1847
+ const from = channelIndex[channel];
1848
+ if (from === undefined) {
1849
+ // Unsupported channel — pass the source through unchanged.
1850
+ const { rgba, width, height } = await decodeRgba(image, context);
1851
+ return { output: width ? rawRgbaImageRef(rgba, width, height) : image };
1852
+ }
1853
+ // Broadcast the chosen channel onto R/G/B for a grayscale preview, keep alpha.
1854
+ const output = await runShaderNode(colorChannelShuffleV1, { rFrom: from, gFrom: from, bFrom: from, aFrom: 3 }, image, {}, context);
1855
+ return { output };
1856
+ }
1857
+ }
1858
+ __decorate([
1859
+ prop({
1860
+ type: "image",
1861
+ default: {
1862
+ type: "image",
1863
+ uri: "",
1864
+ asset_id: null,
1865
+ data: null,
1866
+ metadata: null
1867
+ },
1868
+ title: "Image",
1869
+ description: "The image to extract a channel from."
1870
+ })
1871
+ ], ChannelsNode.prototype, "image", void 0);
1872
+ __decorate([
1873
+ prop({
1874
+ type: "str",
1875
+ default: "luminance",
1876
+ title: "Channel",
1877
+ description: "Which channel to extract.",
1878
+ values: ["red", "green", "blue", "alpha", "luminance"]
1879
+ })
1880
+ ], ChannelsNode.prototype, "channel", void 0);
1881
+ export class BlurNode extends BaseNode {
1882
+ static nodeType = "nodetool.image.Blur";
1883
+ static title = "Blur";
1884
+ static description = "Blur an image — Box, Gaussian, or horizontal Motion variants.\n image, blur, gaussian, box, motion, filter";
1885
+ static metadataOutputTypes = {
1886
+ output: "image"
1887
+ };
1888
+ static inlineFields = [];
1889
+ static inputFields = ["image"];
1890
+ async process(context) {
1891
+ const image = this.image;
1892
+ const size = Math.max(0, Math.min(100, Math.round(this.size)));
1893
+ const blurType = this.blur_type;
1894
+ if (size <= 0) {
1895
+ const { rgba, width, height } = await decodeRgba(image, context);
1896
+ return { output: width ? rawRgbaImageRef(rgba, width, height) : image };
1897
+ }
1898
+ // Map the 0–100 "size" onto the gaussian shader's 0–20px kernel radius;
1899
+ // sigma tracks radius for a natural falloff.
1900
+ const radius = Math.min(20, Math.max(1, size / 5));
1901
+ const sigma = Math.max(0.5, radius * 0.6);
1902
+ if (blurType === "motion") {
1903
+ // Horizontal directional blur (single-axis gaussian).
1904
+ const output = await runShaderNode(blurGaussianV1, { radius, sigma, direction: d.vec2f(1, 0) }, image, {}, context);
1905
+ return { output };
1906
+ }
1907
+ // gaussian + box → isotropic separable (horizontal then vertical) blur.
1908
+ const output = await runRecipeNode(filtersBlurSeparableV1, { radius, sigma }, image, {}, context);
1909
+ return { output };
1910
+ }
1911
+ }
1912
+ __decorate([
1913
+ prop({
1914
+ type: "image",
1915
+ default: {
1916
+ type: "image",
1917
+ uri: "",
1918
+ asset_id: null,
1919
+ data: null,
1920
+ metadata: null
1921
+ },
1922
+ title: "Image",
1923
+ description: "The image to blur."
1924
+ })
1925
+ ], BlurNode.prototype, "image", void 0);
1926
+ __decorate([
1927
+ prop({
1928
+ type: "str",
1929
+ default: "gaussian",
1930
+ title: "Type",
1931
+ description: "Blur algorithm: gaussian (smooth), box (boxcar), motion (horizontal streak).",
1932
+ values: ["gaussian", "box", "motion"]
1933
+ })
1934
+ ], BlurNode.prototype, "blur_type", void 0);
1935
+ __decorate([
1936
+ prop({
1937
+ type: "int",
1938
+ default: 5,
1939
+ title: "Size",
1940
+ description: "Blur amount (0 = none, 100 = max).",
1941
+ min: 0,
1942
+ max: 100
1943
+ })
1944
+ ], BlurNode.prototype, "size", void 0);
1945
+ export class LevelsNode extends BaseNode {
1946
+ static nodeType = "nodetool.image.Levels";
1947
+ static title = "Levels";
1948
+ static description = "Adjust input black point, gamma, and white point per RGB channel.\n image, levels, color, tone, curves";
1949
+ static metadataOutputTypes = {
1950
+ output: "image"
1951
+ };
1952
+ static inlineFields = [];
1953
+ static inputFields = ["image"];
1954
+ async process(context) {
1955
+ const image = this.image;
1956
+ const clamp255 = (n) => Math.max(0, Math.min(255, Math.round(n)));
1957
+ const clampGamma = (n) => Math.max(0.01, Math.min(10, n));
1958
+ const rBlack = clamp255(this.r_black);
1959
+ const rWhite = clamp255(this.r_white);
1960
+ const rGamma = clampGamma(this.r_gamma);
1961
+ const gBlack = clamp255(this.g_black);
1962
+ const gWhite = clamp255(this.g_white);
1963
+ const gGamma = clampGamma(this.g_gamma);
1964
+ const bBlack = clamp255(this.b_black);
1965
+ const bWhite = clamp255(this.b_white);
1966
+ const bGamma = clampGamma(this.b_gamma);
1967
+ const { rgba, width, height } = await decodeRgba(image, context);
1968
+ if (!width || !height)
1969
+ return { output: image };
1970
+ const identity = rBlack === 0 && rWhite === 255 && rGamma === 1 &&
1971
+ gBlack === 0 && gWhite === 255 && gGamma === 1 &&
1972
+ bBlack === 0 && bWhite === 255 && bGamma === 1;
1973
+ if (identity) {
1974
+ return { output: rawRgbaImageRef(rgba, width, height) };
1975
+ }
1976
+ // The levels shader works in [0,1]; the node authors black/white in 0–255.
1977
+ const output = await runShaderNode(colorLevelsV1, {
1978
+ rBlack: rBlack / 255,
1979
+ rGamma,
1980
+ rWhite: rWhite / 255,
1981
+ gBlack: gBlack / 255,
1982
+ gGamma,
1983
+ gWhite: gWhite / 255,
1984
+ bBlack: bBlack / 255,
1985
+ bGamma,
1986
+ bWhite: bWhite / 255
1987
+ }, image, {}, context);
1988
+ return { output };
1989
+ }
1990
+ }
1991
+ __decorate([
1992
+ prop({
1993
+ type: "image",
1994
+ default: {
1995
+ type: "image",
1996
+ uri: "",
1997
+ asset_id: null,
1998
+ data: null,
1999
+ metadata: null
2000
+ },
2001
+ title: "Image",
2002
+ description: "The image to adjust."
2003
+ })
2004
+ ], LevelsNode.prototype, "image", void 0);
2005
+ __decorate([
2006
+ prop({
2007
+ type: "int",
2008
+ default: 0,
2009
+ title: "Red Black",
2010
+ description: "Red channel input black point (0–255).",
2011
+ min: 0,
2012
+ max: 255
2013
+ })
2014
+ ], LevelsNode.prototype, "r_black", void 0);
2015
+ __decorate([
2016
+ prop({
2017
+ type: "float",
2018
+ default: 1,
2019
+ title: "Red Gamma",
2020
+ description: "Red channel gamma (0.01–10).",
2021
+ min: 0.01,
2022
+ max: 10
2023
+ })
2024
+ ], LevelsNode.prototype, "r_gamma", void 0);
2025
+ __decorate([
2026
+ prop({
2027
+ type: "int",
2028
+ default: 255,
2029
+ title: "Red White",
2030
+ description: "Red channel input white point (0–255).",
2031
+ min: 0,
2032
+ max: 255
2033
+ })
2034
+ ], LevelsNode.prototype, "r_white", void 0);
2035
+ __decorate([
2036
+ prop({
2037
+ type: "int",
2038
+ default: 0,
2039
+ title: "Green Black",
2040
+ description: "Green channel input black point (0–255).",
2041
+ min: 0,
2042
+ max: 255
2043
+ })
2044
+ ], LevelsNode.prototype, "g_black", void 0);
2045
+ __decorate([
2046
+ prop({
2047
+ type: "float",
2048
+ default: 1,
2049
+ title: "Green Gamma",
2050
+ description: "Green channel gamma (0.01–10).",
2051
+ min: 0.01,
2052
+ max: 10
2053
+ })
2054
+ ], LevelsNode.prototype, "g_gamma", void 0);
2055
+ __decorate([
2056
+ prop({
2057
+ type: "int",
2058
+ default: 255,
2059
+ title: "Green White",
2060
+ description: "Green channel input white point (0–255).",
2061
+ min: 0,
2062
+ max: 255
2063
+ })
2064
+ ], LevelsNode.prototype, "g_white", void 0);
2065
+ __decorate([
2066
+ prop({
2067
+ type: "int",
2068
+ default: 0,
2069
+ title: "Blue Black",
2070
+ description: "Blue channel input black point (0–255).",
2071
+ min: 0,
2072
+ max: 255
2073
+ })
2074
+ ], LevelsNode.prototype, "b_black", void 0);
2075
+ __decorate([
2076
+ prop({
2077
+ type: "float",
2078
+ default: 1,
2079
+ title: "Blue Gamma",
2080
+ description: "Blue channel gamma (0.01–10).",
2081
+ min: 0.01,
2082
+ max: 10
2083
+ })
2084
+ ], LevelsNode.prototype, "b_gamma", void 0);
2085
+ __decorate([
2086
+ prop({
2087
+ type: "int",
2088
+ default: 255,
2089
+ title: "Blue White",
2090
+ description: "Blue channel input white point (0–255).",
2091
+ min: 0,
2092
+ max: 255
2093
+ })
2094
+ ], LevelsNode.prototype, "b_white", void 0);
2095
+ function compositorLayerTransform(raw) {
2096
+ if (!isObjectLike(raw))
2097
+ return undefined;
2098
+ const r = raw;
2099
+ const num = (v, fallback) => isFiniteNumber(v) ? v : fallback;
2100
+ // A persisted transform must at least pin a position; scale defaults to 1.
2101
+ if (!isNumber(r.x) || !isNumber(r.y))
2102
+ return undefined;
2103
+ return {
2104
+ x: r.x,
2105
+ y: r.y,
2106
+ scaleX: num(r.scaleX, 1),
2107
+ scaleY: num(r.scaleY, 1),
2108
+ rotation: num(r.rotation, 0)
2109
+ };
2110
+ }
2111
+ function compositorLayerState(raw) {
2112
+ const r = (raw ?? {});
2113
+ const opacity = isNumber(r.opacity) ? Math.max(0, Math.min(1, r.opacity)) : 1;
2114
+ const visible = r.visible === undefined ? true : !!r.visible;
2115
+ // Stored values are canonical blend modes; the legacy "over" name still
2116
+ // resolves to "normal" via coerceBlendMode.
2117
+ return {
2118
+ opacity,
2119
+ blend_mode: coerceBlendMode(r.blend_mode),
2120
+ visible,
2121
+ transform: compositorLayerTransform(r.transform)
2122
+ };
2123
+ }
2124
+ export class CompositorNode extends BaseNode {
2125
+ static nodeType = "nodetool.image.Compositor";
2126
+ static title = "Compositor";
2127
+ static description = "Composite multiple image layers with per-layer opacity and blend mode.\n image, compositor, blend, layers, mask";
2128
+ static metadataOutputTypes = {
2129
+ output: "image"
2130
+ };
2131
+ static supportsDynamicInputs = true;
2132
+ static inlineFields = [];
2133
+ static inputFields = [];
2134
+ async process(context) {
2135
+ const layerStates = Array.isArray(this.layers) ? this.layers : [];
2136
+ // Collect dynamic image_N inputs, sorted ascending by N. Position in
2137
+ // that sorted list is the index into `layers` for per-layer state.
2138
+ const collected = [];
2139
+ for (const [key, value] of this.dynamicProps) {
2140
+ const m = /^image_(\d+)$/.exec(key);
2141
+ if (!m || !isObjectLike(value))
2142
+ continue;
2143
+ collected.push({ index: Number(m[1]), image: value });
2144
+ }
2145
+ collected.sort((a, b) => a.index - b.index);
2146
+ const inputs = collected.map((c, i) => ({
2147
+ ...c,
2148
+ state: compositorLayerState(layerStates[i])
2149
+ }));
2150
+ const visible = inputs.filter((l) => l.state.visible && l.state.opacity > 0);
2151
+ if (visible.length === 0) {
2152
+ return {
2153
+ output: imageRef(new Uint8Array(), {
2154
+ uri: "",
2155
+ width: undefined,
2156
+ height: undefined
2157
+ })
2158
+ };
2159
+ }
2160
+ // Decode each visible layer to straight-alpha RGBA. Each layer is placed
2161
+ // by its authored transform (default: top-left at the canvas origin).
2162
+ const decoded = [];
2163
+ for (const layer of visible) {
2164
+ try {
2165
+ // Reuses an upstream GPU op's raw RGBA when present (skips the PNG
2166
+ // decode); otherwise decodes the encoded bytes.
2167
+ const { rgba, width, height } = await decodeRgba(layer.image, context);
2168
+ if (rgba.length === 0)
2169
+ continue;
2170
+ decoded.push({
2171
+ rgba,
2172
+ width,
2173
+ height,
2174
+ opacity: layer.state.opacity,
2175
+ blendModeId: blendModeGpuId(layer.state.blend_mode),
2176
+ transform: layer.state.transform
2177
+ });
2178
+ }
2179
+ catch (err) {
2180
+ // Undecodable input → skip this layer, keep the rest of the stack.
2181
+ console.warn("CompositorNode: failed to decode layer, skipping.", err);
2182
+ }
2183
+ }
2184
+ if (decoded.length === 0) {
2185
+ return {
2186
+ output: imageRef(new Uint8Array(), {
2187
+ uri: "",
2188
+ width: undefined,
2189
+ height: undefined
2190
+ })
2191
+ };
2192
+ }
2193
+ // Canvas size: explicit props win; otherwise the top (first) layer's size.
2194
+ const canvasWidth = Number(this.canvas_width) > 0
2195
+ ? Math.floor(Number(this.canvas_width))
2196
+ : decoded[0].width;
2197
+ const canvasHeight = Number(this.canvas_height) > 0
2198
+ ? Math.floor(Number(this.canvas_height))
2199
+ : decoded[0].height;
2200
+ // Reverse so that image_0 (top input handle) is composited last (on top).
2201
+ decoded.reverse();
2202
+ // Composite on the GPU through the shared headless layer compositor (the
2203
+ // same engine the sketch editor and timeline preview use). Node uses the
2204
+ // cached Dawn device; the browser acquires a navigator.gpu device.
2205
+ let result;
2206
+ if (IS_NODE) {
2207
+ result = await compositeImageLayers(decoded, canvasWidth, canvasHeight);
2208
+ }
2209
+ else {
2210
+ const { createBrowserGPUContext, compositeLayersHeadless } = await import("@nodetool-ai/gpu/webgpu");
2211
+ const ctx = await createBrowserGPUContext();
2212
+ result = await compositeLayersHeadless(ctx.device, decoded, canvasWidth, canvasHeight);
2213
+ }
2214
+ // Emit raw RGBA as the in-flight format — no eager PNG encode. An adjacent
2215
+ // GPU op reuses the pixels directly; any boundary that needs a portable
2216
+ // image (client preview, save, Python bridge) encodes to PNG lazily.
2217
+ return {
2218
+ output: rawRgbaImageRef(result.rgba, result.width, result.height)
2219
+ };
2220
+ }
2221
+ }
2222
+ __decorate([
2223
+ prop({
2224
+ type: "list",
2225
+ default: [],
2226
+ title: "Layers",
2227
+ description: "Per-layer state (positional): { opacity, blend_mode, visible, transform }."
2228
+ })
2229
+ ], CompositorNode.prototype, "layers", void 0);
2230
+ __decorate([
2231
+ prop({
2232
+ type: "int",
2233
+ default: 0,
2234
+ title: "Canvas width",
2235
+ description: "Composite canvas width in pixels. 0 → use the first visible layer's width."
2236
+ })
2237
+ ], CompositorNode.prototype, "canvas_width", void 0);
2238
+ __decorate([
2239
+ prop({
2240
+ type: "int",
2241
+ default: 0,
2242
+ title: "Canvas height",
2243
+ description: "Composite canvas height in pixels. 0 → use the first visible layer's height."
2244
+ })
2245
+ ], CompositorNode.prototype, "canvas_height", void 0);
2246
+ export class PainterNode extends BaseNode {
2247
+ static nodeType = "nodetool.image.Painter";
2248
+ static title = "Painter";
2249
+ static description = "Paint an alpha mask on top of an image and output the mask.\n image, painter, mask, brush, paint";
2250
+ static metadataOutputTypes = {
2251
+ mask: "image",
2252
+ image: "image"
2253
+ };
2254
+ static inlineFields = ["mask_data"];
2255
+ static inputFields = ["image"];
2256
+ static platforms = NODE_ONLY;
2257
+ async process(context) {
2258
+ const image = this.image;
2259
+ // Pass the source image through (resolved bytes if available) so
2260
+ // downstream nodes that want the original image can branch off the
2261
+ // Painter without re-loading the asset.
2262
+ const imageBytes = await imageBytesAsync(image, context);
2263
+ const imageOut = imageBytes.length > 0
2264
+ ? imageRef(imageBytes, {
2265
+ uri: image.uri ?? "",
2266
+ width: image.width ?? undefined,
2267
+ height: image.height ?? undefined
2268
+ })
2269
+ : { ...image };
2270
+ // Decode the painted mask. Empty mask_data → blank mask matching
2271
+ // image dimensions (alpha = 0 everywhere).
2272
+ const maskStr = isString(this.mask_data) ? this.mask_data : "";
2273
+ const maskBytes = toBytes(maskStr);
2274
+ if (maskBytes.length === 0) {
2275
+ // Fall back to a transparent canvas. Prefer the source image's
2276
+ // dimensions; otherwise use the user-configured canvas size; finally
2277
+ // 1×1 if nothing is known.
2278
+ const w = Math.max(1, image.width ?? this.canvas_width);
2279
+ const h = Math.max(1, image.height ?? this.canvas_height);
2280
+ try {
2281
+ const sharp = await loadSharp();
2282
+ if (!sharp)
2283
+ throw new Error(SHARP_UNAVAILABLE_MESSAGE);
2284
+ const blank = await sharp({
2285
+ create: {
2286
+ width: w,
2287
+ height: h,
2288
+ channels: 4,
2289
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
2290
+ }
2291
+ })
2292
+ .png()
2293
+ .toBuffer();
2294
+ const meta = await metadataFor(blank);
2295
+ return {
2296
+ mask: imageRef(blank, {
2297
+ uri: "",
2298
+ mimeType: "image/png",
2299
+ width: meta.width,
2300
+ height: meta.height
2301
+ }),
2302
+ image: imageOut
2303
+ };
2304
+ }
2305
+ catch {
2306
+ return {
2307
+ mask: imageRef(new Uint8Array(), { uri: "" }),
2308
+ image: imageOut
2309
+ };
2310
+ }
2311
+ }
2312
+ // Re-encode the mask as PNG to normalize and pick up dimensions.
2313
+ try {
2314
+ const sharp = await loadSharp();
2315
+ if (!sharp)
2316
+ throw new Error(SHARP_UNAVAILABLE_MESSAGE);
2317
+ const out = await sharp(maskBytes, { failOn: "none" })
2318
+ .png()
2319
+ .toBuffer();
2320
+ const meta = await metadataFor(out);
2321
+ return {
2322
+ mask: imageRef(out, {
2323
+ uri: "",
2324
+ mimeType: "image/png",
2325
+ width: meta.width,
2326
+ height: meta.height
2327
+ }),
2328
+ image: imageOut
2329
+ };
2330
+ }
2331
+ catch {
2332
+ return {
2333
+ mask: imageRef(maskBytes, { uri: "" }),
2334
+ image: imageOut
2335
+ };
2336
+ }
2337
+ }
2338
+ }
2339
+ __decorate([
2340
+ prop({
2341
+ type: "image",
2342
+ default: {
2343
+ type: "image",
2344
+ uri: "",
2345
+ asset_id: null,
2346
+ data: null,
2347
+ metadata: null
2348
+ },
2349
+ title: "Image",
2350
+ description: "Source image painted on (passed through to output)."
2351
+ })
2352
+ ], PainterNode.prototype, "image", void 0);
2353
+ __decorate([
2354
+ prop({
2355
+ type: "str",
2356
+ default: "",
2357
+ title: "Mask data",
2358
+ description: "Base64-encoded PNG of the painted alpha mask. Managed by the UI.",
2359
+ json_schema_extra: { hidden_in_inspector: true }
2360
+ })
2361
+ ], PainterNode.prototype, "mask_data", void 0);
2362
+ __decorate([
2363
+ prop({
2364
+ type: "int",
2365
+ default: 512,
2366
+ title: "Canvas width",
2367
+ description: "Width of the paint canvas in pixels. Overwritten by the source image's width when an image is set."
2368
+ })
2369
+ ], PainterNode.prototype, "canvas_width", void 0);
2370
+ __decorate([
2371
+ prop({
2372
+ type: "int",
2373
+ default: 512,
2374
+ title: "Canvas height",
2375
+ description: "Height of the paint canvas in pixels. Overwritten by the source image's height when an image is set."
2376
+ })
2377
+ ], PainterNode.prototype, "canvas_height", void 0);
2378
+ export class UpscaleImageNode extends BaseNode {
2379
+ static nodeType = "nodetool.image.Upscale";
2380
+ static body = "content_card";
2381
+ static title = "Upscale Image";
2382
+ static description = "Increase the resolution and detail of an image using any supported upscaling provider.\n image, upscale, super-resolution, enhance, AI";
2383
+ static metadataOutputTypes = { output: "image" };
2384
+ static inlineFields = [];
2385
+ static inputFields = ["image"];
2386
+ static autoSaveAsset = true;
2387
+ async process(context) {
2388
+ const image = this.image;
2389
+ const bytes = await imageBytesAsync(image, context);
2390
+ if (bytes.length === 0)
2391
+ throw new Error("The input image is empty.");
2392
+ const { providerId, modelId } = getModelConfig(this.serialize());
2393
+ if (!hasProviderSupport(context, providerId, modelId)) {
2394
+ throw new Error("No provider available for image upscaling.");
2395
+ }
2396
+ const output = (await context.runProviderPrediction({
2397
+ provider: providerId,
2398
+ capability: "upscale_image",
2399
+ model: modelId,
2400
+ params: {
2401
+ image: bytes,
2402
+ scale: this.scale,
2403
+ prompt: this.prompt || undefined
2404
+ }
2405
+ }));
2406
+ const meta = await metadataFor(output);
2407
+ return {
2408
+ output: imageRef(output, {
2409
+ mimeType: inferImageMime(image.uri, output),
2410
+ width: meta.width,
2411
+ height: meta.height
2412
+ })
2413
+ };
2414
+ }
2415
+ }
2416
+ __decorate([
2417
+ prop({
2418
+ type: "image_model",
2419
+ default: {
2420
+ type: "image_model",
2421
+ provider: "fal_ai",
2422
+ id: "fal-ai/clarity-upscaler",
2423
+ name: "Clarity Upscaler",
2424
+ path: null,
2425
+ supported_tasks: []
2426
+ },
2427
+ title: "Model",
2428
+ description: "The upscaling model to use"
2429
+ })
2430
+ ], UpscaleImageNode.prototype, "model", void 0);
2431
+ __decorate([
2432
+ prop({
2433
+ type: "image",
2434
+ default: { type: "image", uri: "", asset_id: null, data: null, metadata: null },
2435
+ title: "Image",
2436
+ description: "Input image to upscale"
2437
+ })
2438
+ ], UpscaleImageNode.prototype, "image", void 0);
2439
+ __decorate([
2440
+ prop({
2441
+ type: "int",
2442
+ default: 2,
2443
+ title: "Scale",
2444
+ description: "Target magnification factor",
2445
+ values: [2, 4]
2446
+ })
2447
+ ], UpscaleImageNode.prototype, "scale", void 0);
2448
+ __decorate([
2449
+ prop({
2450
+ type: "str",
2451
+ default: "",
2452
+ title: "Prompt",
2453
+ description: "Optional guidance prompt for creative upscalers"
2454
+ })
2455
+ ], UpscaleImageNode.prototype, "prompt", void 0);
2456
+ export class RemoveBackgroundNode extends BaseNode {
2457
+ static nodeType = "nodetool.image.RemoveBackground";
2458
+ static body = "content_card";
2459
+ static title = "Remove Background";
2460
+ static description = "Remove the background from an image, returning a cutout with transparency.\n image, background, remove, matte, cutout, AI";
2461
+ static metadataOutputTypes = { output: "image" };
2462
+ static inlineFields = [];
2463
+ static inputFields = ["image"];
2464
+ static autoSaveAsset = true;
2465
+ async process(context) {
2466
+ const image = this.image;
2467
+ const bytes = await imageBytesAsync(image, context);
2468
+ if (bytes.length === 0)
2469
+ throw new Error("The input image is empty.");
2470
+ const { providerId, modelId } = getModelConfig(this.serialize());
2471
+ if (!hasProviderSupport(context, providerId, modelId)) {
2472
+ throw new Error("No provider available for background removal.");
2473
+ }
2474
+ const output = (await context.runProviderPrediction({
2475
+ provider: providerId,
2476
+ capability: "remove_background",
2477
+ model: modelId,
2478
+ params: { image: bytes }
2479
+ }));
2480
+ const meta = await metadataFor(output);
2481
+ return {
2482
+ output: imageRef(output, {
2483
+ mimeType: inferImageMime(image.uri, output),
2484
+ width: meta.width,
2485
+ height: meta.height
2486
+ })
2487
+ };
2488
+ }
2489
+ }
2490
+ __decorate([
2491
+ prop({
2492
+ type: "image_model",
2493
+ default: {
2494
+ type: "image_model",
2495
+ provider: "fal_ai",
2496
+ id: "fal-ai/bria/background/remove",
2497
+ name: "Bria Background Remove",
2498
+ path: null,
2499
+ supported_tasks: []
2500
+ },
2501
+ title: "Model",
2502
+ description: "The background-removal model to use"
2503
+ })
2504
+ ], RemoveBackgroundNode.prototype, "model", void 0);
2505
+ __decorate([
2506
+ prop({
2507
+ type: "image",
2508
+ default: { type: "image", uri: "", asset_id: null, data: null, metadata: null },
2509
+ title: "Image",
2510
+ description: "Input image to remove the background from"
2511
+ })
2512
+ ], RemoveBackgroundNode.prototype, "image", void 0);
2513
+ export class RelightImageNode extends BaseNode {
2514
+ static nodeType = "nodetool.image.Relight";
2515
+ static body = "content_card";
2516
+ static title = "Relight Image";
2517
+ static description = "Re-light a subject according to a text prompt using any supported image-editing model.\n image, relight, lighting, AI, image-to-image";
2518
+ static metadataOutputTypes = { output: "image" };
2519
+ static inlineFields = [];
2520
+ static inputFields = ["image", "prompt"];
2521
+ static autoSaveAsset = true;
2522
+ async process(context) {
2523
+ const image = this.image;
2524
+ const bytes = await imageBytesAsync(image, context);
2525
+ if (bytes.length === 0)
2526
+ throw new Error("The input image is empty.");
2527
+ const { providerId, modelId } = getModelConfig(this.serialize());
2528
+ if (!hasProviderSupport(context, providerId, modelId)) {
2529
+ throw new Error("No provider available for image relighting.");
2530
+ }
2531
+ const output = (await context.runProviderPrediction({
2532
+ provider: providerId,
2533
+ capability: "image_to_image",
2534
+ model: modelId,
2535
+ params: {
2536
+ images: [bytes],
2537
+ prompt: this.prompt,
2538
+ negative_prompt: this.negative_prompt
2539
+ }
2540
+ }));
2541
+ const meta = await metadataFor(output);
2542
+ return {
2543
+ output: imageRef(output, {
2544
+ mimeType: inferImageMime(image.uri, output),
2545
+ width: meta.width,
2546
+ height: meta.height
2547
+ })
2548
+ };
2549
+ }
2550
+ }
2551
+ __decorate([
2552
+ prop({
2553
+ type: "image_model",
2554
+ default: {
2555
+ type: "image_model",
2556
+ provider: "fal_ai",
2557
+ id: "fal-ai/image-apps-v2/relighting",
2558
+ name: "Relight",
2559
+ path: null,
2560
+ supported_tasks: []
2561
+ },
2562
+ title: "Model",
2563
+ description: "The image-editing or dedicated relighting model to use"
2564
+ })
2565
+ ], RelightImageNode.prototype, "model", void 0);
2566
+ __decorate([
2567
+ prop({
2568
+ type: "image",
2569
+ default: { type: "image", uri: "", asset_id: null, data: null, metadata: null },
2570
+ title: "Image",
2571
+ description: "Input image to relight"
2572
+ })
2573
+ ], RelightImageNode.prototype, "image", void 0);
2574
+ __decorate([
2575
+ prop({
2576
+ type: "str",
2577
+ default: "studio lighting from the left",
2578
+ title: "Prompt",
2579
+ description: "Description of the desired lighting"
2580
+ })
2581
+ ], RelightImageNode.prototype, "prompt", void 0);
2582
+ __decorate([
2583
+ prop({
2584
+ type: "str",
2585
+ default: "",
2586
+ title: "Negative Prompt",
2587
+ description: "Text prompt describing what to avoid"
2588
+ })
2589
+ ], RelightImageNode.prototype, "negative_prompt", void 0);
2590
+ /** A `points` entry that names a pixel. */
2591
+ function isSegmentPointLike(value) {
2592
+ return isObjectLike(value) && isNumber(value.x) && isNumber(value.y);
2593
+ }
2594
+ /** A `box` value that names a rectangle. */
2595
+ function isSegmentBoxLike(value) {
2596
+ return (isObjectLike(value) &&
2597
+ isNumber(value.x) &&
2598
+ isNumber(value.y) &&
2599
+ isNumber(value.width) &&
2600
+ isNumber(value.height));
2601
+ }
2602
+ /** The `points` property, keeping only entries that name a pixel. */
2603
+ function segmentPoints(value) {
2604
+ if (!Array.isArray(value))
2605
+ return undefined;
2606
+ const points = value
2607
+ .filter(isSegmentPointLike)
2608
+ .map(({ x, y, include }) => ({ x, y, include: include !== false }));
2609
+ return points.length > 0 ? points : undefined;
2610
+ }
2611
+ /** The `box` property, or undefined when it is the empty default. */
2612
+ function segmentBox(value) {
2613
+ return isSegmentBoxLike(value) ? value : undefined;
2614
+ }
2615
+ export class SegmentImageNode extends BaseNode {
2616
+ static nodeType = "nodetool.image.Segment";
2617
+ static body = "content_card";
2618
+ static title = "Segment Image";
2619
+ static description = "Find objects in an image and return one mask per object, using any supported segmentation provider.\n image, segment, mask, sam, cutout, AI";
2620
+ static metadataOutputTypes = {
2621
+ masks: "list[image]",
2622
+ labels: "list[str]",
2623
+ scores: "list[float]"
2624
+ };
2625
+ static inlineFields = [];
2626
+ static inputFields = ["image", "prompt"];
2627
+ async process(context) {
2628
+ const image = this.image;
2629
+ const bytes = await imageBytesAsync(image, context);
2630
+ if (bytes.length === 0)
2631
+ throw new Error("The input image is empty.");
2632
+ const { providerId, modelId } = getModelConfig(this.serialize());
2633
+ if (!hasProviderSupport(context, providerId, modelId)) {
2634
+ throw new Error("No provider available for image segmentation.");
2635
+ }
2636
+ const minConfidence = this.min_confidence;
2637
+ const found = (await context.runProviderPrediction({
2638
+ provider: providerId,
2639
+ capability: "segment_image",
2640
+ model: modelId,
2641
+ params: {
2642
+ image: bytes,
2643
+ prompt: this.prompt || undefined,
2644
+ points: segmentPoints(this.points),
2645
+ box: segmentBox(this.box),
2646
+ max_masks: this.max_masks || undefined,
2647
+ // 0 is "keep every mask", not a threshold to send.
2648
+ min_confidence: minConfidence > 0 ? minConfidence : undefined
2649
+ }
2650
+ }));
2651
+ return {
2652
+ masks: found.map((entry) => imageRef(entry.mask, {
2653
+ mimeType: entry.mimeType,
2654
+ width: entry.width ?? undefined,
2655
+ height: entry.height ?? undefined
2656
+ })),
2657
+ // Positional: the label and score at index i belong to mask i, so an
2658
+ // unlabeled or unscored mask keeps its slot rather than shifting the rest.
2659
+ labels: found.map((entry, index) => entry.label ?? `Object ${index + 1}`),
2660
+ scores: found.map((entry) => entry.confidence ?? 0)
2661
+ };
2662
+ }
2663
+ }
2664
+ __decorate([
2665
+ prop({
2666
+ type: "image_model",
2667
+ default: {
2668
+ type: "image_model",
2669
+ provider: "fal_ai",
2670
+ id: "fal-ai/sam-3-1/image",
2671
+ name: "SAM 3.1",
2672
+ path: null,
2673
+ supported_tasks: []
2674
+ },
2675
+ title: "Model",
2676
+ description: "The segmentation model to use"
2677
+ })
2678
+ ], SegmentImageNode.prototype, "model", void 0);
2679
+ __decorate([
2680
+ prop({
2681
+ type: "image",
2682
+ default: { type: "image", uri: "", asset_id: null, data: null, metadata: null },
2683
+ title: "Image",
2684
+ description: "Input image to segment"
2685
+ })
2686
+ ], SegmentImageNode.prototype, "image", void 0);
2687
+ __decorate([
2688
+ prop({
2689
+ type: "str",
2690
+ default: "",
2691
+ title: "Prompt",
2692
+ description: "The object to find, e.g. \"the red car\". Most models need this: a concept-driven model such as SAM 3.1 segments nothing without it, and ignores points and boxes. Leave it empty only for a model that finds objects on its own, such as fal-ai/sam2/auto-segment."
2693
+ })
2694
+ ], SegmentImageNode.prototype, "prompt", void 0);
2695
+ __decorate([
2696
+ prop({
2697
+ type: "list[dict]",
2698
+ default: [],
2699
+ title: "Points",
2700
+ description: "Clicks that point at one object, in source-image pixels: {x, y, include}. `include: false` marks a point that is NOT part of it."
2701
+ })
2702
+ ], SegmentImageNode.prototype, "points", void 0);
2703
+ __decorate([
2704
+ prop({
2705
+ type: "dict",
2706
+ default: {},
2707
+ title: "Box",
2708
+ description: "A rectangle around one object, in source-image pixels: {x, y, width, height}"
2709
+ })
2710
+ ], SegmentImageNode.prototype, "box", void 0);
2711
+ __decorate([
2712
+ prop({
2713
+ type: "int",
2714
+ default: 3,
2715
+ title: "Max Masks",
2716
+ description: "Upper bound on how many masks to return"
2717
+ })
2718
+ ], SegmentImageNode.prototype, "max_masks", void 0);
2719
+ __decorate([
2720
+ prop({
2721
+ type: "float",
2722
+ default: 0,
2723
+ title: "Min Confidence",
2724
+ description: "Drop masks the model scores below this (0 = keep every mask)"
2725
+ })
2726
+ ], SegmentImageNode.prototype, "min_confidence", void 0);
2727
+ export class VectorizeImageNode extends BaseNode {
2728
+ static nodeType = "nodetool.image.Vectorize";
2729
+ static body = "content_card";
2730
+ static title = "Vectorize Image";
2731
+ static description = "Convert a raster image into a scalable vector (SVG) using any supported vectorization provider.\n image, vector, svg, vectorize, trace, AI";
2732
+ static metadataOutputTypes = { output: "svg_element" };
2733
+ static inlineFields = [];
2734
+ static inputFields = ["image"];
2735
+ async process(context) {
2736
+ const image = this.image;
2737
+ const bytes = await imageBytesAsync(image, context);
2738
+ if (bytes.length === 0)
2739
+ throw new Error("The input image is empty.");
2740
+ const { providerId, modelId } = getModelConfig(this.serialize());
2741
+ if (!hasProviderSupport(context, providerId, modelId)) {
2742
+ throw new Error("No provider available for image vectorization.");
2743
+ }
2744
+ const output = (await context.runProviderPrediction({
2745
+ provider: providerId,
2746
+ capability: "vectorize_image",
2747
+ model: modelId,
2748
+ params: { image: bytes }
2749
+ }));
2750
+ return { output: { content: new TextDecoder().decode(output) } };
2751
+ }
2752
+ }
2753
+ __decorate([
2754
+ prop({
2755
+ type: "image_model",
2756
+ default: {
2757
+ type: "image_model",
2758
+ provider: "fal_ai",
2759
+ id: "fal-ai/recraft/vectorize",
2760
+ name: "Recraft Vectorize",
2761
+ path: null,
2762
+ supported_tasks: []
2763
+ },
2764
+ title: "Model",
2765
+ description: "The vectorization model to use"
2766
+ })
2767
+ ], VectorizeImageNode.prototype, "model", void 0);
2768
+ __decorate([
2769
+ prop({
2770
+ type: "image",
2771
+ default: { type: "image", uri: "", asset_id: null, data: null, metadata: null },
2772
+ title: "Image",
2773
+ description: "Input image to vectorize"
2774
+ })
2775
+ ], VectorizeImageNode.prototype, "image", void 0);
2776
+ // GPU transform nodes: pure WebGPU pixel ops (no sharp) — runnable in the
2777
+ // browser and rendered as media content cards.
2778
+ const IMAGE_TRANSFORM_NODES = tagAsContentCard(tagAsBrowserGpu([
2779
+ PasteNode,
2780
+ ScaleNode,
2781
+ // The replacement for Scale/Resize/Fit. It was written, exported and
2782
+ // tested but never listed here, so `nodetool.image.ResizeImage` was not in
2783
+ // the registry and every `replacedBy` pointing at it named a node the
2784
+ // editor could not place.
2785
+ ResizeImageNode,
2786
+ ResizeNode,
2787
+ CanvasResizeNode,
2788
+ CropNode,
2789
+ FitNode,
2790
+ RotateAndFlipNode,
2791
+ ChannelsNode,
2792
+ BlurNode,
2793
+ LevelsNode,
2794
+ CompositorNode
2795
+ ]));
2796
+ // Non-browser nodes. `tagAsServer` declares node+workers+edge, but it skips any
2797
+ // class that already declares `static platforms` — the filesystem/sharp-bound
2798
+ // members below pin themselves to `NODE_ONLY` (they cannot run on the workers /
2799
+ // edge V8 isolates: no fs, no native addons). The pure-JS list nodes
2800
+ // (BatchToList, ImagesToList) and the provider/HTTP generation nodes
2801
+ // (TextToImage, ImageToImage, Upscale, RemoveBackground, Relight, Vectorize,
2802
+ // Segment)
2803
+ // keep the full server set — they only touch sharp via metadataFor, which
2804
+ // degrades to undefined dimensions off-Node.
2805
+ const IMAGE_SERVER_NODES = tagAsServer([
2806
+ LoadImageFileNode,
2807
+ LoadImageFolderNode,
2808
+ SaveImageFileImageNode,
2809
+ LoadImageAssetsNode,
2810
+ SaveImageNode,
2811
+ GetMetadataNode,
2812
+ BatchToListNode,
2813
+ ImagesToListNode,
2814
+ PainterNode,
2815
+ TextToImageNode,
2816
+ ImageToImageNode,
2817
+ UpscaleImageNode,
2818
+ RemoveBackgroundNode,
2819
+ RelightImageNode,
2820
+ VectorizeImageNode,
2821
+ SegmentImageNode
2822
+ ]);
2823
+ export const IMAGE_NODES = [
2824
+ ...IMAGE_TRANSFORM_NODES,
2825
+ ...IMAGE_SERVER_NODES
2826
+ ];
2827
+ //# sourceMappingURL=image.js.map