@joycostudio/chopper 0.8.0 → 0.9.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.
@@ -156,7 +156,28 @@ interface UastcHdrEncoding {
156
156
  zstd?: boolean;
157
157
  }
158
158
  type RasterEncoding = WebpEncoding | AvifEncoding | JpegEncoding | PngEncoding;
159
- type ImageEncoding = RasterEncoding | UastcEncoding | Etc1sEncoding | UastcHdrEncoding;
159
+ /** Standalone, lossless RGBA8 texels. Color-space metadata never transforms samples. */
160
+ type RawKtx2Encoding = {
161
+ /** Store decoded RGBA8 pixels in KTX2. */
162
+ codec: 'ktx2';
163
+ /** Preserve original dimensions and every decoded RGBA8 byte, including transparent RGB. */
164
+ mode: 'raw';
165
+ /** Label unchanged samples; alpha is always linear. @defaultValue `'linear'` */
166
+ colorSpace?: 'linear' | 'srgb';
167
+ /** Raw mode stores exactly one base level. @defaultValue `false` */
168
+ mipmaps?: false;
169
+ } & ({
170
+ /** Compress the texels for delivery; GPU storage remains RGBA8. @defaultValue `true` */
171
+ zstd?: true;
172
+ /** Offline compression effort, integer 1–19; never changes fidelity. @defaultValue `19` */
173
+ zstdLevel?: number;
174
+ } | {
175
+ /** Store texels without supercompression. */
176
+ zstd: false;
177
+ /** Effort is unavailable when Zstandard is disabled. */
178
+ zstdLevel?: never;
179
+ });
180
+ type ImageEncoding = RasterEncoding | UastcEncoding | Etc1sEncoding | UastcHdrEncoding | RawKtx2Encoding;
160
181
  type GlbProperty = 'accessor' | 'animation' | 'buffer' | 'camera' | 'material' | 'mesh' | 'node' | 'primitive' | 'primitiveTarget' | 'skin' | 'texture';
161
182
  type GlbMethodRecipe = {
162
183
  /** Merge equivalent accessors, materials, meshes, skins, or textures. */
@@ -219,8 +240,8 @@ interface EmbeddedTextureRecipe {
219
240
  label: string;
220
241
  /** Textures to encode. A texture cannot be claimed by more than one selector. */
221
242
  select: TextureSelector;
222
- /** Output encoding for the selected textures. UASTC HDR is not supported inside GLBs. */
223
- encode: ImageEncoding;
243
+ /** Output encoding for the selected textures. Raw RGBA8 and UASTC HDR are not supported inside GLBs. */
244
+ encode: Exclude<ImageEncoding, RawKtx2Encoding>;
224
245
  }
225
246
  type GeometryEncoding = {
226
247
  /** Compress geometry with `KHR_draco_mesh_compression` for broad decoder support. */
@@ -280,6 +301,29 @@ interface ChopperRule {
280
301
  exclude?: readonly string[];
281
302
  /** Optimization recipe applied to every asset matched by this rule. */
282
303
  recipe: AssetRecipe;
304
+ /**
305
+ * Builds the output file name, without extension, for each matched source.
306
+ * Chopper still owns the directory (the reserved {@link ChopperConfig.outputDirectory}
307
+ * sibling) and the extension (derived from the recipe codec), so the builder
308
+ * only names the file. The result must be one safe path segment.
309
+ *
310
+ * Use it to let several rules produce distinct outputs from one source, such
311
+ * as a smaller mobile encoding next to the desktop one:
312
+ * `filename: ({ name }) => name + '_mobile'`.
313
+ *
314
+ * @defaultValue `({ name }) => name`
315
+ */
316
+ filename?: (source: ChopperFilenameSource) => string;
317
+ }
318
+ interface ChopperFilenameSource {
319
+ /** Project-relative POSIX path of the matched source, such as `assets/hero.png`. */
320
+ input: string;
321
+ /** Source directory, such as `assets`, or `''` at the project root. */
322
+ directory: string;
323
+ /** Source file name without its extension, such as `hero`. */
324
+ name: string;
325
+ /** Recipe of the rule being planned. */
326
+ recipe: AssetRecipe;
283
327
  }
284
328
  interface ChopperConfig {
285
329
  /**
@@ -303,9 +347,10 @@ interface ChopperConfig {
303
347
  * Given `assets/wall.png` and `outputDirectory: 'compressed'`, a WebP
304
348
  * recipe resolves to `assets/compressed/wall.webp`. Inputs already inside
305
349
  * this directory are classified as generated outputs and are never
306
- * processed again. Rules choose which assets and recipes apply; this
307
- * config-level property is the sole authority for where their logical
308
- * outputs go. This logical segment is independent of
350
+ * processed again. Rules choose which assets and recipes apply, and may
351
+ * name the output file with {@link ChopperRule.filename}; this config-level
352
+ * property is the sole authority for which directory their logical outputs
353
+ * go to. This logical segment is independent of
309
354
  * {@link buildDirectory}, the physical filesystem root used by Node and the
310
355
  * CLI.
311
356
  *
@@ -367,4 +412,4 @@ declare function createChopper<const T extends ChopperConfig>(config: T & NoUnkn
367
412
  /** @deprecated Use {@link createChopper} instead. */
368
413
  declare const defineConfig: typeof createChopper;
369
414
 
370
- export { COLOR_TEXTURE_SLOTS, type ChopperConfig, type ChopperRule, type ConfigAssetPlanner, type ConfigRoute, type ConfiguredChopper, DATA_TEXTURE_SLOTS, DIRECTIONAL_TEXTURE_SLOTS, type PlannedConfigAsset, createChopper, defineConfig, defineRecipe };
415
+ export { COLOR_TEXTURE_SLOTS, type ChopperConfig, type ChopperFilenameSource, type ChopperRule, type ConfigAssetPlanner, type ConfigRoute, type ConfiguredChopper, DATA_TEXTURE_SLOTS, DIRECTIONAL_TEXTURE_SLOTS, type PlannedConfigAsset, createChopper, defineConfig, defineRecipe };
@@ -102,6 +102,9 @@ function recipeShapeIssue(recipe) {
102
102
  if (!Array.isArray(selector[valueField])) return "Texture recipe selectors are malformed";
103
103
  const encodingIssue2 = encodingShapeIssue(entry.encode);
104
104
  if (encodingIssue2) return encodingIssue2;
105
+ if (entry.encode.codec === "ktx2" && entry.encode.mode === "raw") {
106
+ return `Texture recipe "${entry.label}" uses raw RGBA8, which KHR_texture_basisu does not cover; raw mode is only supported for standalone image recipes`;
107
+ }
105
108
  }
106
109
  if (candidate.geometry !== void 0 && candidate.geometry !== false && (!candidate.geometry || typeof candidate.geometry !== "object" || !["draco", "meshopt"].includes(String(candidate.geometry.codec)))) {
107
110
  return "GLB geometry must be false, Draco, or Meshopt";
@@ -122,15 +125,18 @@ function encodingShapeIssue(encoding) {
122
125
  if (!["webp", "avif", "jpeg", "png", "ktx2"].includes(String(candidate.codec))) {
123
126
  return `Unsupported image codec: ${String(candidate.codec)}`;
124
127
  }
125
- if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s" && candidate.mode !== "uastc-hdr") {
128
+ if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s" && candidate.mode !== "raw" && candidate.mode !== "uastc-hdr") {
126
129
  return `Unsupported KTX2 mode: ${String(candidate.mode)}`;
127
130
  }
128
131
  if (candidate.codec === "ktx2" && candidate.mode === "uastc-hdr" && candidate.maxSize !== void 0) {
129
132
  return "UASTC HDR does not support maxSize; resizing requires a decoded 8-bit image. Author the source at its target resolution.";
130
133
  }
131
- const allowedFields = candidate.codec === "webp" ? ["codec", "maxSize", "quality", "effort", "lossless", "nearLossless"] : candidate.codec === "avif" ? ["codec", "maxSize", "quality", "effort", "lossless", "chromaSubsampling"] : candidate.codec === "jpeg" ? ["codec", "maxSize", "quality", "chromaSubsampling"] : candidate.codec === "png" ? ["codec", "maxSize"] : candidate.mode === "uastc" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "level", "mipmaps", "zstd", "rdo"] : candidate.mode === "etc1s" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "quality", "compression", "mipmaps"] : ["codec", "mode", "level", "mipmaps", "zstd"];
134
+ const allowedFields = candidate.codec === "webp" ? ["codec", "maxSize", "quality", "effort", "lossless", "nearLossless"] : candidate.codec === "avif" ? ["codec", "maxSize", "quality", "effort", "lossless", "chromaSubsampling"] : candidate.codec === "jpeg" ? ["codec", "maxSize", "quality", "chromaSubsampling"] : candidate.codec === "png" ? ["codec", "maxSize"] : candidate.mode === "uastc" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "level", "mipmaps", "zstd", "rdo"] : candidate.mode === "etc1s" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "quality", "compression", "mipmaps"] : candidate.mode === "raw" ? ["codec", "mode", "colorSpace", "mipmaps", "zstd", "zstdLevel"] : ["codec", "mode", "level", "mipmaps", "zstd"];
132
135
  const unknownField = unknownFieldIssue(candidate, allowedFields, "image encoding");
133
136
  if (unknownField) return unknownField;
137
+ if (candidate.codec === "ktx2" && candidate.mode === "raw" && candidate.zstd === false && candidate.zstdLevel !== void 0) {
138
+ return "Raw KTX2 zstdLevel requires Zstandard supercompression";
139
+ }
134
140
  if (candidate.codec === "ktx2" && candidate.mode === "uastc" && candidate.rdo !== void 0) {
135
141
  if (!candidate.rdo || typeof candidate.rdo !== "object" || Array.isArray(candidate.rdo)) {
136
142
  return "UASTC RDO must be an object";
@@ -186,6 +192,18 @@ function selectorValues(selector) {
186
192
  return success(selector.indices);
187
193
  }
188
194
  function encodingIssue(encoding) {
195
+ if (encoding.codec === "ktx2" && encoding.mode === "raw") {
196
+ if (encoding.colorSpace !== void 0 && encoding.colorSpace !== "linear" && encoding.colorSpace !== "srgb") {
197
+ return "Raw KTX2 colorSpace must be linear or srgb";
198
+ }
199
+ if (encoding.mipmaps !== void 0 && encoding.mipmaps !== false) return "Raw KTX2 mipmaps must be false";
200
+ if (encoding.zstd !== void 0 && typeof encoding.zstd !== "boolean") return "Raw KTX2 zstd must be a boolean";
201
+ if (encoding.zstdLevel !== void 0) {
202
+ if (!Number.isInteger(encoding.zstdLevel) || encoding.zstdLevel < 1 || encoding.zstdLevel > 19) {
203
+ return "Raw KTX2 zstdLevel must be an integer between 1 and 19";
204
+ }
205
+ }
206
+ }
189
207
  if ("maxSize" in encoding && encoding.maxSize) {
190
208
  const [width, height] = encoding.maxSize;
191
209
  if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
@@ -264,7 +282,11 @@ function validateConfig(config) {
264
282
  return failure("invalid_recipe", `Config rule ${index} must be an object`);
265
283
  }
266
284
  const entry = rule;
267
- const ruleUnknownField = unknownFieldIssue(entry, ["include", "exclude", "recipe"], `config rule ${index}`);
285
+ const ruleUnknownField = unknownFieldIssue(
286
+ entry,
287
+ ["include", "exclude", "recipe", "filename"],
288
+ `config rule ${index}`
289
+ );
268
290
  if (ruleUnknownField) return failure("invalid_recipe", ruleUnknownField);
269
291
  if (!isStringArray(entry.include)) {
270
292
  return failure("invalid_recipe", `Config rule ${index} include must be an array of glob patterns`);
@@ -278,6 +300,9 @@ function validateConfig(config) {
278
300
  if (invalidGlob) {
279
301
  return failure("invalid_recipe", `Config rule ${index} glob must be project-relative: ${invalidGlob}`);
280
302
  }
303
+ if (entry.filename !== void 0 && typeof entry.filename !== "function") {
304
+ return failure("invalid_recipe", `Config rule ${index} filename must be a function`);
305
+ }
281
306
  const recipe = validateRecipe(entry.recipe);
282
307
  if (!recipe.ok) return recipe;
283
308
  }
@@ -358,7 +383,8 @@ function createConfigAssetPlanner(config) {
358
383
  for (const { rule, matches } of prepared.data.rules) {
359
384
  if (!matches(normalizedInput)) continue;
360
385
  const output = resolveOutput(rule, normalizedInput, prepared.data.outputDirectory);
361
- planned.set(output, { input: normalizedInput, output, rule });
386
+ if (!output.ok) return output;
387
+ planned.set(output.data, { input: normalizedInput, output: output.data, rule });
362
388
  }
363
389
  const outputs = [...planned.values()];
364
390
  return outputs.length ? success({ kind: "source", input: normalizedInput, outputs }) : success({ kind: "unmatched", input: normalizedInput });
@@ -370,6 +396,133 @@ function createConfigAssetPlanner(config) {
370
396
  };
371
397
  return { route, resolve };
372
398
  }
399
+ var EXPANSION_LIMIT = 64;
400
+ var FILLERS = ["x", "q", "chopper"];
401
+ function findRuleOverrides(config) {
402
+ const prepared = prepareRules(config);
403
+ if (!prepared.ok) return [];
404
+ const { rules, outputDirectory } = prepared.data;
405
+ const patterns = rules.map(({ rule }) => parsedIncludes(rule));
406
+ const overrides = [];
407
+ for (let later = 1; later < rules.length; later++) {
408
+ for (let earlier = 0; earlier < later; earlier++) {
409
+ const witness = FILLERS.flatMap(
410
+ (filler) => patterns[earlier].flatMap((a) => patterns[later].map((b) => intersectPaths(a, b, filler)))
411
+ ).sort((a = "", b = "") => a.split("/").length - b.split("/").length || a.length - b.length).map((input) => {
412
+ if (!input || isGeneratedOutput(input, outputDirectory)) return void 0;
413
+ if (!rules[earlier].matches(input) || !rules[later].matches(input)) return void 0;
414
+ const first = resolveOutput(rules[earlier].rule, input, outputDirectory);
415
+ const second = resolveOutput(rules[later].rule, input, outputDirectory);
416
+ return first.ok && second.ok && first.data === second.data ? { input, output: first.data } : void 0;
417
+ }).find(Boolean);
418
+ if (witness) overrides.push({ earlier, later, ...witness });
419
+ }
420
+ }
421
+ return overrides;
422
+ }
423
+ var STAR_SEGMENT = [{ star: true }];
424
+ function parsedIncludes(rule) {
425
+ return rule.include.filter((pattern) => !pattern.startsWith("!") || pattern.startsWith("!(")).flatMap((pattern) => expandBraces(expandDirectoryPattern(pattern))).map((pattern) => pattern.split("/").map((segment) => segment === "**" ? "globstar" : parseSegment(segment)));
426
+ }
427
+ function parseSegment(segment) {
428
+ const literal = (char) => ({ star: false, accepts: (c) => c === char, hints: char });
429
+ const tokens = [];
430
+ for (let index = 0; index < segment.length; index++) {
431
+ const char = segment[index];
432
+ const end = char === "[" ? segment.indexOf("]", index + 2) : -1;
433
+ if (char === "*") {
434
+ if (!tokens.at(-1)?.star) tokens.push({ star: true });
435
+ } else if (char === "?") {
436
+ tokens.push({ star: false, accepts: () => true, hints: "" });
437
+ } else if (end > 0) {
438
+ const body = segment.slice(index + 1, end);
439
+ try {
440
+ const set = new RegExp(`^[${body.replace(/^!/, "^")}]$`);
441
+ tokens.push({ star: false, accepts: (c) => set.test(c), hints: body });
442
+ index = end;
443
+ } catch {
444
+ tokens.push(literal(char));
445
+ }
446
+ } else if (char === "\\" && index + 1 < segment.length) {
447
+ tokens.push(literal(segment[++index]));
448
+ } else {
449
+ tokens.push(literal(char));
450
+ }
451
+ }
452
+ return tokens;
453
+ }
454
+ function intersectPaths(a, b, filler) {
455
+ const memo = /* @__PURE__ */ new Map();
456
+ const cons = (head, rest) => head && rest ? [head, ...rest] : null;
457
+ const visit = (i, j) => {
458
+ const key = i * (b.length + 1) + j;
459
+ if (memo.has(key)) return memo.get(key);
460
+ const x = a[i];
461
+ const y = b[j];
462
+ let result = null;
463
+ if (!x && !y) result = [];
464
+ else if (x === "globstar" && y === "globstar") {
465
+ result = visit(i + 1, j) ?? visit(i, j + 1);
466
+ } else if (x === "globstar") {
467
+ result = visit(i + 1, j) ?? (y && y !== "globstar" ? cons(intersectSegments(y, STAR_SEGMENT, filler), visit(i, j + 1)) : null);
468
+ } else if (y === "globstar") {
469
+ result = visit(i, j + 1) ?? (x ? cons(intersectSegments(x, STAR_SEGMENT, filler), visit(i + 1, j)) : null);
470
+ } else if (x && y) {
471
+ result = cons(intersectSegments(x, y, filler), visit(i + 1, j + 1));
472
+ }
473
+ memo.set(key, result);
474
+ return result;
475
+ };
476
+ const path = visit(0, 0);
477
+ return path ? path.join("/") || filler : void 0;
478
+ }
479
+ function intersectSegments(a, b, filler) {
480
+ const memo = /* @__PURE__ */ new Map();
481
+ const prefix = (char, rest) => char !== void 0 && rest !== null ? char + rest : null;
482
+ const visit = (i, j) => {
483
+ const key = i * (b.length + 1) + j;
484
+ if (memo.has(key)) return memo.get(key);
485
+ const x = a[i];
486
+ const y = b[j];
487
+ let result = null;
488
+ if (!x && !y) result = "";
489
+ else if (x?.star && y?.star) {
490
+ result = prefix(filler, visit(i + 1, j)) ?? prefix(filler, visit(i, j + 1)) ?? visit(i + 1, j) ?? visit(i, j + 1);
491
+ } else if (x?.star) result = visit(i + 1, j) ?? (y && !y.star ? prefix(pickChar(filler, y), visit(i, j + 1)) : null);
492
+ else if (y?.star) result = visit(i, j + 1) ?? (x && !x.star ? prefix(pickChar(filler, x), visit(i + 1, j)) : null);
493
+ else if (x && y && !x.star && !y.star) result = prefix(pickChar(filler, x, y), visit(i + 1, j + 1));
494
+ memo.set(key, result);
495
+ return result;
496
+ };
497
+ return visit(0, 0) || void 0;
498
+ }
499
+ function pickChar(filler, ...tokens) {
500
+ const candidates = `${tokens.map(({ hints }) => hints).join("")}${filler}xa0_-`;
501
+ return [...candidates].find((char) => char !== "/" && tokens.every(({ accepts }) => accepts(char)));
502
+ }
503
+ function expandBraces(pattern) {
504
+ const open = pattern.indexOf("{");
505
+ if (open < 0) return [pattern];
506
+ let depth = 0;
507
+ const commas = [];
508
+ for (let index = open; index < pattern.length; index++) {
509
+ const char = pattern[index];
510
+ if (char === "{") depth++;
511
+ else if (char === "," && depth === 1) commas.push(index);
512
+ else if (char === "}" && --depth === 0) {
513
+ if (!commas.length) return [pattern];
514
+ const bounds = [open, ...commas, index];
515
+ const head = pattern.slice(0, open);
516
+ const tail = expandBraces(pattern.slice(index + 1));
517
+ return bounds.slice(1).flatMap(
518
+ (end, alternative) => expandBraces(pattern.slice(bounds[alternative] + 1, end)).flatMap(
519
+ (middle) => tail.map((rest) => `${head}${middle}${rest}`)
520
+ )
521
+ ).slice(0, EXPANSION_LIMIT);
522
+ }
523
+ }
524
+ return [pattern];
525
+ }
373
526
  function prepareRules(config) {
374
527
  const validated = validateConfig(config);
375
528
  if (!validated.ok) return validated;
@@ -408,7 +561,21 @@ function resolveOutput(rule, input, outputDirectory) {
408
561
  const dot = base.lastIndexOf(".");
409
562
  const name = dot <= 0 ? base : base.slice(0, dot);
410
563
  const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
411
- return `${directory ? `${directory}/` : ""}${outputDirectory}/${name}${extension}`;
564
+ let filename = name;
565
+ if (rule.filename) {
566
+ try {
567
+ filename = rule.filename({ input, directory, name, recipe: rule.recipe });
568
+ } catch (cause) {
569
+ return failure("invalid_recipe", `Config rule filename threw for ${input}`, cause);
570
+ }
571
+ if (!isSafePathSegment(filename)) {
572
+ return failure(
573
+ "invalid_recipe",
574
+ `Config rule filename must return exactly one safe path segment for ${input}: ${String(filename)}`
575
+ );
576
+ }
577
+ }
578
+ return success(`${directory ? `${directory}/` : ""}${outputDirectory}/${filename}${extension}`);
412
579
  }
413
580
  function isGeneratedOutput(input, outputDirectory) {
414
581
  return input.split("/").slice(0, -1).includes(outputDirectory);
@@ -419,12 +586,26 @@ function createChopper(config) {
419
586
  const { buildDirectory = DEFAULT_BUILD_DIRECTORY, outputDirectory = DEFAULT_OUTPUT_DIRECTORY, ...rest } = config;
420
587
  const defined = { buildDirectory, outputDirectory, ...rest };
421
588
  const planner = createConfigAssetPlanner(defined);
589
+ if (isDevelopment()) {
590
+ for (const { earlier, later, input, output } of findRuleOverrides(defined)) {
591
+ console.warn(
592
+ `[chopper] Rule ${later} overrides rule ${earlier} wherever both match, e.g. ${input} \u2192 ${output}. The later rule wins.`
593
+ );
594
+ }
595
+ }
422
596
  Object.defineProperties(defined, {
423
597
  route: { enumerable: false, value: planner.route },
424
598
  resolve: { enumerable: false, value: planner.resolve }
425
599
  });
426
600
  return defined;
427
601
  }
602
+ function isDevelopment() {
603
+ try {
604
+ return process.env.NODE_ENV !== "production";
605
+ } catch {
606
+ return false;
607
+ }
608
+ }
428
609
  var defineConfig = createChopper;
429
610
 
430
611
  export { COLOR_TEXTURE_SLOTS, DATA_TEXTURE_SLOTS, DIRECTIONAL_TEXTURE_SLOTS, createChopper, defineConfig, defineRecipe };