@joycostudio/chopper 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,3 @@
1
- declare const RECIPE_SCHEMA_VERSION: 1;
2
1
  type TextureSize = readonly [width: number, height: number];
3
2
  interface SizedEncoding {
4
3
  /** Maximum dimensions. Aspect ratio is preserved and images are not enlarged. */
@@ -48,8 +47,25 @@ interface Etc1sEncoding extends SizedEncoding {
48
47
  compression?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
49
48
  mipmaps?: boolean;
50
49
  }
50
+ /**
51
+ * UASTC HDR 4x4. Encodes half-float EXR source into blocks the runtime
52
+ * transcodes to BC6H on desktop, or uploads as ASTC 4x4 SFLOAT where the HDR
53
+ * profile exists. Fixed 8 bits per texel on the GPU regardless of source.
54
+ *
55
+ * Deliberately not a `SizedEncoding`: resizing runs on decoded 8-bit RGBA, and
56
+ * there is no half-float resampler in the pipeline, so HDR sources must already
57
+ * be authored at their target resolution.
58
+ */
59
+ interface UastcHdrEncoding {
60
+ codec: 'ktx2';
61
+ mode: 'uastc-hdr';
62
+ /** Encoder effort. Higher is slower; rarely helps on low-frequency lightmaps. */
63
+ level?: 0 | 1 | 2 | 3 | 4;
64
+ mipmaps?: boolean;
65
+ zstd?: boolean;
66
+ }
51
67
  type RasterEncoding = WebpEncoding | AvifEncoding | JpegEncoding | PngEncoding;
52
- type ImageEncoding = RasterEncoding | UastcEncoding | Etc1sEncoding;
68
+ type ImageEncoding = RasterEncoding | UastcEncoding | Etc1sEncoding | UastcHdrEncoding;
53
69
  type GlbProperty = 'accessor' | 'animation' | 'buffer' | 'camera' | 'material' | 'mesh' | 'node' | 'primitive' | 'primitiveTarget' | 'skin' | 'texture';
54
70
  type GlbMethodRecipe = {
55
71
  method: 'dedup';
@@ -88,25 +104,21 @@ type GeometryEncoding = {
88
104
  codec: 'meshopt';
89
105
  };
90
106
  interface GlbAssetRecipe {
91
- schemaVersion: typeof RECIPE_SCHEMA_VERSION;
92
107
  kind: 'glb';
93
108
  methods?: readonly GlbMethodRecipe[];
94
109
  textures?: readonly EmbeddedTextureRecipe[];
95
110
  geometry?: GeometryEncoding | false;
96
111
  }
97
112
  interface ImageAssetRecipe {
98
- schemaVersion: typeof RECIPE_SCHEMA_VERSION;
99
113
  kind: 'image';
100
114
  encode: ImageEncoding;
101
115
  }
102
116
  type AssetRecipe = GlbAssetRecipe | ImageAssetRecipe;
103
- type NormalizedImageEncoding = (Required<Omit<WebpEncoding, 'maxSize'>> & Pick<WebpEncoding, 'maxSize'>) | (Required<Omit<AvifEncoding, 'maxSize'>> & Pick<AvifEncoding, 'maxSize'>) | (Required<Omit<JpegEncoding, 'maxSize'>> & Pick<JpegEncoding, 'maxSize'>) | PngEncoding | (Required<Omit<UastcEncoding, 'maxSize' | 'rdo'>> & Pick<UastcEncoding, 'maxSize' | 'rdo'>) | (Required<Omit<Etc1sEncoding, 'maxSize'>> & Pick<Etc1sEncoding, 'maxSize'>);
117
+ type NormalizedImageEncoding = (Required<Omit<WebpEncoding, 'maxSize'>> & Pick<WebpEncoding, 'maxSize'>) | (Required<Omit<AvifEncoding, 'maxSize'>> & Pick<AvifEncoding, 'maxSize'>) | (Required<Omit<JpegEncoding, 'maxSize'>> & Pick<JpegEncoding, 'maxSize'>) | PngEncoding | (Required<Omit<UastcEncoding, 'maxSize' | 'rdo'>> & Pick<UastcEncoding, 'maxSize' | 'rdo'>) | (Required<Omit<Etc1sEncoding, 'maxSize'>> & Pick<Etc1sEncoding, 'maxSize'>) | Required<UastcHdrEncoding>;
104
118
  type NormalizedAssetRecipe = {
105
- schemaVersion: typeof RECIPE_SCHEMA_VERSION;
106
119
  kind: 'image';
107
120
  encode: NormalizedImageEncoding;
108
121
  } | {
109
- schemaVersion: typeof RECIPE_SCHEMA_VERSION;
110
122
  kind: 'glb';
111
123
  methods: readonly GlbMethodRecipe[];
112
124
  textures: readonly (Omit<EmbeddedTextureRecipe, 'encode'> & {
@@ -130,7 +142,9 @@ interface ChopperSuccess<T> {
130
142
  }
131
143
  type ChopperResult<T> = ChopperSuccess<T> | ChopperFailure;
132
144
 
133
- type SourceImageMimeType = 'image/jpeg' | 'image/png';
145
+ type HdrSourceMimeType = 'image/x-exr' | 'image/vnd.radiance';
146
+
147
+ type SourceImageMimeType = 'image/jpeg' | 'image/png' | HdrSourceMimeType;
134
148
  interface SourceImage {
135
149
  bytes: Uint8Array;
136
150
  mimeType: SourceImageMimeType;
@@ -164,7 +178,7 @@ interface AssetInput {
164
178
  }
165
179
  interface ImageInspection {
166
180
  kind: 'image';
167
- mimeType: 'image/png' | 'image/jpeg';
181
+ mimeType: 'image/png' | 'image/jpeg' | 'image/x-exr' | 'image/vnd.radiance';
168
182
  width: number;
169
183
  height: number;
170
184
  byteLength: number;
@@ -278,19 +292,21 @@ interface OptimizeFileOptions extends OptimizationOptions {
278
292
  }
279
293
  declare function optimizeFile({ input, output, recipe, ...options }: OptimizeFileOptions): Promise<ChopperResult<OptimizationOutput>>;
280
294
 
281
- type ChopperOutput = {
282
- mode: 'replace';
283
- } | {
284
- mode: 'template';
285
- path: string;
286
- };
287
295
  interface ChopperRule {
288
296
  include: readonly string[];
289
297
  exclude?: readonly string[];
290
298
  recipe: AssetRecipe;
291
- output: ChopperOutput;
299
+ path?: string;
292
300
  }
293
301
  interface ChopperConfig {
302
+ output: string;
303
+ /**
304
+ * Every rule matches independently, so one file can be claimed by several of
305
+ * them. Where two rules resolve the same output path for the same input, the
306
+ * later rule wins: state the general strategy first and narrow it with
307
+ * exceptions after. Rules that resolve to different output paths all run, so
308
+ * one input can still fan out to several encodings.
309
+ */
294
310
  rules: readonly ChopperRule[];
295
311
  concurrency?: number;
296
312
  }
@@ -312,6 +328,7 @@ interface BatchFileReport {
312
328
  }
313
329
  interface BatchReport {
314
330
  mode: BatchMode;
331
+ output: string;
315
332
  files: BatchFileReport[];
316
333
  totals: {
317
334
  matched: number;
@@ -327,7 +344,6 @@ interface RunConfigOptions {
327
344
  configPath?: string;
328
345
  cwd?: string;
329
346
  mode?: BatchMode;
330
- outputDirectory?: string;
331
347
  chopper?: Chopper;
332
348
  }
333
349
  interface PlannedAsset {
@@ -336,7 +352,7 @@ interface PlannedAsset {
336
352
  rule: ChopperRule;
337
353
  }
338
354
  declare function runConfig(options?: RunConfigOptions): Promise<ChopperResult<BatchReport>>;
339
- declare function planAssets(config: ChopperConfig, cwd: string, outputDirectory?: string): Promise<ChopperResult<PlannedAsset[]>>;
355
+ declare function planAssets(config: ChopperConfig, cwd: string): Promise<ChopperResult<PlannedAsset[]>>;
340
356
 
341
357
  declare function syncCodecs(output: string): Promise<ChopperResult<{
342
358
  directory: string;
@@ -24,7 +24,6 @@ import { glob } from 'tinyglobby';
24
24
  // src/node/image-engine.ts
25
25
 
26
26
  // src/core/recipes.ts
27
- var RECIPE_SCHEMA_VERSION = 1;
28
27
  function outputExtension(encoding) {
29
28
  if (encoding.codec === "ktx2") return ".ktx2";
30
29
  if (encoding.codec === "jpeg") return ".jpg";
@@ -60,13 +59,11 @@ function normalizeRecipe(value) {
60
59
  const recipe = validated.data;
61
60
  if (recipe.kind === "image") {
62
61
  return success({
63
- schemaVersion: RECIPE_SCHEMA_VERSION,
64
62
  kind: "image",
65
63
  encode: normalizeEncoding(recipe.encode)
66
64
  });
67
65
  }
68
66
  return success({
69
- schemaVersion: RECIPE_SCHEMA_VERSION,
70
67
  kind: "glb",
71
68
  methods: recipe.methods ?? [],
72
69
  textures: (recipe.textures ?? []).map((texture) => ({
@@ -120,15 +117,15 @@ function encodingShapeIssue(encoding) {
120
117
  if (!["webp", "avif", "jpeg", "png", "ktx2"].includes(String(candidate.codec))) {
121
118
  return `Unsupported image codec: ${String(candidate.codec)}`;
122
119
  }
123
- if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s") {
120
+ if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s" && candidate.mode !== "uastc-hdr") {
124
121
  return `Unsupported KTX2 mode: ${String(candidate.mode)}`;
125
122
  }
123
+ if (candidate.codec === "ktx2" && candidate.mode === "uastc-hdr" && candidate.maxSize !== void 0) {
124
+ return "UASTC HDR does not support maxSize; resizing requires a decoded 8-bit image. Author the source at its target resolution.";
125
+ }
126
126
  return void 0;
127
127
  }
128
128
  function recipeIssue(recipe) {
129
- if (recipe.schemaVersion !== RECIPE_SCHEMA_VERSION) {
130
- return `Unsupported recipe schema version: ${String(recipe.schemaVersion)}`;
131
- }
132
129
  if (recipe.kind === "image") return encodingIssue(recipe.encode);
133
130
  const labels = /* @__PURE__ */ new Set();
134
131
  const selectors = /* @__PURE__ */ new Set();
@@ -150,6 +147,9 @@ function recipeIssue(recipe) {
150
147
  }
151
148
  selectors.add(key);
152
149
  }
150
+ if (texture.encode.codec === "ktx2" && texture.encode.mode === "uastc-hdr") {
151
+ return `Texture recipe "${texture.label}" uses UASTC HDR, which KHR_texture_basisu does not cover; HDR is only supported for standalone image recipes`;
152
+ }
153
153
  const issue = encodingIssue(texture.encode);
154
154
  if (issue) return issue;
155
155
  }
@@ -171,7 +171,7 @@ function selectorValues(selector) {
171
171
  return success(selector.indices);
172
172
  }
173
173
  function encodingIssue(encoding) {
174
- if (encoding.maxSize) {
174
+ if ("maxSize" in encoding && encoding.maxSize) {
175
175
  const [width, height] = encoding.maxSize;
176
176
  if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
177
177
  return "Texture maxSize must contain positive integers";
@@ -200,6 +200,9 @@ function encodingIssue(encoding) {
200
200
  return "UASTC RDO lambda must be between 0.001 and 10";
201
201
  }
202
202
  }
203
+ if (encoding.codec === "ktx2" && encoding.mode === "uastc-hdr" && encoding.level !== void 0 && (!Number.isInteger(encoding.level) || encoding.level < 0 || encoding.level > 4)) {
204
+ return "UASTC HDR level must be an integer between 0 and 4";
205
+ }
203
206
  if (encoding.codec === "ktx2" && encoding.mode === "etc1s" && encoding.compression !== void 0 && (!Number.isInteger(encoding.compression) || encoding.compression < 0 || encoding.compression > 6)) {
204
207
  return "ETC1S compression must be an integer between 0 and 6";
205
208
  }
@@ -232,6 +235,14 @@ function normalizeEncoding(encoding) {
232
235
  case "png":
233
236
  return { ...encoding };
234
237
  case "ktx2":
238
+ if (encoding.mode === "uastc-hdr") {
239
+ return {
240
+ ...encoding,
241
+ level: encoding.level ?? 1,
242
+ mipmaps: encoding.mipmaps ?? true,
243
+ zstd: encoding.zstd ?? true
244
+ };
245
+ }
235
246
  if (encoding.mode === "uastc") {
236
247
  return {
237
248
  ...encoding,
@@ -253,9 +264,133 @@ function normalizeEncoding(encoding) {
253
264
  }
254
265
  }
255
266
 
267
+ // src/codecs/hdr-source.ts
268
+ var HDR_SOURCE_MIME_TYPES = {
269
+ exr: "image/x-exr",
270
+ hdr: "image/vnd.radiance"
271
+ };
272
+ function isHdrSourceMimeType(mimeType) {
273
+ return mimeType === "image/x-exr" || mimeType === "image/vnd.radiance";
274
+ }
275
+ var EXR_MAGIC = [118, 47, 49, 1];
276
+ var VERSION_NUMBER_FIELD = 255;
277
+ var NON_IMAGE_FLAG = 2048;
278
+ var MULTI_PART_FILE_FLAG = 4096;
279
+ var EXR_COMPRESSION = [
280
+ { name: "NO_COMPRESSION", supported: true },
281
+ { name: "RLE", supported: true },
282
+ { name: "ZIPS", supported: true },
283
+ { name: "ZIP", supported: true },
284
+ { name: "PIZ", supported: true },
285
+ { name: "PXR24", supported: false },
286
+ { name: "B44", supported: false },
287
+ { name: "B44A", supported: false },
288
+ { name: "DWAA", supported: false },
289
+ { name: "DWAB", supported: false }
290
+ ];
291
+ var RADIANCE_MAGIC = [35, 63];
292
+ var RADIANCE_HEADER_LIMIT = 8192;
293
+ var MAX_HDR_SOURCE_TEXELS = 12 * 1024 * 1024;
294
+ function detectHdrContainer(bytes) {
295
+ if (bytes.length >= 8 && EXR_MAGIC.every((byte, index) => bytes[index] === byte)) return "exr";
296
+ if (bytes.length >= 8 && RADIANCE_MAGIC.every((byte, index) => bytes[index] === byte)) return "hdr";
297
+ return void 0;
298
+ }
299
+ function readHdrSource(bytes) {
300
+ const container = detectHdrContainer(bytes);
301
+ if (!container) return { error: "Not an OpenEXR or Radiance HDR file" };
302
+ return container === "exr" ? readExr(bytes) : readRadiance(bytes);
303
+ }
304
+ function readExr(bytes) {
305
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
306
+ const version = view.getInt32(4, true);
307
+ if ((version & VERSION_NUMBER_FIELD) !== 2) {
308
+ return { error: `Unsupported EXR version: ${version & VERSION_NUMBER_FIELD}` };
309
+ }
310
+ if (version & MULTI_PART_FILE_FLAG) return { error: "Multi-part EXR files are not supported" };
311
+ if (version & NON_IMAGE_FLAG) return { error: "Deep EXR files are not supported" };
312
+ let size;
313
+ let compressionIssue;
314
+ let offset = 8;
315
+ while (offset < bytes.length) {
316
+ const name = readNullTerminated(bytes, offset);
317
+ if (name === void 0) return { error: "Malformed EXR header" };
318
+ if (name.value === "") break;
319
+ offset = name.next;
320
+ const type = readNullTerminated(bytes, offset);
321
+ if (type === void 0) return { error: "Malformed EXR header" };
322
+ offset = type.next;
323
+ if (offset + 4 > bytes.length) return { error: "Malformed EXR header" };
324
+ const length = view.getInt32(offset, true);
325
+ offset += 4;
326
+ if (length < 0 || offset + length > bytes.length) return { error: "Malformed EXR header" };
327
+ if (name.value === "dataWindow") {
328
+ if (type.value !== "box2i" || length !== 16) return { error: "Malformed EXR dataWindow" };
329
+ const xMin = view.getInt32(offset, true);
330
+ const yMin = view.getInt32(offset + 4, true);
331
+ const xMax = view.getInt32(offset + 8, true);
332
+ const yMax = view.getInt32(offset + 12, true);
333
+ const width = xMax - xMin + 1;
334
+ const height = yMax - yMin + 1;
335
+ if (width < 1 || height < 1) return { error: "EXR dataWindow is empty" };
336
+ size = { container: "exr", width, height };
337
+ }
338
+ if (name.value === "compression") {
339
+ if (length !== 1) return { error: "Malformed EXR compression attribute" };
340
+ compressionIssue = exrCompressionIssue(bytes[offset]);
341
+ }
342
+ offset += length;
343
+ }
344
+ if (compressionIssue) return { error: compressionIssue };
345
+ return size ?? { error: "EXR header has no dataWindow attribute" };
346
+ }
347
+ function exrCompressionIssue(code) {
348
+ const codec = EXR_COMPRESSION[code];
349
+ if (!codec) return `Unsupported EXR compression: unknown codec ${code}`;
350
+ if (codec.supported) return void 0;
351
+ const readable = EXR_COMPRESSION.filter((entry) => entry.supported).map((entry) => entry.name).join(", ");
352
+ return `EXR uses ${codec.name} compression, which the HDR encoder cannot read. Re-export with one of: ${readable}. EXR compression only affects the file on disk \u2014 it does not change the encoded KTX2.`;
353
+ }
354
+ function readRadiance(bytes) {
355
+ const text = latin1(bytes.subarray(0, RADIANCE_HEADER_LIMIT));
356
+ const lines = text.split("\n");
357
+ let index = 0;
358
+ while (index < lines.length && lines[index] !== "" && lines[index] !== "\r") index++;
359
+ index++;
360
+ while (index < lines.length && (lines[index] === "" || lines[index] === "\r")) index++;
361
+ if (index >= lines.length) return { error: "Radiance file has no resolution line" };
362
+ const resolution = /^([+-][XY])\s+(\d+)\s+([+-][XY])\s+(\d+)\s*$/.exec(lines[index].replace(/\r$/, ""));
363
+ if (!resolution) return { error: `Malformed Radiance resolution line: ${lines[index].slice(0, 40)}` };
364
+ const extents = /* @__PURE__ */ new Map([
365
+ [resolution[1][1], Number(resolution[2])],
366
+ [resolution[3][1], Number(resolution[4])]
367
+ ]);
368
+ const width = extents.get("X");
369
+ const height = extents.get("Y");
370
+ if (width === void 0 || height === void 0) {
371
+ return { error: "Radiance resolution line must pair an X and a Y axis" };
372
+ }
373
+ if (width < 1 || height < 1) return { error: "Radiance image is empty" };
374
+ return { container: "hdr", width, height };
375
+ }
376
+ function readNullTerminated(bytes, start) {
377
+ const limit = Math.min(bytes.length, start + 256);
378
+ for (let index = start; index < limit; index++) {
379
+ if (bytes[index] === 0) {
380
+ return { value: latin1(bytes.subarray(start, index)), next: index + 1 };
381
+ }
382
+ }
383
+ return void 0;
384
+ }
385
+ function latin1(bytes) {
386
+ let value = "";
387
+ for (const byte of bytes) value += String.fromCharCode(byte);
388
+ return value;
389
+ }
390
+
256
391
  // package.json
257
392
  var package_default = {
258
- version: "0.3.0"};
393
+ version: "0.5.0"};
259
394
 
260
395
  // src/codecs/manifest.ts
261
396
  var CODEC_MANIFEST_HASH = "2046d60deb0f9f224743f4404f3c6e8ba5399f81b2811fa50466e93fce3bd322";
@@ -345,12 +480,23 @@ var ENGINE_ID = `chopper@${package_default.version}:${CODEC_MANIFEST_HASH}`;
345
480
  // src/codecs/image-engine.ts
346
481
  var CodecLoadError = class extends Error {
347
482
  };
483
+ var SourceError = class extends Error {
484
+ constructor(code, message) {
485
+ super(message);
486
+ this.code = code;
487
+ }
488
+ };
348
489
  function createWasmImageEngine(loader) {
349
490
  const adapters = createAdapterCache(loader);
350
491
  return {
351
492
  id: ENGINE_ID,
352
493
  manifestHash: CODEC_MANIFEST_HASH,
353
494
  async inspect(source) {
495
+ if (isHdrSourceMimeType(source.mimeType)) {
496
+ const header = readHdrSource(source.bytes);
497
+ if ("error" in header) return failure("decode_failed", header.error);
498
+ return success({ width: header.width, height: header.height });
499
+ }
354
500
  try {
355
501
  const image = await decodeSource(source, adapters);
356
502
  return success({ width: image.width, height: image.height });
@@ -359,10 +505,17 @@ function createWasmImageEngine(loader) {
359
505
  }
360
506
  },
361
507
  async encode(source, encoding, signal) {
362
- const valid = validateRecipe({ schemaVersion: 1, kind: "image", encode: encoding });
508
+ const valid = validateRecipe({ kind: "image", encode: encoding });
363
509
  if (!valid.ok) return valid;
510
+ const mismatch = sourcePairingIssue(source, encoding);
511
+ if (mismatch) return mismatch;
364
512
  try {
365
513
  assertNotAborted(signal);
514
+ if (isHdrEncoding(encoding)) {
515
+ const encoded2 = await encodeKtx2Hdr(source, encoding, await loader.basisEncoderUrl());
516
+ assertNotAborted(signal);
517
+ return success(encoded2);
518
+ }
366
519
  let image = await decodeSource(source, adapters);
367
520
  assertNotAborted(signal);
368
521
  if (encoding.maxSize) {
@@ -517,6 +670,45 @@ async function encodeRaster(image, encoding, adapters) {
517
670
  }
518
671
  return { bytes: toUint8Array(bytes), mimeType: outputMimeType(encoding) };
519
672
  }
673
+ var megapixels = (texels) => (texels / 1e6).toFixed(1);
674
+ function isHdrEncoding(encoding) {
675
+ return encoding.codec === "ktx2" && encoding.mode === "uastc-hdr";
676
+ }
677
+ function sourcePairingIssue(source, encoding) {
678
+ const isHdrSource = isHdrSourceMimeType(source.mimeType);
679
+ if (isHdrEncoding(encoding) && !isHdrSource) {
680
+ return failure("invalid_recipe", `UASTC HDR requires an EXR or Radiance HDR source; received ${source.mimeType}`);
681
+ }
682
+ if (isHdrSource && !isHdrEncoding(encoding)) {
683
+ return failure(
684
+ "invalid_recipe",
685
+ "HDR sources can only be encoded as KTX2 with mode 'uastc-hdr'; chopper does not decode HDR pixels"
686
+ );
687
+ }
688
+ return void 0;
689
+ }
690
+ async function encodeKtx2Hdr(source, encoding, wasmUrl) {
691
+ const header = readHdrSource(source.bytes);
692
+ if ("error" in header) throw new SourceError("decode_failed", header.error);
693
+ const texels = header.width * header.height;
694
+ if (texels > MAX_HDR_SOURCE_TEXELS) {
695
+ throw new SourceError(
696
+ "unsupported_asset",
697
+ `Source is ${header.width}x${header.height} (${megapixels(texels)} Mpix), over the ${megapixels(MAX_HDR_SOURCE_TEXELS)} Mpix HDR encoder limit. Reduce the total pixel count (3072x3072 and 4096x3072 both fit) or split the source into tiles.`
698
+ );
699
+ }
700
+ const bytes = await encodeToKTX2(source.bytes, {
701
+ isHDR: true,
702
+ imageType: header.container,
703
+ isUASTC: true,
704
+ hdrQualityLevel: encoding.level ?? 1,
705
+ needSupercompression: encoding.zstd ?? true,
706
+ generateMipmap: encoding.mipmaps ?? true,
707
+ isKTX2File: true,
708
+ wasmUrl
709
+ });
710
+ return { bytes, mimeType: outputMimeType(encoding), width: header.width, height: header.height };
711
+ }
520
712
  async function encodeKtx2(source, image, encoding, wasmUrl) {
521
713
  const srgb = encoding.colorSpace !== "linear";
522
714
  const bytes = await encodeToKTX2(source.bytes, {
@@ -542,7 +734,9 @@ async function encodeKtx2(source, image, encoding, wasmUrl) {
542
734
  return { bytes, mimeType: outputMimeType(encoding) };
543
735
  }
544
736
  function operationFailure(code, message, cause) {
545
- return cause instanceof CodecLoadError ? failure("codec_load_failed", cause.message, cause.cause) : failure(code, message, cause);
737
+ if (cause instanceof CodecLoadError) return failure("codec_load_failed", cause.message, cause.cause);
738
+ if (cause instanceof SourceError) return failure(cause.code, cause.message);
739
+ return failure(code, message, cause);
546
740
  }
547
741
  function assertNotAborted(signal) {
548
742
  if (signal?.aborted) throw new DOMException("Optimization was aborted", "AbortError");
@@ -988,8 +1182,11 @@ function detectAsset(input) {
988
1182
  if (input.bytes.length >= 4 && input.bytes[0] === 103 && input.bytes[1] === 108 && input.bytes[2] === 84 && input.bytes[3] === 70) {
989
1183
  return success("glb");
990
1184
  }
991
- if (isPng(input.bytes) || isJpeg(input.bytes)) return success("image");
992
- return failure("unsupported_asset", `Unsupported asset: ${input.fileName}; expected GLB, PNG, or JPEG`);
1185
+ if (isPng(input.bytes) || isJpeg(input.bytes) || detectHdrContainer(input.bytes)) return success("image");
1186
+ return failure(
1187
+ "unsupported_asset",
1188
+ `Unsupported asset: ${input.fileName}; expected GLB, PNG, JPEG, EXR, or Radiance HDR`
1189
+ );
993
1190
  }
994
1191
  async function inspectImage(input, mimeType, engine) {
995
1192
  const dimensions = await engine.inspect({ bytes: input.bytes, mimeType });
@@ -1003,6 +1200,8 @@ async function inspectImage(input, mimeType, engine) {
1003
1200
  });
1004
1201
  }
1005
1202
  function imageMimeType(input) {
1203
+ const hdr = detectHdrContainer(input.bytes);
1204
+ if (hdr) return HDR_SOURCE_MIME_TYPES[hdr];
1006
1205
  return isPng(input.bytes) ? "image/png" : "image/jpeg";
1007
1206
  }
1008
1207
  function isPng(bytes) {
@@ -1108,7 +1307,7 @@ async function runConfig(options = {}) {
1108
1307
  const mode = options.mode ?? "write";
1109
1308
  const loaded = options.config ? success(options.config) : await loadConfig(resolve(cwd, options.configPath ?? "chopper.config.ts"));
1110
1309
  if (!loaded.ok) return loaded;
1111
- const planned = await planAssets(loaded.data, cwd, options.outputDirectory);
1310
+ const planned = await planAssets(loaded.data, cwd);
1112
1311
  if (!planned.ok) return planned;
1113
1312
  const chopper2 = options.chopper ?? createNodeChopper();
1114
1313
  const files = await mapConcurrent(
@@ -1116,11 +1315,18 @@ async function runConfig(options = {}) {
1116
1315
  loaded.data.concurrency ?? 2,
1117
1316
  (asset) => executeAsset(asset, mode, cwd, chopper2)
1118
1317
  );
1119
- return success({ mode, files, totals: summarize(files) });
1318
+ return success({ mode, output: relative(cwd, resolve(cwd, loaded.data.output)), files, totals: summarize(files) });
1120
1319
  }
1121
- async function planAssets(config, cwd, outputDirectory) {
1320
+ async function planAssets(config, cwd) {
1122
1321
  const planned = [];
1123
- const outputRoot = outputDirectory ? resolve(cwd, outputDirectory) : void 0;
1322
+ if (typeof config.output !== "string" || !config.output) {
1323
+ return failure("invalid_recipe", "Config output directory is required");
1324
+ }
1325
+ const outputRoot = resolve(cwd, config.output);
1326
+ const relativeRoot = relative(cwd, outputRoot);
1327
+ if (isAbsolute(relativeRoot) || relativeRoot === ".." || relativeRoot.startsWith(`..${sep}`)) {
1328
+ return failure("invalid_recipe", `Output directory must be inside the project: ${config.output}`);
1329
+ }
1124
1330
  for (const rule of config.rules) {
1125
1331
  const valid = validateRecipe(rule.recipe);
1126
1332
  if (!valid.ok) return valid;
@@ -1130,34 +1336,34 @@ async function planAssets(config, cwd, outputDirectory) {
1130
1336
  onlyFiles: true
1131
1337
  });
1132
1338
  for (const match of matches.sort()) {
1133
- const configuredOutput = resolveOutput(rule, match, cwd);
1134
- const relativeOutput = relative(cwd, configuredOutput);
1135
- if (outputRoot && (isAbsolute(relativeOutput) || relativeOutput === ".." || relativeOutput.startsWith(`..${sep}`))) {
1136
- return failure("invalid_recipe", `Cannot stage output outside the project: ${configuredOutput}`);
1339
+ const output = resolveOutput(rule, match, outputRoot);
1340
+ const relativeOutput = relative(outputRoot, output);
1341
+ if (isAbsolute(relativeOutput) || relativeOutput === ".." || relativeOutput.startsWith(`..${sep}`)) {
1342
+ return failure("invalid_recipe", `Output path must stay inside ${config.output}: ${rule.path}`);
1137
1343
  }
1138
1344
  planned.push({
1139
1345
  input: resolve(cwd, match),
1140
- output: outputRoot ? resolve(outputRoot, relativeOutput) : configuredOutput,
1346
+ output,
1141
1347
  rule
1142
1348
  });
1143
1349
  }
1144
1350
  }
1145
- const outputs = /* @__PURE__ */ new Map();
1351
+ const resolved = /* @__PURE__ */ new Map();
1146
1352
  const inputs = new Set(planned.map(({ input }) => input));
1147
1353
  for (const asset of planned) {
1148
- const owner = outputs.get(asset.output);
1149
- if (owner && owner !== asset.input) {
1354
+ const owner = resolved.get(asset.output);
1355
+ if (owner && owner.input !== asset.input) {
1150
1356
  return failure(
1151
1357
  "invalid_recipe",
1152
- `Output collision: ${relative(cwd, owner)} and ${relative(cwd, asset.input)} both write ${relative(cwd, asset.output)}`
1358
+ `Output collision: ${relative(cwd, owner.input)} and ${relative(cwd, asset.input)} both write ${relative(cwd, asset.output)}`
1153
1359
  );
1154
1360
  }
1155
1361
  if (asset.output !== asset.input && inputs.has(asset.output)) {
1156
1362
  return failure("invalid_recipe", `Output loop: ${relative(cwd, asset.output)} is also a matched input`);
1157
1363
  }
1158
- outputs.set(asset.output, asset.input);
1364
+ resolved.set(asset.output, asset);
1159
1365
  }
1160
- return success(planned);
1366
+ return success([...resolved.values()]);
1161
1367
  }
1162
1368
  async function executeAsset(asset, mode, cwd, chopper2) {
1163
1369
  try {
@@ -1200,14 +1406,13 @@ async function executeAsset(asset, mode, cwd, chopper2) {
1200
1406
  };
1201
1407
  }
1202
1408
  }
1203
- function resolveOutput(rule, input, cwd) {
1204
- if (rule.output.mode === "replace") return resolve(cwd, input);
1409
+ function resolveOutput(rule, input, outputRoot) {
1205
1410
  const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
1206
1411
  const inputDirectory = dirname(input) === "." ? "" : dirname(input);
1207
1412
  const name = basename(input, extname(input));
1208
1413
  return resolve(
1209
- cwd,
1210
- rule.output.path.replaceAll("{dir}", inputDirectory).replaceAll("{name}", name).replaceAll("{ext}", extension.slice(1))
1414
+ outputRoot,
1415
+ (rule.path ?? "{dir}/{name}.{ext}").replaceAll("{dir}", inputDirectory).replaceAll("{name}", name).replaceAll("{ext}", extension.slice(1))
1211
1416
  );
1212
1417
  }
1213
1418
  async function writeAtomic(path, bytes) {