@joycostudio/chopper 0.5.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFile, readdir, mkdir, copyFile, mkdtemp, writeFile, rename, rm } from 'fs/promises';
3
- import { extname, parse, join, dirname, resolve, relative, isAbsolute, sep, basename } from 'path';
3
+ import { extname, parse, join, dirname, resolve, relative, isAbsolute, sep } from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { PropertyType, NodeIO } from '@gltf-transform/core';
6
6
  import { ALL_EXTENSIONS, EXTTextureWebP, EXTTextureAVIF, KHRTextureBasisu } from '@gltf-transform/extensions';
@@ -21,6 +21,7 @@ import webpEncoderFactory from '@jsquash/webp/codec/enc/webp_enc.js';
21
21
  import { defaultOptions as defaultOptions$2 } from '@jsquash/webp/meta.js';
22
22
  import { encodeToKTX2 } from 'ktx2-encoder';
23
23
  import { glob } from 'tinyglobby';
24
+ import picomatch from 'picomatch';
24
25
  import { createJiti } from 'jiti';
25
26
 
26
27
  // src/core/recipes.ts
@@ -225,7 +226,7 @@ function latin1(bytes) {
225
226
 
226
227
  // package.json
227
228
  var package_default = {
228
- version: "0.5.4"};
229
+ version: "0.7.0"};
229
230
 
230
231
  // src/codecs/manifest.ts
231
232
  var CODEC_MANIFEST_HASH = "2046d60deb0f9f224743f4404f3c6e8ba5399f81b2811fa50466e93fce3bd322";
@@ -1360,13 +1361,28 @@ function createNodeChopper(options = {}) {
1360
1361
  if (!options.codecDirectory) chopper = created;
1361
1362
  return created;
1362
1363
  }
1364
+
1365
+ // src/config/validation.ts
1366
+ var DEFAULT_OUTPUT = ".chopper-output";
1363
1367
  function validateConfig(config) {
1364
1368
  if (!config || typeof config !== "object" || Array.isArray(config)) {
1365
1369
  return failure("invalid_recipe", "Config must be an object");
1366
1370
  }
1367
1371
  const candidate = config;
1368
- const unknownField = unknownFieldIssue(candidate, ["output", "rules", "concurrency"], "config");
1372
+ const unknownField = unknownFieldIssue(candidate, ["output", "outputDirectory", "rules", "concurrency"], "config");
1369
1373
  if (unknownField) return failure("invalid_recipe", unknownField);
1374
+ if (candidate.output !== void 0 && (typeof candidate.output !== "string" || !candidate.output)) {
1375
+ return failure("invalid_recipe", "Config output must be a non-empty string");
1376
+ }
1377
+ if (candidate.output !== void 0 && !isProjectRelativePath(candidate.output, true)) {
1378
+ return failure("invalid_recipe", `Output directory must be a project-relative POSIX path: ${candidate.output}`);
1379
+ }
1380
+ if (candidate.outputDirectory !== void 0 && !isSafePathSegment(candidate.outputDirectory)) {
1381
+ return failure(
1382
+ "invalid_recipe",
1383
+ `Config outputDirectory must be exactly one safe path segment: ${candidate.outputDirectory}`
1384
+ );
1385
+ }
1370
1386
  if (!Array.isArray(candidate.rules)) {
1371
1387
  return failure("invalid_recipe", "Config rules must be an array");
1372
1388
  }
@@ -1380,10 +1396,182 @@ function validateConfig(config) {
1380
1396
  const entry = rule;
1381
1397
  const ruleUnknownField = unknownFieldIssue(entry, ["include", "exclude", "recipe", "path"], `config rule ${index}`);
1382
1398
  if (ruleUnknownField) return failure("invalid_recipe", ruleUnknownField);
1399
+ if (!isStringArray(entry.include)) {
1400
+ return failure("invalid_recipe", `Config rule ${index} include must be an array of glob patterns`);
1401
+ }
1402
+ if (entry.exclude !== void 0 && !isStringArray(entry.exclude)) {
1403
+ return failure("invalid_recipe", `Config rule ${index} exclude must be an array of glob patterns`);
1404
+ }
1405
+ const invalidGlob = [...entry.include, ...entry.exclude ?? []].find(
1406
+ (pattern) => !isProjectRelativeGlob(pattern)
1407
+ );
1408
+ if (invalidGlob) {
1409
+ return failure("invalid_recipe", `Config rule ${index} glob must be project-relative: ${invalidGlob}`);
1410
+ }
1411
+ if (entry.path !== void 0 && (typeof entry.path !== "string" || !entry.path)) {
1412
+ return failure("invalid_recipe", `Config rule ${index} path must be a non-empty string`);
1413
+ }
1414
+ if (candidate.outputDirectory !== void 0 && entry.path !== void 0) {
1415
+ return failure(
1416
+ "invalid_recipe",
1417
+ `Config rule ${index} path cannot be combined with outputDirectory; authoritative sibling output routing determines the output path`
1418
+ );
1419
+ }
1383
1420
  const recipe = validateRecipe(entry.recipe);
1384
1421
  if (!recipe.ok) return recipe;
1385
1422
  }
1386
- return success(config);
1423
+ return success({ ...config, output: candidate.output ?? DEFAULT_OUTPUT });
1424
+ }
1425
+ function normalizeProjectPath(path) {
1426
+ if (typeof path !== "string") return void 0;
1427
+ if (!isProjectRelativePath(path, false)) return void 0;
1428
+ const parts = [];
1429
+ for (const part of path.split("/")) {
1430
+ if (!part || part === ".") continue;
1431
+ if (part === "..") {
1432
+ if (!parts.length) return void 0;
1433
+ parts.pop();
1434
+ } else {
1435
+ parts.push(part);
1436
+ }
1437
+ }
1438
+ return parts.join("/") || void 0;
1439
+ }
1440
+ function isStringArray(value) {
1441
+ return Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0);
1442
+ }
1443
+ function isSafePathSegment(value) {
1444
+ return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !value.includes("/") && !value.includes("\\") && !value.includes("\0") && !value.includes(":");
1445
+ }
1446
+ function isProjectRelativeGlob(pattern) {
1447
+ const path = pattern.startsWith("!") && !pattern.startsWith("!(") ? pattern.slice(1) : pattern;
1448
+ return path.length > 0 && !path.includes("\0") && !path.startsWith("/") && !/^[A-Za-z]:\//.test(path) && !path.split("/").includes("..");
1449
+ }
1450
+ function isProjectRelativePath(path, allowCurrentDirectory) {
1451
+ if (!path || path.includes("\\") || path.includes("\0") || path.startsWith("/") || /^[A-Za-z]:\//.test(path)) {
1452
+ return false;
1453
+ }
1454
+ const normalized = normalizeSegments(path);
1455
+ return normalized !== void 0 && (allowCurrentDirectory || normalized !== "");
1456
+ }
1457
+ function normalizeSegments(path) {
1458
+ const parts = [];
1459
+ for (const part of path.split("/")) {
1460
+ if (!part || part === ".") continue;
1461
+ if (part === "..") {
1462
+ if (!parts.length) return void 0;
1463
+ parts.pop();
1464
+ } else {
1465
+ parts.push(part);
1466
+ }
1467
+ }
1468
+ return parts.join("/");
1469
+ }
1470
+
1471
+ // src/config/planner.ts
1472
+ var GLOB_OPTIONS = {
1473
+ dot: false,
1474
+ nobrace: false,
1475
+ nocase: false,
1476
+ noextglob: false,
1477
+ noglobstar: false,
1478
+ posix: true
1479
+ };
1480
+ function createConfigAssetPlanner(config) {
1481
+ let prepared;
1482
+ const route = (input) => {
1483
+ prepared ??= prepareRules(config);
1484
+ if (!prepared.ok) return prepared;
1485
+ const normalizedInput = normalizeProjectPath(input);
1486
+ if (!normalizedInput) {
1487
+ return failure("invalid_recipe", `Asset input must be a project-relative POSIX path: ${input}`);
1488
+ }
1489
+ if (prepared.data.outputDirectory && isGeneratedOutput(normalizedInput, prepared.data.outputDirectory)) {
1490
+ return success({ kind: "output", input: normalizedInput });
1491
+ }
1492
+ const planned = /* @__PURE__ */ new Map();
1493
+ for (const { rule, matches } of prepared.data.rules) {
1494
+ if (!matches(normalizedInput)) continue;
1495
+ const output = resolveOutput(rule, normalizedInput, prepared.data.outputDirectory);
1496
+ if (!output.ok) return output;
1497
+ planned.set(output.data, { input: normalizedInput, output: output.data, rule });
1498
+ }
1499
+ const outputs = [...planned.values()];
1500
+ return outputs.length ? success({ kind: "source", input: normalizedInput, outputs }) : success({ kind: "unmatched", input: normalizedInput });
1501
+ };
1502
+ const resolve5 = (input) => {
1503
+ const routed = route(input);
1504
+ if (!routed.ok) return routed;
1505
+ return success(routed.data.kind === "source" ? routed.data.outputs : []);
1506
+ };
1507
+ return { route, resolve: resolve5 };
1508
+ }
1509
+ function prepareRules(config) {
1510
+ const validated = validateConfig(config);
1511
+ if (!validated.ok) return validated;
1512
+ try {
1513
+ return success({
1514
+ outputDirectory: validated.data.outputDirectory,
1515
+ rules: validated.data.rules.map((rule) => ({ rule, matches: compileRuleMatcher(rule) }))
1516
+ });
1517
+ } catch (cause) {
1518
+ return failure("invalid_recipe", "Config contains an invalid glob pattern", cause);
1519
+ }
1520
+ }
1521
+ function compileRuleMatcher(rule) {
1522
+ const includePatterns = [];
1523
+ const ignorePatterns = (rule.exclude ?? []).filter((pattern) => !pattern.startsWith("!") || pattern.startsWith("!("));
1524
+ for (const pattern of rule.include) {
1525
+ if (pattern.startsWith("!") && !pattern.startsWith("!(")) {
1526
+ if (!pattern.startsWith("!!") || pattern.startsWith("!!(")) ignorePatterns.push(pattern.slice(1));
1527
+ } else {
1528
+ includePatterns.push(pattern);
1529
+ }
1530
+ }
1531
+ const include = picomatch(includePatterns.map(expandDirectoryPattern), GLOB_OPTIONS);
1532
+ const ignore = picomatch(ignorePatterns.map(expandDirectoryPattern), GLOB_OPTIONS);
1533
+ return (input) => include(input) && !ignore(input);
1534
+ }
1535
+ function expandDirectoryPattern(pattern) {
1536
+ const normalized = pattern.split("/").filter((segment) => segment && segment !== ".").join("/") || "**";
1537
+ const withoutTrailingSlash = normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
1538
+ return withoutTrailingSlash.endsWith("*") ? withoutTrailingSlash : `${withoutTrailingSlash}/**`;
1539
+ }
1540
+ function resolveOutput(rule, input, outputDirectory) {
1541
+ const slash = input.lastIndexOf("/");
1542
+ const directory = slash < 0 ? "" : input.slice(0, slash);
1543
+ const base = slash < 0 ? input : input.slice(slash + 1);
1544
+ const dot = base.lastIndexOf(".");
1545
+ const name = dot <= 0 ? base : base.slice(0, dot);
1546
+ const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
1547
+ if (outputDirectory) {
1548
+ return success(`${directory ? `${directory}/` : ""}${outputDirectory}/${name}${extension}`);
1549
+ }
1550
+ const template = rule.path ?? "{dir}/{name}.{ext}";
1551
+ if (template.includes("\\") || template.startsWith("/") || /^[A-Za-z]:\//.test(template)) {
1552
+ return failure("invalid_recipe", `Output path must stay inside the configured output directory: ${template}`);
1553
+ }
1554
+ const rendered = template.replaceAll("{dir}/", directory ? `${directory}/` : "").replaceAll("{dir}", directory).replaceAll("{name}", name).replaceAll("{ext}", extension.slice(1));
1555
+ if (/\{[^{}]+\}/.test(rendered)) {
1556
+ return failure("invalid_recipe", `Output path contains an unsupported placeholder: ${template}`);
1557
+ }
1558
+ const output = normalizeProjectPath(rendered);
1559
+ return output ? success(output) : failure("invalid_recipe", `Output path must stay inside the configured output directory: ${template}`);
1560
+ }
1561
+ function isGeneratedOutput(input, outputDirectory) {
1562
+ return input.split("/").slice(0, -1).includes(outputDirectory);
1563
+ }
1564
+
1565
+ // src/config/index.ts
1566
+ function createChopper2(config) {
1567
+ const { output = DEFAULT_OUTPUT, ...rest } = config;
1568
+ const defined = { output, ...rest };
1569
+ const planner = createConfigAssetPlanner(defined);
1570
+ Object.defineProperties(defined, {
1571
+ route: { enumerable: false, value: planner.route },
1572
+ resolve: { enumerable: false, value: planner.resolve }
1573
+ });
1574
+ return defined;
1387
1575
  }
1388
1576
  async function loadConfig(path = "chopper.config.ts") {
1389
1577
  const absolutePath = resolve(path);
@@ -1409,49 +1597,45 @@ async function runConfig(options = {}) {
1409
1597
  const mode = options.mode ?? "write";
1410
1598
  const loaded = options.config ? success(options.config) : await loadConfig(resolve(cwd, options.configPath ?? "chopper.config.ts"));
1411
1599
  if (!loaded.ok) return loaded;
1412
- const planned = await planAssets(loaded.data, cwd);
1600
+ const validated = validateConfig(loaded.data);
1601
+ if (!validated.ok) return validated;
1602
+ const config = validated.data;
1603
+ const planned = await planAssets(config, cwd);
1413
1604
  if (!planned.ok) return planned;
1414
1605
  const chopper2 = options.chopper ?? createNodeChopper();
1415
1606
  const files = await mapConcurrent(
1416
1607
  planned.data,
1417
- loaded.data.concurrency ?? 2,
1608
+ config.concurrency ?? 2,
1418
1609
  (asset) => executeAsset(asset, mode, cwd, chopper2)
1419
1610
  );
1420
- return success({ mode, output: relative(cwd, resolve(cwd, loaded.data.output)), files, totals: summarize(files) });
1611
+ return success({ mode, output: relative(cwd, resolve(cwd, config.output)), files, totals: summarize(files) });
1421
1612
  }
1422
1613
  async function planAssets(config, cwd) {
1423
1614
  const validated = validateConfig(config);
1424
1615
  if (!validated.ok) return validated;
1425
- config = validated.data;
1616
+ const configured = validated.data;
1426
1617
  const planned = [];
1427
- if (typeof config.output !== "string" || !config.output) {
1428
- return failure("invalid_recipe", "Config output directory is required");
1429
- }
1430
- const outputRoot = resolve(cwd, config.output);
1618
+ const outputRoot = resolve(cwd, configured.output);
1431
1619
  const relativeRoot = relative(cwd, outputRoot);
1432
1620
  if (isAbsolute(relativeRoot) || relativeRoot === ".." || relativeRoot.startsWith(`..${sep}`)) {
1433
- return failure("invalid_recipe", `Output directory must be inside the project: ${config.output}`);
1434
- }
1435
- for (const rule of config.rules) {
1436
- const valid = validateRecipe(rule.recipe);
1437
- if (!valid.ok) return valid;
1438
- const matches = await glob(rule.include, {
1439
- cwd,
1440
- ignore: rule.exclude,
1441
- onlyFiles: true
1442
- });
1443
- for (const match of matches.sort()) {
1444
- const output = resolveOutput(rule, match, outputRoot);
1445
- const relativeOutput = relative(outputRoot, output);
1446
- if (isAbsolute(relativeOutput) || relativeOutput === ".." || relativeOutput.startsWith(`..${sep}`)) {
1447
- return failure("invalid_recipe", `Output path must stay inside ${config.output}: ${rule.path}`);
1448
- }
1449
- planned.push({
1450
- input: resolve(cwd, match),
1451
- output,
1621
+ return failure("invalid_recipe", `Output directory must be inside the project: ${configured.output}`);
1622
+ }
1623
+ const planner = createChopper2(configured);
1624
+ const discoveryPatterns = configured.rules.flatMap(
1625
+ ({ include }) => include.filter((pattern) => !pattern.startsWith("!") || pattern.startsWith("!("))
1626
+ );
1627
+ const matches = await glob(discoveryPatterns, { cwd, onlyFiles: true });
1628
+ for (const match of matches.sort()) {
1629
+ const routed = planner.route(match);
1630
+ if (!routed.ok) return routed;
1631
+ if (routed.data.kind !== "source") continue;
1632
+ planned.push(
1633
+ ...routed.data.outputs.map(({ input, output, rule }) => ({
1634
+ input: resolve(cwd, input),
1635
+ output: resolve(outputRoot, output),
1452
1636
  rule
1453
- });
1454
- }
1637
+ }))
1638
+ );
1455
1639
  }
1456
1640
  const resolved = /* @__PURE__ */ new Map();
1457
1641
  const inputs = new Set(planned.map(({ input }) => input));
@@ -1512,15 +1696,6 @@ async function executeAsset(asset, mode, cwd, chopper2) {
1512
1696
  };
1513
1697
  }
1514
1698
  }
1515
- function resolveOutput(rule, input, outputRoot) {
1516
- const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
1517
- const inputDirectory = dirname(input) === "." ? "" : dirname(input);
1518
- const name = basename(input, extname(input));
1519
- return resolve(
1520
- outputRoot,
1521
- (rule.path ?? "{dir}/{name}.{ext}").replaceAll("{dir}", inputDirectory).replaceAll("{name}", name).replaceAll("{ext}", extension.slice(1))
1522
- );
1523
- }
1524
1699
  async function writeAtomic(path, bytes) {
1525
1700
  await mkdir(dirname(path), { recursive: true });
1526
1701
  const temporaryDirectory = await mkdtemp(join(dirname(path), ".chopper-"));