@joycostudio/chopper 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -0
- package/THIRD_PARTY_NOTICES.md +19 -0
- package/codecs/avif_enc.wasm +0 -0
- package/codecs/basis_encoder.wasm +0 -0
- package/codecs/draco_decoder_gltf.js +116 -0
- package/codecs/draco_decoder_gltf.wasm +0 -0
- package/codecs/draco_encoder.wasm +0 -0
- package/codecs/draco_encoder_gltf.js +98 -0
- package/codecs/manifest.json +86 -0
- package/codecs/mozjpeg_dec.wasm +0 -0
- package/codecs/mozjpeg_enc.wasm +0 -0
- package/codecs/squoosh_png_bg.wasm +0 -0
- package/codecs/squoosh_resize_bg.wasm +0 -0
- package/codecs/webp_enc.wasm +0 -0
- package/dist/browser/chunk-5WRI5ZAA.js +29 -0
- package/dist/browser/chunk-5WRI5ZAA.js.map +1 -0
- package/dist/browser/chunk-OTTLKWP4.js +105 -0
- package/dist/browser/chunk-OTTLKWP4.js.map +1 -0
- package/dist/browser/in-process-V4NPIVZF.js +26747 -0
- package/dist/browser/in-process-V4NPIVZF.js.map +1 -0
- package/dist/browser/index.d.ts +244 -0
- package/dist/browser/index.js +86 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/node-shim-3YE6NHES.js +16 -0
- package/dist/browser/node-shim-3YE6NHES.js.map +1 -0
- package/dist/browser/worker.d.ts +2 -0
- package/dist/browser/worker.js +27425 -0
- package/dist/browser/worker.js.map +1 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +1421 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/config/index.d.ts +123 -0
- package/dist/config/index.js +9 -0
- package/dist/config/index.js.map +1 -0
- package/dist/index.d.ts +367 -0
- package/dist/index.js +396 -0
- package/dist/index.js.map +1 -0
- package/dist/node/index.d.ts +346 -0
- package/dist/node/index.js +1266 -0
- package/dist/node/index.js.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,1266 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import { readFile, mkdir, mkdtemp, writeFile, rename, rm, readdir, copyFile } from 'fs/promises';
|
|
3
|
+
import { join, resolve, dirname, relative, basename, extname } from 'path';
|
|
4
|
+
import avifEncoderFactory from '@jsquash/avif/codec/enc/avif_enc.js';
|
|
5
|
+
import { defaultOptions as defaultOptions$1 } from '@jsquash/avif/meta.js';
|
|
6
|
+
import jpegDecoderFactory from '@jsquash/jpeg/codec/dec/mozjpeg_dec.js';
|
|
7
|
+
import jpegEncoderFactory from '@jsquash/jpeg/codec/enc/mozjpeg_enc.js';
|
|
8
|
+
import { defaultOptions } from '@jsquash/jpeg/meta.js';
|
|
9
|
+
import decodePng, { init } from '@jsquash/png/decode.js';
|
|
10
|
+
import encodePng, { init as init$1 } from '@jsquash/png/encode.js';
|
|
11
|
+
import resize, { initResize } from '@jsquash/resize';
|
|
12
|
+
import { initEmscriptenModule } from '@jsquash/webp/utils.js';
|
|
13
|
+
import webpEncoderFactory from '@jsquash/webp/codec/enc/webp_enc.js';
|
|
14
|
+
import { defaultOptions as defaultOptions$2 } from '@jsquash/webp/meta.js';
|
|
15
|
+
import { encodeToKTX2 } from 'ktx2-encoder';
|
|
16
|
+
import { PropertyType, NodeIO } from '@gltf-transform/core';
|
|
17
|
+
import { ALL_EXTENSIONS, EXTTextureWebP, EXTTextureAVIF, KHRTextureBasisu } from '@gltf-transform/extensions';
|
|
18
|
+
import draco3d from 'draco3dgltf';
|
|
19
|
+
import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
|
|
20
|
+
import { draco, meshopt, resample, prune, dedup, listTextureSlots } from '@gltf-transform/functions';
|
|
21
|
+
import { createJiti } from 'jiti';
|
|
22
|
+
import { glob } from 'tinyglobby';
|
|
23
|
+
|
|
24
|
+
// src/node/image-engine.ts
|
|
25
|
+
|
|
26
|
+
// src/core/recipes.ts
|
|
27
|
+
var RECIPE_SCHEMA_VERSION = 1;
|
|
28
|
+
function outputExtension(encoding) {
|
|
29
|
+
if (encoding.codec === "ktx2") return ".ktx2";
|
|
30
|
+
if (encoding.codec === "jpeg") return ".jpg";
|
|
31
|
+
return `.${encoding.codec}`;
|
|
32
|
+
}
|
|
33
|
+
function outputMimeType(encoding) {
|
|
34
|
+
if (encoding.codec === "ktx2") return "image/ktx2";
|
|
35
|
+
return `image/${encoding.codec}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/core/result.ts
|
|
39
|
+
var success = (data) => ({ ok: true, data });
|
|
40
|
+
var failure = (code, message, cause) => ({
|
|
41
|
+
ok: false,
|
|
42
|
+
error: cause === void 0 ? { code, message } : { code, message, cause }
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// src/core/validation.ts
|
|
46
|
+
function validateRecipe(recipe) {
|
|
47
|
+
const shapeIssue = recipeShapeIssue(recipe);
|
|
48
|
+
if (shapeIssue) return failure("invalid_recipe", shapeIssue);
|
|
49
|
+
try {
|
|
50
|
+
const typedRecipe = recipe;
|
|
51
|
+
const issue = recipeIssue(typedRecipe);
|
|
52
|
+
return issue ? failure("invalid_recipe", issue) : success(typedRecipe);
|
|
53
|
+
} catch {
|
|
54
|
+
return failure("invalid_recipe", "Recipe contains malformed fields");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function normalizeRecipe(value) {
|
|
58
|
+
const validated = validateRecipe(value);
|
|
59
|
+
if (!validated.ok) return validated;
|
|
60
|
+
const recipe = validated.data;
|
|
61
|
+
if (recipe.kind === "image") {
|
|
62
|
+
return success({
|
|
63
|
+
schemaVersion: RECIPE_SCHEMA_VERSION,
|
|
64
|
+
kind: "image",
|
|
65
|
+
encode: normalizeEncoding(recipe.encode)
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return success({
|
|
69
|
+
schemaVersion: RECIPE_SCHEMA_VERSION,
|
|
70
|
+
kind: "glb",
|
|
71
|
+
methods: recipe.methods ?? [],
|
|
72
|
+
textures: (recipe.textures ?? []).map((texture) => ({
|
|
73
|
+
...texture,
|
|
74
|
+
encode: normalizeEncoding(texture.encode)
|
|
75
|
+
})),
|
|
76
|
+
geometry: recipe.geometry ?? false
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
function recipeShapeIssue(recipe) {
|
|
80
|
+
if (!recipe || typeof recipe !== "object") return "Recipe must be an object";
|
|
81
|
+
const candidate = recipe;
|
|
82
|
+
if (candidate.kind !== "image" && candidate.kind !== "glb") {
|
|
83
|
+
return `Unsupported recipe kind: ${String(candidate.kind)}`;
|
|
84
|
+
}
|
|
85
|
+
if (candidate.kind === "image") {
|
|
86
|
+
return encodingShapeIssue(candidate.encode);
|
|
87
|
+
}
|
|
88
|
+
if (candidate.methods !== void 0 && !Array.isArray(candidate.methods)) {
|
|
89
|
+
return "GLB methods must be an array";
|
|
90
|
+
}
|
|
91
|
+
for (const method of candidate.methods ?? []) {
|
|
92
|
+
if (!method || typeof method !== "object" || !["dedup", "prune", "resample"].includes(String(method.method))) {
|
|
93
|
+
return "GLB methods contain an unsupported transform";
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (candidate.textures !== void 0 && !Array.isArray(candidate.textures)) {
|
|
97
|
+
return "GLB textures must be an array";
|
|
98
|
+
}
|
|
99
|
+
for (const texture of candidate.textures ?? []) {
|
|
100
|
+
if (!texture || typeof texture !== "object") return "Texture recipes must be objects";
|
|
101
|
+
const entry = texture;
|
|
102
|
+
if (typeof entry.label !== "string") return "Texture recipe labels must be strings";
|
|
103
|
+
if (!entry.select || typeof entry.select !== "object") return "Texture recipes require a selector";
|
|
104
|
+
const selector = entry.select;
|
|
105
|
+
const values = selector[selector.by === "slot" ? "slots" : selector.by === "name" ? "names" : "indices"];
|
|
106
|
+
if (!["slot", "name", "index"].includes(String(selector.by)) || !Array.isArray(values)) {
|
|
107
|
+
return "Texture recipe selectors are malformed";
|
|
108
|
+
}
|
|
109
|
+
const encodingIssue2 = encodingShapeIssue(entry.encode);
|
|
110
|
+
if (encodingIssue2) return encodingIssue2;
|
|
111
|
+
}
|
|
112
|
+
if (candidate.geometry !== void 0 && candidate.geometry !== false && (!candidate.geometry || typeof candidate.geometry !== "object" || !["draco", "meshopt"].includes(String(candidate.geometry.codec)))) {
|
|
113
|
+
return "GLB geometry must be false, Draco, or Meshopt";
|
|
114
|
+
}
|
|
115
|
+
return void 0;
|
|
116
|
+
}
|
|
117
|
+
function encodingShapeIssue(encoding) {
|
|
118
|
+
if (!encoding || typeof encoding !== "object") return "Image encoding must be an object";
|
|
119
|
+
const candidate = encoding;
|
|
120
|
+
if (!["webp", "avif", "jpeg", "png", "ktx2"].includes(String(candidate.codec))) {
|
|
121
|
+
return `Unsupported image codec: ${String(candidate.codec)}`;
|
|
122
|
+
}
|
|
123
|
+
if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s") {
|
|
124
|
+
return `Unsupported KTX2 mode: ${String(candidate.mode)}`;
|
|
125
|
+
}
|
|
126
|
+
return void 0;
|
|
127
|
+
}
|
|
128
|
+
function recipeIssue(recipe) {
|
|
129
|
+
if (recipe.schemaVersion !== RECIPE_SCHEMA_VERSION) {
|
|
130
|
+
return `Unsupported recipe schema version: ${String(recipe.schemaVersion)}`;
|
|
131
|
+
}
|
|
132
|
+
if (recipe.kind === "image") return encodingIssue(recipe.encode);
|
|
133
|
+
const labels = /* @__PURE__ */ new Set();
|
|
134
|
+
const selectors = /* @__PURE__ */ new Set();
|
|
135
|
+
for (const texture of recipe.textures ?? []) {
|
|
136
|
+
if (!texture.label) return "Texture recipe labels cannot be empty";
|
|
137
|
+
if (labels.has(texture.label)) {
|
|
138
|
+
return `Duplicate texture recipe label: ${texture.label}`;
|
|
139
|
+
}
|
|
140
|
+
labels.add(texture.label);
|
|
141
|
+
const values = selectorValues(texture.select);
|
|
142
|
+
if (!values.ok) return values.error.message;
|
|
143
|
+
if (!values.data.length) {
|
|
144
|
+
return `Texture recipe "${texture.label}" has an empty selector`;
|
|
145
|
+
}
|
|
146
|
+
for (const value of values.data) {
|
|
147
|
+
const key = `${texture.select.by}:${value}`;
|
|
148
|
+
if (selectors.has(key)) {
|
|
149
|
+
return `Texture selector appears in more than one recipe: ${key}`;
|
|
150
|
+
}
|
|
151
|
+
selectors.add(key);
|
|
152
|
+
}
|
|
153
|
+
const issue = encodingIssue(texture.encode);
|
|
154
|
+
if (issue) return issue;
|
|
155
|
+
}
|
|
156
|
+
for (const method of recipe.methods ?? []) {
|
|
157
|
+
if (method.method === "resample" && (method.tolerance ?? 1e-4) <= 0) {
|
|
158
|
+
return "Resample tolerance must be greater than zero";
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return void 0;
|
|
162
|
+
}
|
|
163
|
+
function selectorValues(selector) {
|
|
164
|
+
if (selector.by === "slot") return success(selector.slots);
|
|
165
|
+
if (selector.by === "name") return success(selector.names);
|
|
166
|
+
for (const index of selector.indices) {
|
|
167
|
+
if (!Number.isInteger(index) || index < 0) {
|
|
168
|
+
return failure("invalid_recipe", "Texture indices must be non-negative integers");
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return success(selector.indices);
|
|
172
|
+
}
|
|
173
|
+
function encodingIssue(encoding) {
|
|
174
|
+
if (encoding.maxSize) {
|
|
175
|
+
const [width, height] = encoding.maxSize;
|
|
176
|
+
if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
|
|
177
|
+
return "Texture maxSize must contain positive integers";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if ("quality" in encoding && encoding.quality !== void 0) {
|
|
181
|
+
const max = encoding.codec === "ktx2" ? 255 : 100;
|
|
182
|
+
if (encoding.quality < 1 || encoding.quality > max) {
|
|
183
|
+
return `${encoding.codec} quality must be between 1 and ${max}`;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if ("effort" in encoding && encoding.effort !== void 0) {
|
|
187
|
+
if (encoding.effort < 0 || encoding.effort > 100) {
|
|
188
|
+
return `${encoding.codec} effort must be between 0 and 100`;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (encoding.codec === "webp" && encoding.nearLossless !== void 0 && (encoding.nearLossless < 0 || encoding.nearLossless > 100)) {
|
|
192
|
+
return "WebP nearLossless must be between 0 and 100";
|
|
193
|
+
}
|
|
194
|
+
if (encoding.codec === "ktx2" && encoding.mode === "uastc") {
|
|
195
|
+
if (encoding.level !== void 0 && (!Number.isInteger(encoding.level) || encoding.level < 0 || encoding.level > 4)) {
|
|
196
|
+
return "UASTC level must be an integer between 0 and 4";
|
|
197
|
+
}
|
|
198
|
+
const lambda = encoding.rdo?.lambda;
|
|
199
|
+
if (lambda !== void 0 && (lambda < 1e-3 || lambda > 10)) {
|
|
200
|
+
return "UASTC RDO lambda must be between 0.001 and 10";
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (encoding.codec === "ktx2" && encoding.mode === "etc1s" && encoding.compression !== void 0 && (!Number.isInteger(encoding.compression) || encoding.compression < 0 || encoding.compression > 6)) {
|
|
204
|
+
return "ETC1S compression must be an integer between 0 and 6";
|
|
205
|
+
}
|
|
206
|
+
return void 0;
|
|
207
|
+
}
|
|
208
|
+
function normalizeEncoding(encoding) {
|
|
209
|
+
switch (encoding.codec) {
|
|
210
|
+
case "webp":
|
|
211
|
+
return {
|
|
212
|
+
...encoding,
|
|
213
|
+
quality: encoding.quality ?? 75,
|
|
214
|
+
effort: encoding.effort ?? 50,
|
|
215
|
+
lossless: encoding.lossless ?? false,
|
|
216
|
+
nearLossless: encoding.nearLossless ?? 100
|
|
217
|
+
};
|
|
218
|
+
case "avif":
|
|
219
|
+
return {
|
|
220
|
+
...encoding,
|
|
221
|
+
quality: encoding.quality ?? 50,
|
|
222
|
+
effort: encoding.effort ?? 40,
|
|
223
|
+
lossless: encoding.lossless ?? false,
|
|
224
|
+
chromaSubsampling: encoding.chromaSubsampling ?? "4:2:0"
|
|
225
|
+
};
|
|
226
|
+
case "jpeg":
|
|
227
|
+
return {
|
|
228
|
+
...encoding,
|
|
229
|
+
quality: encoding.quality ?? 75,
|
|
230
|
+
chromaSubsampling: encoding.chromaSubsampling ?? "4:2:0"
|
|
231
|
+
};
|
|
232
|
+
case "png":
|
|
233
|
+
return { ...encoding };
|
|
234
|
+
case "ktx2":
|
|
235
|
+
if (encoding.mode === "uastc") {
|
|
236
|
+
return {
|
|
237
|
+
...encoding,
|
|
238
|
+
colorSpace: encoding.colorSpace ?? "srgb",
|
|
239
|
+
normalMap: encoding.normalMap ?? false,
|
|
240
|
+
level: encoding.level ?? 2,
|
|
241
|
+
mipmaps: encoding.mipmaps ?? true,
|
|
242
|
+
zstd: encoding.zstd ?? true
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
...encoding,
|
|
247
|
+
colorSpace: encoding.colorSpace ?? "srgb",
|
|
248
|
+
normalMap: encoding.normalMap ?? false,
|
|
249
|
+
quality: encoding.quality ?? 128,
|
|
250
|
+
compression: encoding.compression ?? 1,
|
|
251
|
+
mipmaps: encoding.mipmaps ?? true
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// package.json
|
|
257
|
+
var package_default = {
|
|
258
|
+
version: "0.1.0"};
|
|
259
|
+
|
|
260
|
+
// src/codecs/manifest.ts
|
|
261
|
+
var CODEC_MANIFEST_HASH = "2046d60deb0f9f224743f4404f3c6e8ba5399f81b2811fa50466e93fce3bd322";
|
|
262
|
+
var CODEC_ARTIFACTS = {
|
|
263
|
+
avifEncoder: {
|
|
264
|
+
packageName: "@jsquash/avif",
|
|
265
|
+
packageVersion: "2.1.1",
|
|
266
|
+
packagePath: "codec/enc/avif_enc.wasm",
|
|
267
|
+
publicFile: "avif_enc.wasm",
|
|
268
|
+
sha256: "d9f2a95164362af48558d176e619becfd49dd97b50b86c679b47100860522b3d"
|
|
269
|
+
},
|
|
270
|
+
jpegDecoder: {
|
|
271
|
+
packageName: "@jsquash/jpeg",
|
|
272
|
+
packageVersion: "1.6.0",
|
|
273
|
+
packagePath: "codec/dec/mozjpeg_dec.wasm",
|
|
274
|
+
publicFile: "mozjpeg_dec.wasm",
|
|
275
|
+
sha256: "a7c4b12169817e779ff4af137981393ae924944e167ad1bd95747c9199162d3e"
|
|
276
|
+
},
|
|
277
|
+
jpegEncoder: {
|
|
278
|
+
packageName: "@jsquash/jpeg",
|
|
279
|
+
packageVersion: "1.6.0",
|
|
280
|
+
packagePath: "codec/enc/mozjpeg_enc.wasm",
|
|
281
|
+
publicFile: "mozjpeg_enc.wasm",
|
|
282
|
+
sha256: "24d4177f1c4963e2058b107189249651c61fdef125570e79b1dfb63c8bb49326"
|
|
283
|
+
},
|
|
284
|
+
ktx2Encoder: {
|
|
285
|
+
packageName: "ktx2-encoder",
|
|
286
|
+
packageVersion: "0.6.0",
|
|
287
|
+
packagePath: "dist/basis/basis_encoder.wasm",
|
|
288
|
+
publicFile: "basis_encoder.wasm",
|
|
289
|
+
sha256: "9807719e87cf3d979b0d69ae7112eb88aec6a0e0206c0b2d00dc0bed0d581b80"
|
|
290
|
+
},
|
|
291
|
+
png: {
|
|
292
|
+
packageName: "@jsquash/png",
|
|
293
|
+
packageVersion: "3.1.1",
|
|
294
|
+
packagePath: "codec/pkg/squoosh_png_bg.wasm",
|
|
295
|
+
publicFile: "squoosh_png_bg.wasm",
|
|
296
|
+
sha256: "263d6e658808a74b72a1a99c5cc1d619237e70c150db6e41d5d84d3d117ab9be"
|
|
297
|
+
},
|
|
298
|
+
resize: {
|
|
299
|
+
packageName: "@jsquash/resize",
|
|
300
|
+
packageVersion: "2.1.1",
|
|
301
|
+
packagePath: "lib/resize/pkg/squoosh_resize_bg.wasm",
|
|
302
|
+
publicFile: "squoosh_resize_bg.wasm",
|
|
303
|
+
sha256: "5b1f702d502c4d0a70b99f78691bd554d566ba95859e4c57af5435955a1d74a5"
|
|
304
|
+
},
|
|
305
|
+
webpEncoder: {
|
|
306
|
+
packageName: "@jsquash/webp",
|
|
307
|
+
packageVersion: "1.5.0",
|
|
308
|
+
packagePath: "codec/enc/webp_enc.wasm",
|
|
309
|
+
publicFile: "webp_enc.wasm",
|
|
310
|
+
sha256: "b6085bb6702f144e9dc6016d58d230b34a84976bf0d080b7390b4b4b137d6ab7"
|
|
311
|
+
},
|
|
312
|
+
dracoDecoderScript: {
|
|
313
|
+
packageName: "draco3dgltf",
|
|
314
|
+
packageVersion: "1.5.7",
|
|
315
|
+
packagePath: "draco_decoder_gltf_nodejs.js",
|
|
316
|
+
publicFile: "draco_decoder_gltf.js",
|
|
317
|
+
sha256: "8bb2952d2ba7d67e1414f8df819410cb0434a666be53f671fff75f68843d76f6"
|
|
318
|
+
},
|
|
319
|
+
dracoDecoderWasm: {
|
|
320
|
+
packageName: "draco3dgltf",
|
|
321
|
+
packageVersion: "1.5.7",
|
|
322
|
+
packagePath: "draco_decoder_gltf.wasm",
|
|
323
|
+
publicFile: "draco_decoder_gltf.wasm",
|
|
324
|
+
sha256: "712db3449ae2041d6e8a224c395bda6cedb49e51322fae38b7db9beb8b381889"
|
|
325
|
+
},
|
|
326
|
+
dracoEncoderScript: {
|
|
327
|
+
packageName: "draco3dgltf",
|
|
328
|
+
packageVersion: "1.5.7",
|
|
329
|
+
packagePath: "draco_encoder_gltf_nodejs.js",
|
|
330
|
+
publicFile: "draco_encoder_gltf.js",
|
|
331
|
+
sha256: "8434adecd1446459601763e499be3697546056bca90b286a538ae0483a00845a"
|
|
332
|
+
},
|
|
333
|
+
dracoEncoderWasm: {
|
|
334
|
+
packageName: "draco3dgltf",
|
|
335
|
+
packageVersion: "1.5.7",
|
|
336
|
+
packagePath: "draco_encoder.wasm",
|
|
337
|
+
publicFile: "draco_encoder.wasm",
|
|
338
|
+
sha256: "d2a3ac80c91980d5d321c116454834ff36264825c6d1794cc84e42288f158958"
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
var CODEC_MANIFEST = {
|
|
342
|
+
chopperVersion: package_default.version};
|
|
343
|
+
var ENGINE_ID = `chopper@${package_default.version}:${CODEC_MANIFEST_HASH}`;
|
|
344
|
+
|
|
345
|
+
// src/codecs/image-engine.ts
|
|
346
|
+
var CodecLoadError = class extends Error {
|
|
347
|
+
};
|
|
348
|
+
function createWasmImageEngine(loader) {
|
|
349
|
+
const adapters = createAdapterCache(loader);
|
|
350
|
+
return {
|
|
351
|
+
id: ENGINE_ID,
|
|
352
|
+
manifestHash: CODEC_MANIFEST_HASH,
|
|
353
|
+
async inspect(source) {
|
|
354
|
+
try {
|
|
355
|
+
const image = await decodeSource(source, adapters);
|
|
356
|
+
return success({ width: image.width, height: image.height });
|
|
357
|
+
} catch (cause) {
|
|
358
|
+
return operationFailure("decode_failed", "Could not decode image", cause);
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
async encode(source, encoding, signal) {
|
|
362
|
+
const valid = validateRecipe({ schemaVersion: 1, kind: "image", encode: encoding });
|
|
363
|
+
if (!valid.ok) return valid;
|
|
364
|
+
try {
|
|
365
|
+
assertNotAborted(signal);
|
|
366
|
+
let image = await decodeSource(source, adapters);
|
|
367
|
+
assertNotAborted(signal);
|
|
368
|
+
if (encoding.maxSize) {
|
|
369
|
+
image = await resizeWithin(image, encoding.maxSize, adapters);
|
|
370
|
+
}
|
|
371
|
+
assertNotAborted(signal);
|
|
372
|
+
const encoded = encoding.codec === "ktx2" ? await encodeKtx2(source, image, encoding, await loader.basisEncoderUrl()) : await encodeRaster(image, encoding, adapters);
|
|
373
|
+
assertNotAborted(signal);
|
|
374
|
+
return success({
|
|
375
|
+
...encoded,
|
|
376
|
+
width: image.width,
|
|
377
|
+
height: image.height
|
|
378
|
+
});
|
|
379
|
+
} catch (cause) {
|
|
380
|
+
if (cause instanceof DOMException && cause.name === "AbortError") {
|
|
381
|
+
return failure("aborted", "Optimization was aborted", cause);
|
|
382
|
+
}
|
|
383
|
+
return operationFailure("encode_failed", "Could not encode image", cause);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function createAdapterCache(loader) {
|
|
389
|
+
let avif;
|
|
390
|
+
let jpegDecoder;
|
|
391
|
+
let jpegEncoder;
|
|
392
|
+
let png;
|
|
393
|
+
let resizeModule;
|
|
394
|
+
let webp;
|
|
395
|
+
const load = async (name) => {
|
|
396
|
+
try {
|
|
397
|
+
return await loader.load(name);
|
|
398
|
+
} catch (cause) {
|
|
399
|
+
throw new CodecLoadError(`Could not load ${name}`, { cause });
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
return {
|
|
403
|
+
avif: () => avif ??= load("avifEncoder").then(
|
|
404
|
+
(module) => initEmscriptenModule(avifEncoderFactory, module)
|
|
405
|
+
),
|
|
406
|
+
jpegDecoder: () => jpegDecoder ??= load("jpegDecoder").then(
|
|
407
|
+
(module) => initEmscriptenModule(jpegDecoderFactory, module)
|
|
408
|
+
),
|
|
409
|
+
jpegEncoder: () => jpegEncoder ??= load("jpegEncoder").then(
|
|
410
|
+
(module) => initEmscriptenModule(jpegEncoderFactory, module)
|
|
411
|
+
),
|
|
412
|
+
png: () => png ??= load("png").then(async (module) => {
|
|
413
|
+
await Promise.all([init(module), init$1(module)]);
|
|
414
|
+
}),
|
|
415
|
+
resize: () => resizeModule ??= load("resize").then(async (module) => {
|
|
416
|
+
await initResize(module);
|
|
417
|
+
}),
|
|
418
|
+
webp: () => webp ??= load("webpEncoder").then(
|
|
419
|
+
(module) => initEmscriptenModule(webpEncoderFactory, module)
|
|
420
|
+
)
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
async function decodeSource(source, adapters) {
|
|
424
|
+
if (source.mimeType === "image/png") {
|
|
425
|
+
await adapters.png();
|
|
426
|
+
return decodePng(toArrayBuffer(source.bytes));
|
|
427
|
+
}
|
|
428
|
+
const decoder = await adapters.jpegDecoder();
|
|
429
|
+
const image = decoder.decode(source.bytes, false);
|
|
430
|
+
if (!image) throw new Error("JPEG decoding failed");
|
|
431
|
+
return image;
|
|
432
|
+
}
|
|
433
|
+
async function resizeWithin(image, [maxWidth, maxHeight], adapters) {
|
|
434
|
+
const scale = Math.min(maxWidth / image.width, maxHeight / image.height, 1);
|
|
435
|
+
if (scale === 1) return image;
|
|
436
|
+
await adapters.resize();
|
|
437
|
+
return resize(image, {
|
|
438
|
+
width: Math.max(1, Math.round(image.width * scale)),
|
|
439
|
+
height: Math.max(1, Math.round(image.height * scale)),
|
|
440
|
+
method: "lanczos3",
|
|
441
|
+
fitMethod: "stretch",
|
|
442
|
+
premultiply: true,
|
|
443
|
+
linearRGB: true
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
async function encodeRaster(image, encoding, adapters) {
|
|
447
|
+
let bytes;
|
|
448
|
+
switch (encoding.codec) {
|
|
449
|
+
case "webp": {
|
|
450
|
+
const encoder = await adapters.webp();
|
|
451
|
+
bytes = requireEncoded(
|
|
452
|
+
encoder.encode(image.data, image.width, image.height, {
|
|
453
|
+
...defaultOptions$2,
|
|
454
|
+
quality: encoding.quality ?? 75,
|
|
455
|
+
method: encoding.effort === void 0 ? defaultOptions$2.method : remapEffort(encoding.effort, 6),
|
|
456
|
+
lossless: encoding.lossless ? 1 : 0,
|
|
457
|
+
near_lossless: encoding.nearLossless ?? 100,
|
|
458
|
+
thread_level: 0
|
|
459
|
+
}),
|
|
460
|
+
"WebP"
|
|
461
|
+
);
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
case "avif": {
|
|
465
|
+
const encoder = await adapters.avif();
|
|
466
|
+
bytes = requireEncoded(
|
|
467
|
+
encoder.encode(image.data, image.width, image.height, {
|
|
468
|
+
...defaultOptions$1,
|
|
469
|
+
quality: encoding.lossless ? 100 : encoding.quality ?? 50,
|
|
470
|
+
qualityAlpha: -1,
|
|
471
|
+
denoiseLevel: 0,
|
|
472
|
+
tileRowsLog2: 0,
|
|
473
|
+
tileColsLog2: 0,
|
|
474
|
+
speed: encoding.effort === void 0 ? defaultOptions$1.speed : 10 - remapEffort(encoding.effort, 10),
|
|
475
|
+
subsample: encoding.lossless || encoding.chromaSubsampling === "4:4:4" ? 3 : 1,
|
|
476
|
+
chromaDeltaQ: false,
|
|
477
|
+
sharpness: 0,
|
|
478
|
+
enableSharpYUV: false,
|
|
479
|
+
tune: 0,
|
|
480
|
+
bitDepth: 8,
|
|
481
|
+
lossless: encoding.lossless ?? false
|
|
482
|
+
}),
|
|
483
|
+
"AVIF"
|
|
484
|
+
);
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
case "jpeg": {
|
|
488
|
+
const encoder = await adapters.jpegEncoder();
|
|
489
|
+
bytes = requireEncoded(
|
|
490
|
+
encoder.encode(image.data, image.width, image.height, {
|
|
491
|
+
...defaultOptions,
|
|
492
|
+
quality: encoding.quality ?? 75,
|
|
493
|
+
baseline: false,
|
|
494
|
+
arithmetic: false,
|
|
495
|
+
progressive: true,
|
|
496
|
+
optimize_coding: true,
|
|
497
|
+
smoothing: 0,
|
|
498
|
+
color_space: 3,
|
|
499
|
+
quant_table: 3,
|
|
500
|
+
trellis_multipass: false,
|
|
501
|
+
trellis_opt_zero: false,
|
|
502
|
+
trellis_opt_table: false,
|
|
503
|
+
trellis_loops: 1,
|
|
504
|
+
auto_subsample: encoding.chromaSubsampling === void 0,
|
|
505
|
+
chroma_subsample: encoding.chromaSubsampling === "4:4:4" ? 1 : 2,
|
|
506
|
+
separate_chroma_quality: false,
|
|
507
|
+
chroma_quality: encoding.quality ?? 75
|
|
508
|
+
}),
|
|
509
|
+
"JPEG"
|
|
510
|
+
);
|
|
511
|
+
break;
|
|
512
|
+
}
|
|
513
|
+
case "png":
|
|
514
|
+
await adapters.png();
|
|
515
|
+
bytes = await encodePng(image);
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
return { bytes: toUint8Array(bytes), mimeType: outputMimeType(encoding) };
|
|
519
|
+
}
|
|
520
|
+
async function encodeKtx2(source, image, encoding, wasmUrl) {
|
|
521
|
+
const srgb = encoding.colorSpace !== "linear";
|
|
522
|
+
const bytes = await encodeToKTX2(source.bytes, {
|
|
523
|
+
isUASTC: encoding.mode === "uastc",
|
|
524
|
+
qualityLevel: encoding.mode === "etc1s" ? encoding.quality : void 0,
|
|
525
|
+
compressionLevel: encoding.mode === "etc1s" ? encoding.compression : void 0,
|
|
526
|
+
needSupercompression: encoding.mode === "uastc" ? encoding.zstd ?? true : false,
|
|
527
|
+
uastcLDRQualityLevel: encoding.mode === "uastc" ? encoding.level : void 0,
|
|
528
|
+
enableRDO: encoding.mode === "uastc" && encoding.rdo !== void 0,
|
|
529
|
+
rdoQualityLevel: encoding.mode === "uastc" ? encoding.rdo?.lambda : void 0,
|
|
530
|
+
isNormalMap: encoding.normalMap,
|
|
531
|
+
isPerceptual: srgb,
|
|
532
|
+
isSetKTX2SRGBTransferFunc: srgb,
|
|
533
|
+
generateMipmap: encoding.mipmaps ?? true,
|
|
534
|
+
isKTX2File: true,
|
|
535
|
+
imageDecoder: async () => ({
|
|
536
|
+
data: new Uint8Array(image.data.buffer, image.data.byteOffset, image.data.byteLength),
|
|
537
|
+
width: image.width,
|
|
538
|
+
height: image.height
|
|
539
|
+
}),
|
|
540
|
+
wasmUrl
|
|
541
|
+
});
|
|
542
|
+
return { bytes, mimeType: outputMimeType(encoding) };
|
|
543
|
+
}
|
|
544
|
+
function operationFailure(code, message, cause) {
|
|
545
|
+
return cause instanceof CodecLoadError ? failure("codec_load_failed", cause.message, cause.cause) : failure(code, message, cause);
|
|
546
|
+
}
|
|
547
|
+
function assertNotAborted(signal) {
|
|
548
|
+
if (signal?.aborted) throw new DOMException("Optimization was aborted", "AbortError");
|
|
549
|
+
}
|
|
550
|
+
function requireEncoded(bytes, codec) {
|
|
551
|
+
if (!bytes) throw new Error(`${codec} encoding failed`);
|
|
552
|
+
return bytes;
|
|
553
|
+
}
|
|
554
|
+
function toUint8Array(bytes) {
|
|
555
|
+
return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
556
|
+
}
|
|
557
|
+
function toArrayBuffer(bytes) {
|
|
558
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
559
|
+
}
|
|
560
|
+
function remapEffort(effort, max) {
|
|
561
|
+
return Math.round(effort / 100 * max);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// src/node/image-engine.ts
|
|
565
|
+
var defaultEngine;
|
|
566
|
+
function createNodeImageEngine(options = {}) {
|
|
567
|
+
installImageData();
|
|
568
|
+
if (options.codecDirectory) {
|
|
569
|
+
return createWasmImageEngine(createNodeCodecLoader(options.codecDirectory));
|
|
570
|
+
}
|
|
571
|
+
return defaultEngine ??= createWasmImageEngine(createNodeCodecLoader());
|
|
572
|
+
}
|
|
573
|
+
function createNodeCodecLoader(codecDirectory = new URL("../../codecs/", import.meta.url)) {
|
|
574
|
+
const modules = /* @__PURE__ */ new Map();
|
|
575
|
+
return {
|
|
576
|
+
load(name) {
|
|
577
|
+
const existing = modules.get(name);
|
|
578
|
+
if (existing) return existing;
|
|
579
|
+
const pending = loadModule(name, codecDirectory);
|
|
580
|
+
modules.set(name, pending);
|
|
581
|
+
return pending;
|
|
582
|
+
},
|
|
583
|
+
async basisEncoderUrl() {
|
|
584
|
+
return void 0;
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
async function loadModule(name, codecDirectory) {
|
|
589
|
+
const artifact = CODEC_ARTIFACTS[name];
|
|
590
|
+
const location = typeof codecDirectory === "string" ? join(codecDirectory, artifact.publicFile) : new URL(artifact.publicFile, codecDirectory);
|
|
591
|
+
const bytes = await readFile(location);
|
|
592
|
+
const hash = createHash("sha256").update(bytes).digest("hex");
|
|
593
|
+
if (hash !== artifact.sha256) {
|
|
594
|
+
throw new Error(`${name} failed integrity validation`);
|
|
595
|
+
}
|
|
596
|
+
return WebAssembly.compile(bytes);
|
|
597
|
+
}
|
|
598
|
+
function installImageData() {
|
|
599
|
+
if (globalThis.ImageData) return;
|
|
600
|
+
globalThis.ImageData = class ImageData {
|
|
601
|
+
constructor(dataOrWidth, widthOrHeight, heightOrSettings) {
|
|
602
|
+
this.colorSpace = "srgb";
|
|
603
|
+
if (typeof dataOrWidth === "number") {
|
|
604
|
+
this.width = dataOrWidth;
|
|
605
|
+
this.height = widthOrHeight;
|
|
606
|
+
this.data = new Uint8ClampedArray(this.width * this.height * 4);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
this.data = dataOrWidth;
|
|
610
|
+
this.width = widthOrHeight;
|
|
611
|
+
if (typeof heightOrSettings !== "number") {
|
|
612
|
+
throw new Error("ImageData height is required in Node");
|
|
613
|
+
}
|
|
614
|
+
this.height = heightOrSettings;
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
var PROPERTY_TYPES = {
|
|
619
|
+
accessor: PropertyType.ACCESSOR,
|
|
620
|
+
animation: PropertyType.ANIMATION,
|
|
621
|
+
buffer: PropertyType.BUFFER,
|
|
622
|
+
camera: PropertyType.CAMERA,
|
|
623
|
+
material: PropertyType.MATERIAL,
|
|
624
|
+
mesh: PropertyType.MESH,
|
|
625
|
+
node: PropertyType.NODE,
|
|
626
|
+
primitive: PropertyType.PRIMITIVE,
|
|
627
|
+
primitiveTarget: PropertyType.PRIMITIVE_TARGET,
|
|
628
|
+
skin: PropertyType.SKIN,
|
|
629
|
+
texture: PropertyType.TEXTURE
|
|
630
|
+
};
|
|
631
|
+
function compileGlbMethods(recipes, options = {}) {
|
|
632
|
+
return recipes.map((recipe) => {
|
|
633
|
+
switch (recipe.method) {
|
|
634
|
+
case "dedup":
|
|
635
|
+
return dedup({
|
|
636
|
+
keepUniqueNames: recipe.keepUniqueNames,
|
|
637
|
+
propertyTypes: dedupPropertyTypes(recipe, options).map(toPropertyType)
|
|
638
|
+
});
|
|
639
|
+
case "prune":
|
|
640
|
+
return prune({
|
|
641
|
+
keepAttributes: recipe.keepAttributes,
|
|
642
|
+
keepExtras: recipe.keepExtras,
|
|
643
|
+
keepLeaves: recipe.keepLeaves,
|
|
644
|
+
keepSolidTextures: recipe.keepSolidTextures,
|
|
645
|
+
propertyTypes: recipe.propertyTypes?.map(toPropertyType)
|
|
646
|
+
});
|
|
647
|
+
case "resample":
|
|
648
|
+
return resample({
|
|
649
|
+
cleanup: recipe.cleanup,
|
|
650
|
+
tolerance: recipe.tolerance
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
function dedupPropertyTypes(recipe, options) {
|
|
656
|
+
const propertyTypes = recipe.propertyTypes ?? ["accessor", "material", "mesh", "skin", "texture"];
|
|
657
|
+
return options.preserveTextureIdentity ? propertyTypes.filter((type) => type !== "texture") : propertyTypes;
|
|
658
|
+
}
|
|
659
|
+
function toPropertyType(property) {
|
|
660
|
+
return PROPERTY_TYPES[property];
|
|
661
|
+
}
|
|
662
|
+
function inspectGlbTextures(document) {
|
|
663
|
+
const textures = document.getRoot().listTextures();
|
|
664
|
+
const nameCounts = /* @__PURE__ */ new Map();
|
|
665
|
+
for (const texture of textures) {
|
|
666
|
+
const name = texture.getName();
|
|
667
|
+
if (name) nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);
|
|
668
|
+
}
|
|
669
|
+
return textures.flatMap((texture, index) => {
|
|
670
|
+
const image = texture.getImage();
|
|
671
|
+
if (!image) return [];
|
|
672
|
+
const name = texture.getName();
|
|
673
|
+
return [
|
|
674
|
+
{
|
|
675
|
+
index,
|
|
676
|
+
name,
|
|
677
|
+
uri: texture.getURI(),
|
|
678
|
+
mimeType: texture.getMimeType(),
|
|
679
|
+
size: texture.getSize() ?? null,
|
|
680
|
+
slots: listTextureSlots(texture),
|
|
681
|
+
bytes: new Uint8Array(image),
|
|
682
|
+
authoringSelector: name && nameCounts.get(name) === 1 ? { by: "name", names: [name] } : { by: "index", indices: [index] }
|
|
683
|
+
}
|
|
684
|
+
];
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
function textureMatchesRecipe(texture, index, recipe) {
|
|
688
|
+
const selector = recipe.select;
|
|
689
|
+
if (selector.by === "index") return selector.indices.includes(index);
|
|
690
|
+
if (selector.by === "name") return selector.names.includes(texture.getName());
|
|
691
|
+
const slots = listTextureSlots(texture);
|
|
692
|
+
return selector.slots.some((slot) => slots.includes(slot));
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// src/gltf/optimizer.ts
|
|
696
|
+
var GlbPipelineFailure = class extends Error {
|
|
697
|
+
constructor(code, message, originalCause) {
|
|
698
|
+
super(message, originalCause === void 0 ? void 0 : { cause: originalCause });
|
|
699
|
+
this.code = code;
|
|
700
|
+
this.originalCause = originalCause;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
async function optimizeGlbDocument(document, recipe, imageEngine, options = {}) {
|
|
704
|
+
const texturePlans = planTextureEncodings(document, recipe.textures);
|
|
705
|
+
assertNotAborted2(options.signal);
|
|
706
|
+
for (const extension of ["KHR_draco_mesh_compression", "EXT_meshopt_compression"]) {
|
|
707
|
+
if (document.hasExtension(extension)) document.disposeExtension(extension);
|
|
708
|
+
}
|
|
709
|
+
for (const [index, method] of recipe.methods.entries()) {
|
|
710
|
+
options.onProgress?.({
|
|
711
|
+
phase: "transform",
|
|
712
|
+
method: method.method,
|
|
713
|
+
index,
|
|
714
|
+
total: recipe.methods.length
|
|
715
|
+
});
|
|
716
|
+
await document.transform(...compileGlbMethods([method], { preserveTextureIdentity: texturePlans.length > 0 }));
|
|
717
|
+
assertNotAborted2(options.signal);
|
|
718
|
+
}
|
|
719
|
+
const reports = await encodeTextures(document, texturePlans, imageEngine, options);
|
|
720
|
+
if (recipe.geometry) {
|
|
721
|
+
options.onProgress?.({ phase: "geometry", codec: recipe.geometry.codec });
|
|
722
|
+
if (recipe.geometry.codec === "draco") {
|
|
723
|
+
await document.transform(draco());
|
|
724
|
+
} else {
|
|
725
|
+
await MeshoptEncoder.ready;
|
|
726
|
+
await document.transform(meshopt({ encoder: MeshoptEncoder }));
|
|
727
|
+
}
|
|
728
|
+
assertNotAborted2(options.signal);
|
|
729
|
+
}
|
|
730
|
+
return reports;
|
|
731
|
+
}
|
|
732
|
+
async function encodeTextures(document, plans, engine, options) {
|
|
733
|
+
const reports = [];
|
|
734
|
+
const textures = document.getRoot().listTextures();
|
|
735
|
+
const outputIndices = new Map(textures.map((texture, index) => [texture, index]));
|
|
736
|
+
for (const { texture, recipe, sourceIndex } of plans) {
|
|
737
|
+
const outputIndex = outputIndices.get(texture);
|
|
738
|
+
if (outputIndex === void 0) continue;
|
|
739
|
+
const image = texture.getImage();
|
|
740
|
+
if (!image) continue;
|
|
741
|
+
const mimeType = sourceMimeType(texture);
|
|
742
|
+
options.onProgress?.({
|
|
743
|
+
phase: "texture",
|
|
744
|
+
label: recipe.label,
|
|
745
|
+
index: outputIndex,
|
|
746
|
+
total: textures.length
|
|
747
|
+
});
|
|
748
|
+
const encoded = await engine.encode({ bytes: image, mimeType }, recipe.encode, options.signal);
|
|
749
|
+
if (!encoded.ok) {
|
|
750
|
+
throw new GlbPipelineFailure(
|
|
751
|
+
encoded.error.code === "validation_failed" || encoded.error.code === "unsupported_asset" || encoded.error.code === "io_failed" ? "encode_failed" : encoded.error.code,
|
|
752
|
+
encoded.error.message,
|
|
753
|
+
encoded.error.cause
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
texture.setImage(encoded.data.bytes).setMimeType(encoded.data.mimeType);
|
|
757
|
+
updateTextureUri(texture, outputExtension(recipe.encode));
|
|
758
|
+
reports.push({
|
|
759
|
+
label: recipe.label,
|
|
760
|
+
sourceIndex,
|
|
761
|
+
outputIndex,
|
|
762
|
+
beforeBytes: image.byteLength,
|
|
763
|
+
afterBytes: encoded.data.bytes.byteLength,
|
|
764
|
+
beforeMimeType: mimeType,
|
|
765
|
+
afterMimeType: encoded.data.mimeType
|
|
766
|
+
});
|
|
767
|
+
assertNotAborted2(options.signal);
|
|
768
|
+
}
|
|
769
|
+
const mimeTypes = new Set(
|
|
770
|
+
document.getRoot().listTextures().map((texture) => texture.getMimeType())
|
|
771
|
+
);
|
|
772
|
+
syncTextureExtension(document, "image/webp", EXTTextureWebP, mimeTypes);
|
|
773
|
+
syncTextureExtension(document, "image/avif", EXTTextureAVIF, mimeTypes);
|
|
774
|
+
syncTextureExtension(document, "image/ktx2", KHRTextureBasisu, mimeTypes);
|
|
775
|
+
return reports;
|
|
776
|
+
}
|
|
777
|
+
function planTextureEncodings(document, recipes) {
|
|
778
|
+
const plans = [];
|
|
779
|
+
for (const [sourceIndex, texture] of document.getRoot().listTextures().entries()) {
|
|
780
|
+
const matches = recipes.filter((recipe) => textureMatchesRecipe(texture, sourceIndex, recipe));
|
|
781
|
+
if (matches.length > 1) {
|
|
782
|
+
const label = texture.getName() || texture.getURI() || "unnamed texture";
|
|
783
|
+
throw new GlbPipelineFailure(
|
|
784
|
+
"invalid_recipe",
|
|
785
|
+
`Texture "${label}" matches multiple encoders: ${matches.map(({ label: match }) => match).join(", ")}`
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
if (matches[0]) plans.push({ texture, recipe: matches[0], sourceIndex });
|
|
789
|
+
}
|
|
790
|
+
return plans;
|
|
791
|
+
}
|
|
792
|
+
function syncTextureExtension(document, mimeType, extension, mimeTypes) {
|
|
793
|
+
if (mimeTypes.has(mimeType)) {
|
|
794
|
+
document.createExtension(extension).setRequired(true);
|
|
795
|
+
} else if (document.hasExtension(extension.EXTENSION_NAME)) {
|
|
796
|
+
document.disposeExtension(extension.EXTENSION_NAME);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
function sourceMimeType(texture) {
|
|
800
|
+
const mimeType = texture.getMimeType();
|
|
801
|
+
if (mimeType === "image/png" || mimeType === "image/jpeg") return mimeType;
|
|
802
|
+
const label = texture.getName() || texture.getURI() || "unnamed texture";
|
|
803
|
+
throw new GlbPipelineFailure(
|
|
804
|
+
"decode_failed",
|
|
805
|
+
`Texture "${label}" uses unsupported source type ${mimeType || "unknown"}; expected PNG or JPEG`
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
function updateTextureUri(texture, extension) {
|
|
809
|
+
const uri = texture.getURI();
|
|
810
|
+
if (!uri) return;
|
|
811
|
+
texture.setURI(uri.replace(/\.[^./]+$/, "") + extension);
|
|
812
|
+
}
|
|
813
|
+
function assertNotAborted2(signal) {
|
|
814
|
+
if (signal?.aborted) {
|
|
815
|
+
throw new GlbPipelineFailure("aborted", "Optimization was aborted");
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// src/gltf/engine.ts
|
|
820
|
+
function createGlbEngine(imageEngine, io) {
|
|
821
|
+
return {
|
|
822
|
+
id: imageEngine.id,
|
|
823
|
+
async inspect(source) {
|
|
824
|
+
try {
|
|
825
|
+
const document = await io.readBinary(source);
|
|
826
|
+
return success(inspectDocument(document, source.byteLength));
|
|
827
|
+
} catch (cause) {
|
|
828
|
+
return failure("decode_failed", "Could not decode GLB", cause);
|
|
829
|
+
}
|
|
830
|
+
},
|
|
831
|
+
async optimize(source, recipe, options = {}) {
|
|
832
|
+
const normalized = normalizeRecipe(recipe);
|
|
833
|
+
if (!normalized.ok) return normalized;
|
|
834
|
+
if (normalized.data.kind !== "glb") {
|
|
835
|
+
return failure("invalid_recipe", "Expected a GLB recipe");
|
|
836
|
+
}
|
|
837
|
+
try {
|
|
838
|
+
options.onProgress?.({ phase: "decode" });
|
|
839
|
+
const document = await io.readBinary(source);
|
|
840
|
+
const textures = await optimizeGlbDocument(document, normalized.data, imageEngine, options);
|
|
841
|
+
const bytes = await io.writeBinary(document);
|
|
842
|
+
const verifiedDocument = await io.readBinary(bytes);
|
|
843
|
+
return success({
|
|
844
|
+
bytes,
|
|
845
|
+
inspection: inspectDocument(verifiedDocument, bytes.byteLength),
|
|
846
|
+
textures
|
|
847
|
+
});
|
|
848
|
+
} catch (cause) {
|
|
849
|
+
if (cause instanceof GlbPipelineFailure) {
|
|
850
|
+
return failure(cause.code, cause.message, cause.originalCause);
|
|
851
|
+
}
|
|
852
|
+
return failure("encode_failed", "Could not optimize GLB", cause);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
function inspectDocument(document, byteLength) {
|
|
858
|
+
const root = document.getRoot();
|
|
859
|
+
const meshes = root.listMeshes();
|
|
860
|
+
return {
|
|
861
|
+
kind: "glb",
|
|
862
|
+
byteLength,
|
|
863
|
+
textures: inspectGlbTextures(document),
|
|
864
|
+
geometry: {
|
|
865
|
+
compression: document.hasExtension("KHR_draco_mesh_compression") ? "draco" : document.hasExtension("EXT_meshopt_compression") ? "meshopt" : false,
|
|
866
|
+
meshCount: meshes.length,
|
|
867
|
+
primitiveCount: meshes.reduce((total, mesh) => total + mesh.listPrimitives().length, 0)
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// src/node/glb-engine.ts
|
|
873
|
+
var dependencies;
|
|
874
|
+
async function createNodeGlbEngine(imageEngine = createNodeImageEngine()) {
|
|
875
|
+
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies(await loadDependencies());
|
|
876
|
+
return createGlbEngine(imageEngine, io);
|
|
877
|
+
}
|
|
878
|
+
function loadDependencies() {
|
|
879
|
+
return dependencies ??= Promise.all([
|
|
880
|
+
draco3d.createDecoderModule(),
|
|
881
|
+
draco3d.createEncoderModule(),
|
|
882
|
+
MeshoptDecoder.ready,
|
|
883
|
+
MeshoptEncoder.ready
|
|
884
|
+
]).then(([dracoDecoder, dracoEncoder]) => ({
|
|
885
|
+
"draco3d.decoder": dracoDecoder,
|
|
886
|
+
"draco3d.encoder": dracoEncoder,
|
|
887
|
+
"meshopt.decoder": MeshoptDecoder,
|
|
888
|
+
"meshopt.encoder": MeshoptEncoder
|
|
889
|
+
}));
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// src/core/chopper.ts
|
|
893
|
+
function createChopper(runtime) {
|
|
894
|
+
return {
|
|
895
|
+
engine: {
|
|
896
|
+
id: ENGINE_ID,
|
|
897
|
+
version: CODEC_MANIFEST.chopperVersion,
|
|
898
|
+
manifestHash: CODEC_MANIFEST_HASH
|
|
899
|
+
},
|
|
900
|
+
async inspect(input) {
|
|
901
|
+
const kind = detectAsset(input);
|
|
902
|
+
if (!kind.ok) return kind;
|
|
903
|
+
if (kind.data === "glb") {
|
|
904
|
+
try {
|
|
905
|
+
return await (await runtime.glb()).inspect(input.bytes);
|
|
906
|
+
} catch (cause) {
|
|
907
|
+
return runtimeLoadFailure("GLB", cause);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return inspectImage(input, imageMimeType(input), runtime.image);
|
|
911
|
+
},
|
|
912
|
+
async optimize(input, recipe, options = {}) {
|
|
913
|
+
const normalized = normalizeRecipe(recipe);
|
|
914
|
+
if (!normalized.ok) return normalized;
|
|
915
|
+
const kind = detectAsset(input);
|
|
916
|
+
if (!kind.ok) return kind;
|
|
917
|
+
if (kind.data !== recipe.kind) {
|
|
918
|
+
return failure("invalid_recipe", `A ${recipe.kind} recipe cannot process a ${kind.data} asset`);
|
|
919
|
+
}
|
|
920
|
+
options.onProgress?.({ phase: "inspect" });
|
|
921
|
+
const startedAt = performance.now();
|
|
922
|
+
if (kind.data === "glb" && recipe.kind === "glb") {
|
|
923
|
+
let glb;
|
|
924
|
+
try {
|
|
925
|
+
glb = await runtime.glb();
|
|
926
|
+
} catch (cause) {
|
|
927
|
+
return runtimeLoadFailure("GLB", cause);
|
|
928
|
+
}
|
|
929
|
+
const optimized = await glb.optimize(input.bytes, recipe, options);
|
|
930
|
+
if (!optimized.ok) return optimized;
|
|
931
|
+
options.onProgress?.({ phase: "validate" });
|
|
932
|
+
const report2 = createReport({
|
|
933
|
+
recipe: normalized.data,
|
|
934
|
+
beforeBytes: input.bytes.byteLength,
|
|
935
|
+
afterBytes: optimized.data.bytes.byteLength,
|
|
936
|
+
durationMs: performance.now() - startedAt,
|
|
937
|
+
textures: optimized.data.textures
|
|
938
|
+
});
|
|
939
|
+
options.onProgress?.({ phase: "complete" });
|
|
940
|
+
return success({
|
|
941
|
+
bytes: optimized.data.bytes,
|
|
942
|
+
fileName: outputFileName(input.fileName, ".glb"),
|
|
943
|
+
mimeType: "model/gltf-binary",
|
|
944
|
+
inspection: optimized.data.inspection,
|
|
945
|
+
report: report2
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
if (kind.data !== "image" || recipe.kind !== "image") {
|
|
949
|
+
return failure("invalid_recipe", "Recipe and input type do not match");
|
|
950
|
+
}
|
|
951
|
+
const inspection = await inspectImage(input, imageMimeType(input), runtime.image);
|
|
952
|
+
if (!inspection.ok) return inspection;
|
|
953
|
+
const encoded = await runtime.image.encode(
|
|
954
|
+
{ bytes: input.bytes, mimeType: imageMimeType(input) },
|
|
955
|
+
recipe.encode,
|
|
956
|
+
options.signal
|
|
957
|
+
);
|
|
958
|
+
if (!encoded.ok) return encoded;
|
|
959
|
+
options.onProgress?.({ phase: "validate" });
|
|
960
|
+
if (!hasExpectedSignature(encoded.data.bytes, encoded.data.mimeType)) {
|
|
961
|
+
return failure("validation_failed", `Encoded bytes do not match ${encoded.data.mimeType}`);
|
|
962
|
+
}
|
|
963
|
+
const report = createReport({
|
|
964
|
+
recipe: normalized.data,
|
|
965
|
+
beforeBytes: input.bytes.byteLength,
|
|
966
|
+
afterBytes: encoded.data.bytes.byteLength,
|
|
967
|
+
durationMs: performance.now() - startedAt
|
|
968
|
+
});
|
|
969
|
+
options.onProgress?.({ phase: "complete" });
|
|
970
|
+
return success({
|
|
971
|
+
bytes: encoded.data.bytes,
|
|
972
|
+
fileName: outputFileName(input.fileName, outputExtension(recipe.encode)),
|
|
973
|
+
mimeType: encoded.data.mimeType,
|
|
974
|
+
inspection: inspection.data,
|
|
975
|
+
report
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
function runtimeLoadFailure(runtime, cause) {
|
|
981
|
+
return failure(
|
|
982
|
+
"codec_load_failed",
|
|
983
|
+
`Could not initialize ${runtime} runtime: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
984
|
+
cause
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
function detectAsset(input) {
|
|
988
|
+
if (input.bytes.length >= 4 && input.bytes[0] === 103 && input.bytes[1] === 108 && input.bytes[2] === 84 && input.bytes[3] === 70) {
|
|
989
|
+
return success("glb");
|
|
990
|
+
}
|
|
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`);
|
|
993
|
+
}
|
|
994
|
+
async function inspectImage(input, mimeType, engine) {
|
|
995
|
+
const dimensions = await engine.inspect({ bytes: input.bytes, mimeType });
|
|
996
|
+
if (!dimensions.ok) return dimensions;
|
|
997
|
+
return success({
|
|
998
|
+
kind: "image",
|
|
999
|
+
mimeType,
|
|
1000
|
+
width: dimensions.data.width,
|
|
1001
|
+
height: dimensions.data.height,
|
|
1002
|
+
byteLength: input.bytes.byteLength
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
function imageMimeType(input) {
|
|
1006
|
+
return isPng(input.bytes) ? "image/png" : "image/jpeg";
|
|
1007
|
+
}
|
|
1008
|
+
function isPng(bytes) {
|
|
1009
|
+
return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71;
|
|
1010
|
+
}
|
|
1011
|
+
function isJpeg(bytes) {
|
|
1012
|
+
return bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 216;
|
|
1013
|
+
}
|
|
1014
|
+
function hasExpectedSignature(bytes, mimeType) {
|
|
1015
|
+
if (mimeType === "image/png") return isPng(bytes);
|
|
1016
|
+
if (mimeType === "image/jpeg") return isJpeg(bytes);
|
|
1017
|
+
if (mimeType === "image/webp") {
|
|
1018
|
+
return ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP";
|
|
1019
|
+
}
|
|
1020
|
+
if (mimeType === "image/avif") return ascii(bytes, 4, 12) === "ftypavif";
|
|
1021
|
+
if (mimeType === "image/ktx2") {
|
|
1022
|
+
return bytes.length >= 12 && bytes[0] === 171 && ascii(bytes, 1, 7) === "KTX 20";
|
|
1023
|
+
}
|
|
1024
|
+
return false;
|
|
1025
|
+
}
|
|
1026
|
+
function ascii(bytes, start, end) {
|
|
1027
|
+
return String.fromCharCode(...bytes.subarray(start, end));
|
|
1028
|
+
}
|
|
1029
|
+
function outputFileName(fileName, extension) {
|
|
1030
|
+
const lastSlash = Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\\"));
|
|
1031
|
+
const lastDot = fileName.lastIndexOf(".");
|
|
1032
|
+
const end = lastDot > lastSlash ? lastDot : fileName.length;
|
|
1033
|
+
return `${fileName.slice(0, end)}${extension}`;
|
|
1034
|
+
}
|
|
1035
|
+
function createReport(values) {
|
|
1036
|
+
return {
|
|
1037
|
+
engineId: ENGINE_ID,
|
|
1038
|
+
manifestHash: CODEC_MANIFEST_HASH,
|
|
1039
|
+
recipe: values.recipe,
|
|
1040
|
+
beforeBytes: values.beforeBytes,
|
|
1041
|
+
afterBytes: values.afterBytes,
|
|
1042
|
+
durationMs: values.durationMs,
|
|
1043
|
+
textures: values.textures ?? [],
|
|
1044
|
+
warnings: [],
|
|
1045
|
+
validation: { valid: true, messages: [] }
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// src/node/chopper.ts
|
|
1050
|
+
var chopper;
|
|
1051
|
+
function createNodeChopper(options = {}) {
|
|
1052
|
+
if (!options.codecDirectory && chopper) return chopper;
|
|
1053
|
+
const image = createNodeImageEngine(options);
|
|
1054
|
+
const created = createChopper({
|
|
1055
|
+
image,
|
|
1056
|
+
glb: () => createNodeGlbEngine(image)
|
|
1057
|
+
});
|
|
1058
|
+
if (!options.codecDirectory) chopper = created;
|
|
1059
|
+
return created;
|
|
1060
|
+
}
|
|
1061
|
+
async function optimizeFile({
|
|
1062
|
+
input,
|
|
1063
|
+
output,
|
|
1064
|
+
recipe,
|
|
1065
|
+
...options
|
|
1066
|
+
}) {
|
|
1067
|
+
const source = resolve(input);
|
|
1068
|
+
const destination = resolve(output);
|
|
1069
|
+
try {
|
|
1070
|
+
const bytes = new Uint8Array(await readFile(source));
|
|
1071
|
+
const result = await createNodeChopper().optimize({ bytes, fileName: input }, recipe, options);
|
|
1072
|
+
if (!result.ok) return result;
|
|
1073
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
1074
|
+
const temporaryDirectory = await mkdtemp(join(dirname(destination), ".chopper-"));
|
|
1075
|
+
const pending = join(temporaryDirectory, "output");
|
|
1076
|
+
try {
|
|
1077
|
+
await writeFile(pending, result.data.bytes);
|
|
1078
|
+
await rename(pending, destination);
|
|
1079
|
+
} finally {
|
|
1080
|
+
await rm(temporaryDirectory, { recursive: true, force: true });
|
|
1081
|
+
}
|
|
1082
|
+
return result;
|
|
1083
|
+
} catch (cause) {
|
|
1084
|
+
return failure("io_failed", `Could not optimize ${input}`, cause);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
async function loadConfig(path = "chopper.config.ts") {
|
|
1088
|
+
const absolutePath = resolve(path);
|
|
1089
|
+
try {
|
|
1090
|
+
await readFile(absolutePath);
|
|
1091
|
+
const jiti = createJiti(import.meta.url);
|
|
1092
|
+
const config = await jiti.import(absolutePath, {
|
|
1093
|
+
default: true
|
|
1094
|
+
});
|
|
1095
|
+
if (!config || !Array.isArray(config.rules)) {
|
|
1096
|
+
return failure("invalid_recipe", `${path} must export a Chopper config`);
|
|
1097
|
+
}
|
|
1098
|
+
if (config.concurrency !== void 0 && (!Number.isInteger(config.concurrency) || config.concurrency < 1)) {
|
|
1099
|
+
return failure("invalid_recipe", "Config concurrency must be a positive integer");
|
|
1100
|
+
}
|
|
1101
|
+
return success(config);
|
|
1102
|
+
} catch (cause) {
|
|
1103
|
+
return failure("io_failed", `Could not load ${path}`, cause);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
async function runConfig(options = {}) {
|
|
1107
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
1108
|
+
const mode = options.mode ?? "write";
|
|
1109
|
+
const loaded = options.config ? success(options.config) : await loadConfig(resolve(cwd, options.configPath ?? "chopper.config.ts"));
|
|
1110
|
+
if (!loaded.ok) return loaded;
|
|
1111
|
+
const planned = await planAssets(loaded.data, cwd, options.changedPaths);
|
|
1112
|
+
if (!planned.ok) return planned;
|
|
1113
|
+
const chopper2 = options.chopper ?? createNodeChopper();
|
|
1114
|
+
const files = await mapConcurrent(
|
|
1115
|
+
planned.data,
|
|
1116
|
+
loaded.data.concurrency ?? 2,
|
|
1117
|
+
(asset) => executeAsset(asset, mode, cwd, chopper2)
|
|
1118
|
+
);
|
|
1119
|
+
return success({ mode, files, totals: summarize(files) });
|
|
1120
|
+
}
|
|
1121
|
+
async function planAssets(config, cwd, changedPaths) {
|
|
1122
|
+
const changed = changedPaths ? new Set(changedPaths.map((path) => normalizePath(path))) : void 0;
|
|
1123
|
+
const planned = [];
|
|
1124
|
+
for (const rule of config.rules) {
|
|
1125
|
+
const valid = validateRecipe(rule.recipe);
|
|
1126
|
+
if (!valid.ok) return valid;
|
|
1127
|
+
const matches = await glob(rule.include, {
|
|
1128
|
+
cwd,
|
|
1129
|
+
ignore: rule.exclude,
|
|
1130
|
+
onlyFiles: true
|
|
1131
|
+
});
|
|
1132
|
+
for (const match of matches.sort()) {
|
|
1133
|
+
const normalized = normalizePath(match);
|
|
1134
|
+
if (changed && !changed.has(normalized)) continue;
|
|
1135
|
+
planned.push({
|
|
1136
|
+
input: resolve(cwd, match),
|
|
1137
|
+
output: resolveOutput(rule, match, cwd),
|
|
1138
|
+
rule
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
const outputs = /* @__PURE__ */ new Map();
|
|
1143
|
+
const inputs = new Set(planned.map(({ input }) => input));
|
|
1144
|
+
for (const asset of planned) {
|
|
1145
|
+
const owner = outputs.get(asset.output);
|
|
1146
|
+
if (owner && owner !== asset.input) {
|
|
1147
|
+
return failure(
|
|
1148
|
+
"invalid_recipe",
|
|
1149
|
+
`Output collision: ${relative(cwd, owner)} and ${relative(cwd, asset.input)} both write ${relative(cwd, asset.output)}`
|
|
1150
|
+
);
|
|
1151
|
+
}
|
|
1152
|
+
if (asset.output !== asset.input && inputs.has(asset.output)) {
|
|
1153
|
+
return failure("invalid_recipe", `Output loop: ${relative(cwd, asset.output)} is also a matched input`);
|
|
1154
|
+
}
|
|
1155
|
+
outputs.set(asset.output, asset.input);
|
|
1156
|
+
}
|
|
1157
|
+
return success(planned);
|
|
1158
|
+
}
|
|
1159
|
+
async function executeAsset(asset, mode, cwd, chopper2) {
|
|
1160
|
+
try {
|
|
1161
|
+
const source = new Uint8Array(await readFile(asset.input));
|
|
1162
|
+
const optimized = await chopper2.optimize({ bytes: source, fileName: relative(cwd, asset.input) }, asset.rule.recipe);
|
|
1163
|
+
if (!optimized.ok) {
|
|
1164
|
+
return {
|
|
1165
|
+
input: relative(cwd, asset.input),
|
|
1166
|
+
output: relative(cwd, asset.output),
|
|
1167
|
+
status: "failed",
|
|
1168
|
+
error: optimized.error
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
const base = {
|
|
1172
|
+
input: relative(cwd, asset.input),
|
|
1173
|
+
output: relative(cwd, asset.output),
|
|
1174
|
+
beforeBytes: source.byteLength,
|
|
1175
|
+
afterBytes: optimized.data.bytes.byteLength,
|
|
1176
|
+
engineId: optimized.data.report.engineId
|
|
1177
|
+
};
|
|
1178
|
+
if (mode === "report") return { ...base, status: "reported" };
|
|
1179
|
+
if (mode === "check") {
|
|
1180
|
+
const current = await readFile(asset.output).catch(() => void 0);
|
|
1181
|
+
return {
|
|
1182
|
+
...base,
|
|
1183
|
+
status: current && bytesEqual(current, optimized.data.bytes) ? "current" : "stale"
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
await writeAtomic(asset.output, optimized.data.bytes);
|
|
1187
|
+
return { ...base, status: "written" };
|
|
1188
|
+
} catch (cause) {
|
|
1189
|
+
return {
|
|
1190
|
+
input: relative(cwd, asset.input),
|
|
1191
|
+
output: relative(cwd, asset.output),
|
|
1192
|
+
status: "failed",
|
|
1193
|
+
error: {
|
|
1194
|
+
code: "io_failed",
|
|
1195
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
function resolveOutput(rule, input, cwd) {
|
|
1201
|
+
if (rule.output.mode === "replace") return resolve(cwd, input);
|
|
1202
|
+
const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
|
|
1203
|
+
const inputDirectory = dirname(input) === "." ? "" : dirname(input);
|
|
1204
|
+
const name = basename(input, extname(input));
|
|
1205
|
+
return resolve(
|
|
1206
|
+
cwd,
|
|
1207
|
+
rule.output.path.replaceAll("{dir}", inputDirectory).replaceAll("{name}", name).replaceAll("{ext}", extension.slice(1))
|
|
1208
|
+
);
|
|
1209
|
+
}
|
|
1210
|
+
async function writeAtomic(path, bytes) {
|
|
1211
|
+
await mkdir(dirname(path), { recursive: true });
|
|
1212
|
+
const temporaryDirectory = await mkdtemp(join(dirname(path), ".chopper-"));
|
|
1213
|
+
const pending = join(temporaryDirectory, "output");
|
|
1214
|
+
try {
|
|
1215
|
+
await writeFile(pending, bytes);
|
|
1216
|
+
await rename(pending, path);
|
|
1217
|
+
} finally {
|
|
1218
|
+
await rm(temporaryDirectory, { recursive: true, force: true });
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
function bytesEqual(left, right) {
|
|
1222
|
+
if (left.byteLength !== right.byteLength) return false;
|
|
1223
|
+
return left.every((value, index) => value === right[index]);
|
|
1224
|
+
}
|
|
1225
|
+
function normalizePath(path) {
|
|
1226
|
+
return path.replaceAll("\\", "/");
|
|
1227
|
+
}
|
|
1228
|
+
async function mapConcurrent(values, concurrency, operation) {
|
|
1229
|
+
const results = new Array(values.length);
|
|
1230
|
+
let next = 0;
|
|
1231
|
+
await Promise.all(
|
|
1232
|
+
Array.from({ length: Math.min(concurrency, values.length) }, async () => {
|
|
1233
|
+
while (next < values.length) {
|
|
1234
|
+
const index = next++;
|
|
1235
|
+
results[index] = await operation(values[index]);
|
|
1236
|
+
}
|
|
1237
|
+
})
|
|
1238
|
+
);
|
|
1239
|
+
return results;
|
|
1240
|
+
}
|
|
1241
|
+
function summarize(files) {
|
|
1242
|
+
return {
|
|
1243
|
+
matched: files.length,
|
|
1244
|
+
written: files.filter(({ status }) => status === "written").length,
|
|
1245
|
+
current: files.filter(({ status }) => status === "current").length,
|
|
1246
|
+
stale: files.filter(({ status }) => status === "stale").length,
|
|
1247
|
+
reported: files.filter(({ status }) => status === "reported").length,
|
|
1248
|
+
failed: files.filter(({ status }) => status === "failed").length
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
async function syncCodecs(output) {
|
|
1252
|
+
const destination = resolve(output);
|
|
1253
|
+
const source = new URL("../../codecs/", import.meta.url);
|
|
1254
|
+
try {
|
|
1255
|
+
const files = (await readdir(source)).sort();
|
|
1256
|
+
await mkdir(destination, { recursive: true });
|
|
1257
|
+
await Promise.all(files.map((file) => copyFile(new URL(file, source), join(destination, file))));
|
|
1258
|
+
return success({ directory: destination, files });
|
|
1259
|
+
} catch (cause) {
|
|
1260
|
+
return failure("io_failed", `Could not sync codecs to ${output}`, cause);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
export { createNodeChopper, createNodeGlbEngine, createNodeImageEngine, loadConfig, optimizeFile, planAssets, runConfig, syncCodecs };
|
|
1265
|
+
//# sourceMappingURL=index.js.map
|
|
1266
|
+
//# sourceMappingURL=index.js.map
|