vizmatic 0.7.2 → 0.8.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/stage.cjs CHANGED
@@ -177,6 +177,7 @@ __export(stage_exports, {
177
177
  Heatmap: () => Heatmap,
178
178
  Histogram: () => Histogram,
179
179
  IDENTITY: () => IDENTITY,
180
+ ImageAssetError: () => ImageAssetError,
180
181
  InfoBox: () => InfoBox,
181
182
  LOOKS: () => LOOKS,
182
183
  Label3D: () => Label3D,
@@ -350,6 +351,7 @@ __export(stage_exports, {
350
351
  rect: () => rect,
351
352
  rectPath: () => rectPath,
352
353
  regularPolygon: () => regularPolygon,
354
+ resolveImageAsset: () => resolveImageAsset,
353
355
  resolveLook: () => resolveLook,
354
356
  retime: () => retime,
355
357
  reverseRing: () => reverseRing,
@@ -2804,6 +2806,1964 @@ var Value = class {
2804
2806
  }
2805
2807
  };
2806
2808
 
2809
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/png_decoder.js
2810
+ var import_fflate = require("fflate");
2811
+
2812
+ // node_modules/.pnpm/iobuffer@6.0.1/node_modules/iobuffer/lib/text.js
2813
+ function decode(bytes, encoding = "utf8") {
2814
+ const decoder = new TextDecoder(encoding);
2815
+ return decoder.decode(bytes);
2816
+ }
2817
+ var encoder = new TextEncoder();
2818
+ function encode(str) {
2819
+ return encoder.encode(str);
2820
+ }
2821
+
2822
+ // node_modules/.pnpm/iobuffer@6.0.1/node_modules/iobuffer/lib/iobuffer.js
2823
+ var defaultByteLength = 1024 * 8;
2824
+ var hostBigEndian = (() => {
2825
+ const array = new Uint8Array(4);
2826
+ const view = new Uint32Array(array.buffer);
2827
+ return !((view[0] = 1) & array[0]);
2828
+ })();
2829
+ var typedArrays = {
2830
+ int8: globalThis.Int8Array,
2831
+ uint8: globalThis.Uint8Array,
2832
+ int16: globalThis.Int16Array,
2833
+ uint16: globalThis.Uint16Array,
2834
+ int32: globalThis.Int32Array,
2835
+ uint32: globalThis.Uint32Array,
2836
+ uint64: globalThis.BigUint64Array,
2837
+ int64: globalThis.BigInt64Array,
2838
+ float32: globalThis.Float32Array,
2839
+ float64: globalThis.Float64Array
2840
+ };
2841
+ var IOBuffer = class _IOBuffer {
2842
+ /**
2843
+ * Reference to the internal ArrayBuffer object.
2844
+ */
2845
+ buffer;
2846
+ /**
2847
+ * Byte length of the internal ArrayBuffer.
2848
+ */
2849
+ byteLength;
2850
+ /**
2851
+ * Byte offset of the internal ArrayBuffer.
2852
+ */
2853
+ byteOffset;
2854
+ /**
2855
+ * Byte length of the internal ArrayBuffer.
2856
+ */
2857
+ length;
2858
+ /**
2859
+ * The current offset of the buffer's pointer.
2860
+ */
2861
+ offset;
2862
+ lastWrittenByte;
2863
+ littleEndian;
2864
+ _data;
2865
+ _mark;
2866
+ _marks;
2867
+ /**
2868
+ * Create a new IOBuffer.
2869
+ * @param data - The data to construct the IOBuffer with.
2870
+ * If data is a number, it will be the new buffer's length<br>
2871
+ * If data is `undefined`, the buffer will be initialized with a default length of 8Kb<br>
2872
+ * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,
2873
+ * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.
2874
+ * @param options - An object for the options.
2875
+ * @returns A new IOBuffer instance.
2876
+ */
2877
+ constructor(data = defaultByteLength, options = {}) {
2878
+ let dataIsGiven = false;
2879
+ if (typeof data === "number") {
2880
+ data = new ArrayBuffer(data);
2881
+ } else {
2882
+ dataIsGiven = true;
2883
+ this.lastWrittenByte = data.byteLength;
2884
+ }
2885
+ const offset = options.offset ? options.offset >>> 0 : 0;
2886
+ const byteLength = data.byteLength - offset;
2887
+ let dvOffset = offset;
2888
+ if (ArrayBuffer.isView(data) || data instanceof _IOBuffer) {
2889
+ if (data.byteLength !== data.buffer.byteLength) {
2890
+ dvOffset = data.byteOffset + offset;
2891
+ }
2892
+ data = data.buffer;
2893
+ }
2894
+ if (dataIsGiven) {
2895
+ this.lastWrittenByte = byteLength;
2896
+ } else {
2897
+ this.lastWrittenByte = 0;
2898
+ }
2899
+ this.buffer = data;
2900
+ this.length = byteLength;
2901
+ this.byteLength = byteLength;
2902
+ this.byteOffset = dvOffset;
2903
+ this.offset = 0;
2904
+ this.littleEndian = true;
2905
+ this._data = new DataView(this.buffer, dvOffset, byteLength);
2906
+ this._mark = 0;
2907
+ this._marks = [];
2908
+ }
2909
+ /**
2910
+ * Checks if the memory allocated to the buffer is sufficient to store more
2911
+ * bytes after the offset.
2912
+ * @param byteLength - The needed memory in bytes.
2913
+ * @returns `true` if there is sufficient space and `false` otherwise.
2914
+ */
2915
+ available(byteLength = 1) {
2916
+ return this.offset + byteLength <= this.length;
2917
+ }
2918
+ /**
2919
+ * Check if little-endian mode is used for reading and writing multi-byte
2920
+ * values.
2921
+ * @returns `true` if little-endian mode is used, `false` otherwise.
2922
+ */
2923
+ isLittleEndian() {
2924
+ return this.littleEndian;
2925
+ }
2926
+ /**
2927
+ * Set little-endian mode for reading and writing multi-byte values.
2928
+ * @returns This.
2929
+ */
2930
+ setLittleEndian() {
2931
+ this.littleEndian = true;
2932
+ return this;
2933
+ }
2934
+ /**
2935
+ * Check if big-endian mode is used for reading and writing multi-byte values.
2936
+ * @returns `true` if big-endian mode is used, `false` otherwise.
2937
+ */
2938
+ isBigEndian() {
2939
+ return !this.littleEndian;
2940
+ }
2941
+ /**
2942
+ * Switches to big-endian mode for reading and writing multi-byte values.
2943
+ * @returns This.
2944
+ */
2945
+ setBigEndian() {
2946
+ this.littleEndian = false;
2947
+ return this;
2948
+ }
2949
+ /**
2950
+ * Move the pointer n bytes forward.
2951
+ * @param n - Number of bytes to skip.
2952
+ * @returns This.
2953
+ */
2954
+ skip(n = 1) {
2955
+ this.offset += n;
2956
+ return this;
2957
+ }
2958
+ /**
2959
+ * Move the pointer n bytes backward.
2960
+ * @param n - Number of bytes to move back.
2961
+ * @returns This.
2962
+ */
2963
+ back(n = 1) {
2964
+ this.offset -= n;
2965
+ return this;
2966
+ }
2967
+ /**
2968
+ * Move the pointer to the given offset.
2969
+ * @param offset - The offset to move to.
2970
+ * @returns This.
2971
+ */
2972
+ seek(offset) {
2973
+ this.offset = offset;
2974
+ return this;
2975
+ }
2976
+ /**
2977
+ * Store the current pointer offset.
2978
+ * @see {@link IOBuffer#reset}
2979
+ * @returns This.
2980
+ */
2981
+ mark() {
2982
+ this._mark = this.offset;
2983
+ return this;
2984
+ }
2985
+ /**
2986
+ * Move the pointer back to the last pointer offset set by mark.
2987
+ * @see {@link IOBuffer#mark}
2988
+ * @returns This.
2989
+ */
2990
+ reset() {
2991
+ this.offset = this._mark;
2992
+ return this;
2993
+ }
2994
+ /**
2995
+ * Push the current pointer offset to the mark stack.
2996
+ * @see {@link IOBuffer#popMark}
2997
+ * @returns This.
2998
+ */
2999
+ pushMark() {
3000
+ this._marks.push(this.offset);
3001
+ return this;
3002
+ }
3003
+ /**
3004
+ * Pop the last pointer offset from the mark stack, and set the current
3005
+ * pointer offset to the popped value.
3006
+ * @see {@link IOBuffer#pushMark}
3007
+ * @returns This.
3008
+ */
3009
+ popMark() {
3010
+ const offset = this._marks.pop();
3011
+ if (offset === void 0) {
3012
+ throw new Error("Mark stack empty");
3013
+ }
3014
+ this.seek(offset);
3015
+ return this;
3016
+ }
3017
+ /**
3018
+ * Move the pointer offset back to 0.
3019
+ * @returns This.
3020
+ */
3021
+ rewind() {
3022
+ this.offset = 0;
3023
+ return this;
3024
+ }
3025
+ /**
3026
+ * Make sure the buffer has sufficient memory to write a given byteLength at
3027
+ * the current pointer offset.
3028
+ * If the buffer's memory is insufficient, this method will create a new
3029
+ * buffer (a copy) with a length that is twice (byteLength + current offset).
3030
+ * @param byteLength - The needed memory in bytes.
3031
+ * @returns This.
3032
+ */
3033
+ ensureAvailable(byteLength = 1) {
3034
+ if (!this.available(byteLength)) {
3035
+ const lengthNeeded = this.offset + byteLength;
3036
+ const newLength = lengthNeeded * 2;
3037
+ const newArray = new Uint8Array(newLength);
3038
+ newArray.set(new Uint8Array(this.buffer));
3039
+ this.buffer = newArray.buffer;
3040
+ this.length = newLength;
3041
+ this.byteLength = newLength;
3042
+ this._data = new DataView(this.buffer);
3043
+ }
3044
+ return this;
3045
+ }
3046
+ /**
3047
+ * Read a byte and return false if the byte's value is 0, or true otherwise.
3048
+ * Moves pointer forward by one byte.
3049
+ * @returns The read boolean.
3050
+ */
3051
+ readBoolean() {
3052
+ return this.readUint8() !== 0;
3053
+ }
3054
+ /**
3055
+ * Read a signed 8-bit integer and move pointer forward by 1 byte.
3056
+ * @returns The read byte.
3057
+ */
3058
+ readInt8() {
3059
+ return this._data.getInt8(this.offset++);
3060
+ }
3061
+ /**
3062
+ * Read an unsigned 8-bit integer and move pointer forward by 1 byte.
3063
+ * @returns The read byte.
3064
+ */
3065
+ readUint8() {
3066
+ return this._data.getUint8(this.offset++);
3067
+ }
3068
+ /**
3069
+ * Alias for {@link IOBuffer#readUint8}.
3070
+ * @returns The read byte.
3071
+ */
3072
+ readByte() {
3073
+ return this.readUint8();
3074
+ }
3075
+ /**
3076
+ * Read `n` bytes and move pointer forward by `n` bytes.
3077
+ * @param n - Number of bytes to read.
3078
+ * @returns The read bytes.
3079
+ */
3080
+ readBytes(n = 1) {
3081
+ return this.readArray(n, "uint8");
3082
+ }
3083
+ /**
3084
+ * Creates an array of corresponding to the type `type` and size `size`.
3085
+ * For example, type `uint8` will create a `Uint8Array`.
3086
+ * @param size - size of the resulting array
3087
+ * @param type - number type of elements to read
3088
+ * @returns The read array.
3089
+ */
3090
+ readArray(size, type) {
3091
+ const bytes = typedArrays[type].BYTES_PER_ELEMENT * size;
3092
+ const offset = this.byteOffset + this.offset;
3093
+ const slice = this.buffer.slice(offset, offset + bytes);
3094
+ if (this.littleEndian === hostBigEndian && type !== "uint8" && type !== "int8") {
3095
+ const slice2 = new Uint8Array(this.buffer.slice(offset, offset + bytes));
3096
+ slice2.reverse();
3097
+ const returnArray2 = new typedArrays[type](slice2.buffer);
3098
+ this.offset += bytes;
3099
+ returnArray2.reverse();
3100
+ return returnArray2;
3101
+ }
3102
+ const returnArray = new typedArrays[type](slice);
3103
+ this.offset += bytes;
3104
+ return returnArray;
3105
+ }
3106
+ /**
3107
+ * Read a 16-bit signed integer and move pointer forward by 2 bytes.
3108
+ * @returns The read value.
3109
+ */
3110
+ readInt16() {
3111
+ const value = this._data.getInt16(this.offset, this.littleEndian);
3112
+ this.offset += 2;
3113
+ return value;
3114
+ }
3115
+ /**
3116
+ * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.
3117
+ * @returns The read value.
3118
+ */
3119
+ readUint16() {
3120
+ const value = this._data.getUint16(this.offset, this.littleEndian);
3121
+ this.offset += 2;
3122
+ return value;
3123
+ }
3124
+ /**
3125
+ * Read a 32-bit signed integer and move pointer forward by 4 bytes.
3126
+ * @returns The read value.
3127
+ */
3128
+ readInt32() {
3129
+ const value = this._data.getInt32(this.offset, this.littleEndian);
3130
+ this.offset += 4;
3131
+ return value;
3132
+ }
3133
+ /**
3134
+ * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.
3135
+ * @returns The read value.
3136
+ */
3137
+ readUint32() {
3138
+ const value = this._data.getUint32(this.offset, this.littleEndian);
3139
+ this.offset += 4;
3140
+ return value;
3141
+ }
3142
+ /**
3143
+ * Read a 32-bit floating number and move pointer forward by 4 bytes.
3144
+ * @returns The read value.
3145
+ */
3146
+ readFloat32() {
3147
+ const value = this._data.getFloat32(this.offset, this.littleEndian);
3148
+ this.offset += 4;
3149
+ return value;
3150
+ }
3151
+ /**
3152
+ * Read a 64-bit floating number and move pointer forward by 8 bytes.
3153
+ * @returns The read value.
3154
+ */
3155
+ readFloat64() {
3156
+ const value = this._data.getFloat64(this.offset, this.littleEndian);
3157
+ this.offset += 8;
3158
+ return value;
3159
+ }
3160
+ /**
3161
+ * Read a 64-bit signed integer number and move pointer forward by 8 bytes.
3162
+ * @returns The read value.
3163
+ */
3164
+ readBigInt64() {
3165
+ const value = this._data.getBigInt64(this.offset, this.littleEndian);
3166
+ this.offset += 8;
3167
+ return value;
3168
+ }
3169
+ /**
3170
+ * Read a 64-bit unsigned integer number and move pointer forward by 8 bytes.
3171
+ * @returns The read value.
3172
+ */
3173
+ readBigUint64() {
3174
+ const value = this._data.getBigUint64(this.offset, this.littleEndian);
3175
+ this.offset += 8;
3176
+ return value;
3177
+ }
3178
+ /**
3179
+ * Read a 1-byte ASCII character and move pointer forward by 1 byte.
3180
+ * @returns The read character.
3181
+ */
3182
+ readChar() {
3183
+ return String.fromCharCode(this.readInt8());
3184
+ }
3185
+ /**
3186
+ * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.
3187
+ * @param n - Number of characters to read.
3188
+ * @returns The read characters.
3189
+ */
3190
+ readChars(n = 1) {
3191
+ let result = "";
3192
+ for (let i = 0; i < n; i++) {
3193
+ result += this.readChar();
3194
+ }
3195
+ return result;
3196
+ }
3197
+ /**
3198
+ * Read the next `n` bytes, return a UTF-8 decoded string and move pointer
3199
+ * forward by `n` bytes.
3200
+ * @param n - Number of bytes to read.
3201
+ * @returns The decoded string.
3202
+ */
3203
+ readUtf8(n = 1) {
3204
+ return decode(this.readBytes(n));
3205
+ }
3206
+ /**
3207
+ * Read the next `n` bytes, return a string decoded with `encoding` and move pointer
3208
+ * forward by `n` bytes.
3209
+ * If no encoding is passed, the function is equivalent to @see {@link IOBuffer#readUtf8}
3210
+ * @param n - Number of bytes to read.
3211
+ * @param encoding - The encoding to use. Default is 'utf8'.
3212
+ * @returns The decoded string.
3213
+ */
3214
+ decodeText(n = 1, encoding = "utf8") {
3215
+ return decode(this.readBytes(n), encoding);
3216
+ }
3217
+ /**
3218
+ * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer
3219
+ * forward by 1 byte.
3220
+ * @param value - The value to write.
3221
+ * @returns This.
3222
+ */
3223
+ writeBoolean(value) {
3224
+ this.writeUint8(value ? 255 : 0);
3225
+ return this;
3226
+ }
3227
+ /**
3228
+ * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.
3229
+ * @param value - The value to write.
3230
+ * @returns This.
3231
+ */
3232
+ writeInt8(value) {
3233
+ this.ensureAvailable(1);
3234
+ this._data.setInt8(this.offset++, value);
3235
+ this._updateLastWrittenByte();
3236
+ return this;
3237
+ }
3238
+ /**
3239
+ * Write `value` as an 8-bit unsigned integer and move pointer forward by 1
3240
+ * byte.
3241
+ * @param value - The value to write.
3242
+ * @returns This.
3243
+ */
3244
+ writeUint8(value) {
3245
+ this.ensureAvailable(1);
3246
+ this._data.setUint8(this.offset++, value);
3247
+ this._updateLastWrittenByte();
3248
+ return this;
3249
+ }
3250
+ /**
3251
+ * An alias for {@link IOBuffer#writeUint8}.
3252
+ * @param value - The value to write.
3253
+ * @returns This.
3254
+ */
3255
+ writeByte(value) {
3256
+ return this.writeUint8(value);
3257
+ }
3258
+ /**
3259
+ * Write all elements of `bytes` as uint8 values and move pointer forward by
3260
+ * `bytes.length` bytes.
3261
+ * @param bytes - The array of bytes to write.
3262
+ * @returns This.
3263
+ */
3264
+ writeBytes(bytes) {
3265
+ this.ensureAvailable(bytes.length);
3266
+ for (let i = 0; i < bytes.length; i++) {
3267
+ this._data.setUint8(this.offset++, bytes[i]);
3268
+ }
3269
+ this._updateLastWrittenByte();
3270
+ return this;
3271
+ }
3272
+ /**
3273
+ * Write `value` as a 16-bit signed integer and move pointer forward by 2
3274
+ * bytes.
3275
+ * @param value - The value to write.
3276
+ * @returns This.
3277
+ */
3278
+ writeInt16(value) {
3279
+ this.ensureAvailable(2);
3280
+ this._data.setInt16(this.offset, value, this.littleEndian);
3281
+ this.offset += 2;
3282
+ this._updateLastWrittenByte();
3283
+ return this;
3284
+ }
3285
+ /**
3286
+ * Write `value` as a 16-bit unsigned integer and move pointer forward by 2
3287
+ * bytes.
3288
+ * @param value - The value to write.
3289
+ * @returns This.
3290
+ */
3291
+ writeUint16(value) {
3292
+ this.ensureAvailable(2);
3293
+ this._data.setUint16(this.offset, value, this.littleEndian);
3294
+ this.offset += 2;
3295
+ this._updateLastWrittenByte();
3296
+ return this;
3297
+ }
3298
+ /**
3299
+ * Write `value` as a 32-bit signed integer and move pointer forward by 4
3300
+ * bytes.
3301
+ * @param value - The value to write.
3302
+ * @returns This.
3303
+ */
3304
+ writeInt32(value) {
3305
+ this.ensureAvailable(4);
3306
+ this._data.setInt32(this.offset, value, this.littleEndian);
3307
+ this.offset += 4;
3308
+ this._updateLastWrittenByte();
3309
+ return this;
3310
+ }
3311
+ /**
3312
+ * Write `value` as a 32-bit unsigned integer and move pointer forward by 4
3313
+ * bytes.
3314
+ * @param value - The value to write.
3315
+ * @returns This.
3316
+ */
3317
+ writeUint32(value) {
3318
+ this.ensureAvailable(4);
3319
+ this._data.setUint32(this.offset, value, this.littleEndian);
3320
+ this.offset += 4;
3321
+ this._updateLastWrittenByte();
3322
+ return this;
3323
+ }
3324
+ /**
3325
+ * Write `value` as a 32-bit floating number and move pointer forward by 4
3326
+ * bytes.
3327
+ * @param value - The value to write.
3328
+ * @returns This.
3329
+ */
3330
+ writeFloat32(value) {
3331
+ this.ensureAvailable(4);
3332
+ this._data.setFloat32(this.offset, value, this.littleEndian);
3333
+ this.offset += 4;
3334
+ this._updateLastWrittenByte();
3335
+ return this;
3336
+ }
3337
+ /**
3338
+ * Write `value` as a 64-bit floating number and move pointer forward by 8
3339
+ * bytes.
3340
+ * @param value - The value to write.
3341
+ * @returns This.
3342
+ */
3343
+ writeFloat64(value) {
3344
+ this.ensureAvailable(8);
3345
+ this._data.setFloat64(this.offset, value, this.littleEndian);
3346
+ this.offset += 8;
3347
+ this._updateLastWrittenByte();
3348
+ return this;
3349
+ }
3350
+ /**
3351
+ * Write `value` as a 64-bit signed bigint and move pointer forward by 8
3352
+ * bytes.
3353
+ * @param value - The value to write.
3354
+ * @returns This.
3355
+ */
3356
+ writeBigInt64(value) {
3357
+ this.ensureAvailable(8);
3358
+ this._data.setBigInt64(this.offset, value, this.littleEndian);
3359
+ this.offset += 8;
3360
+ this._updateLastWrittenByte();
3361
+ return this;
3362
+ }
3363
+ /**
3364
+ * Write `value` as a 64-bit unsigned bigint and move pointer forward by 8
3365
+ * bytes.
3366
+ * @param value - The value to write.
3367
+ * @returns This.
3368
+ */
3369
+ writeBigUint64(value) {
3370
+ this.ensureAvailable(8);
3371
+ this._data.setBigUint64(this.offset, value, this.littleEndian);
3372
+ this.offset += 8;
3373
+ this._updateLastWrittenByte();
3374
+ return this;
3375
+ }
3376
+ /**
3377
+ * Write the charCode of `str`'s first character as an 8-bit unsigned integer
3378
+ * and move pointer forward by 1 byte.
3379
+ * @param str - The character to write.
3380
+ * @returns This.
3381
+ */
3382
+ writeChar(str) {
3383
+ return this.writeUint8(str.charCodeAt(0));
3384
+ }
3385
+ /**
3386
+ * Write the charCodes of all `str`'s characters as 8-bit unsigned integers
3387
+ * and move pointer forward by `str.length` bytes.
3388
+ * @param str - The characters to write.
3389
+ * @returns This.
3390
+ */
3391
+ writeChars(str) {
3392
+ for (let i = 0; i < str.length; i++) {
3393
+ this.writeUint8(str.charCodeAt(i));
3394
+ }
3395
+ return this;
3396
+ }
3397
+ /**
3398
+ * UTF-8 encode and write `str` to the current pointer offset and move pointer
3399
+ * forward according to the encoded length.
3400
+ * @param str - The string to write.
3401
+ * @returns This.
3402
+ */
3403
+ writeUtf8(str) {
3404
+ return this.writeBytes(encode(str));
3405
+ }
3406
+ /**
3407
+ * Export a Uint8Array view of the internal buffer.
3408
+ * The view starts at the byte offset and its length
3409
+ * is calculated to stop at the last written byte or the original length.
3410
+ * @returns A new Uint8Array view.
3411
+ */
3412
+ toArray() {
3413
+ return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);
3414
+ }
3415
+ /**
3416
+ * Get the total number of bytes written so far, regardless of the current offset.
3417
+ * @returns - Total number of bytes.
3418
+ */
3419
+ getWrittenByteLength() {
3420
+ return this.lastWrittenByte - this.byteOffset;
3421
+ }
3422
+ /**
3423
+ * Update the last written byte offset
3424
+ * @private
3425
+ */
3426
+ _updateLastWrittenByte() {
3427
+ if (this.offset > this.lastWrittenByte) {
3428
+ this.lastWrittenByte = this.offset;
3429
+ }
3430
+ }
3431
+ };
3432
+
3433
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/crc.js
3434
+ var crcTable = [];
3435
+ for (let n = 0; n < 256; n++) {
3436
+ let c = n;
3437
+ for (let k = 0; k < 8; k++) {
3438
+ if (c & 1) {
3439
+ c = 3988292384 ^ c >>> 1;
3440
+ } else {
3441
+ c = c >>> 1;
3442
+ }
3443
+ }
3444
+ crcTable[n] = c;
3445
+ }
3446
+ var initialCrc = 4294967295;
3447
+ function updateCrc(currentCrc, data, length) {
3448
+ let c = currentCrc;
3449
+ for (let n = 0; n < length; n++) {
3450
+ c = crcTable[(c ^ data[n]) & 255] ^ c >>> 8;
3451
+ }
3452
+ return c;
3453
+ }
3454
+ function crc(data, length) {
3455
+ return (updateCrc(initialCrc, data, length) ^ initialCrc) >>> 0;
3456
+ }
3457
+ function checkCrc(buffer, crcLength, chunkName) {
3458
+ const expectedCrc = buffer.readUint32();
3459
+ const actualCrc = crc(new Uint8Array(buffer.buffer, buffer.byteOffset + buffer.offset - crcLength - 4, crcLength), crcLength);
3460
+ if (actualCrc !== expectedCrc) {
3461
+ throw new Error(`CRC mismatch for chunk ${chunkName}. Expected ${expectedCrc}, found ${actualCrc}`);
3462
+ }
3463
+ }
3464
+
3465
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/unfilter.js
3466
+ function unfilterNone(currentLine, newLine, bytesPerLine) {
3467
+ for (let i = 0; i < bytesPerLine; i++) {
3468
+ newLine[i] = currentLine[i];
3469
+ }
3470
+ }
3471
+ function unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel) {
3472
+ let i = 0;
3473
+ for (; i < bytesPerPixel; i++) {
3474
+ newLine[i] = currentLine[i];
3475
+ }
3476
+ for (; i < bytesPerLine; i++) {
3477
+ newLine[i] = currentLine[i] + newLine[i - bytesPerPixel] & 255;
3478
+ }
3479
+ }
3480
+ function unfilterUp(currentLine, newLine, prevLine, bytesPerLine) {
3481
+ let i = 0;
3482
+ if (prevLine.length === 0) {
3483
+ for (; i < bytesPerLine; i++) {
3484
+ newLine[i] = currentLine[i];
3485
+ }
3486
+ } else {
3487
+ for (; i < bytesPerLine; i++) {
3488
+ newLine[i] = currentLine[i] + prevLine[i] & 255;
3489
+ }
3490
+ }
3491
+ }
3492
+ function unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
3493
+ let i = 0;
3494
+ if (prevLine.length === 0) {
3495
+ for (; i < bytesPerPixel; i++) {
3496
+ newLine[i] = currentLine[i];
3497
+ }
3498
+ for (; i < bytesPerLine; i++) {
3499
+ newLine[i] = currentLine[i] + (newLine[i - bytesPerPixel] >> 1) & 255;
3500
+ }
3501
+ } else {
3502
+ for (; i < bytesPerPixel; i++) {
3503
+ newLine[i] = currentLine[i] + (prevLine[i] >> 1) & 255;
3504
+ }
3505
+ for (; i < bytesPerLine; i++) {
3506
+ newLine[i] = currentLine[i] + (newLine[i - bytesPerPixel] + prevLine[i] >> 1) & 255;
3507
+ }
3508
+ }
3509
+ }
3510
+ function unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
3511
+ let i = 0;
3512
+ if (prevLine.length === 0) {
3513
+ for (; i < bytesPerPixel; i++) {
3514
+ newLine[i] = currentLine[i];
3515
+ }
3516
+ for (; i < bytesPerLine; i++) {
3517
+ newLine[i] = currentLine[i] + newLine[i - bytesPerPixel] & 255;
3518
+ }
3519
+ } else {
3520
+ for (; i < bytesPerPixel; i++) {
3521
+ newLine[i] = currentLine[i] + prevLine[i] & 255;
3522
+ }
3523
+ for (; i < bytesPerLine; i++) {
3524
+ newLine[i] = currentLine[i] + paethPredictor(newLine[i - bytesPerPixel], prevLine[i], prevLine[i - bytesPerPixel]) & 255;
3525
+ }
3526
+ }
3527
+ }
3528
+ function paethPredictor(a, b, c) {
3529
+ const p = a + b - c;
3530
+ const pa = Math.abs(p - a);
3531
+ const pb = Math.abs(p - b);
3532
+ const pc = Math.abs(p - c);
3533
+ if (pa <= pb && pa <= pc)
3534
+ return a;
3535
+ else if (pb <= pc)
3536
+ return b;
3537
+ else
3538
+ return c;
3539
+ }
3540
+
3541
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/apply_unfilter.js
3542
+ function applyUnfilter(filterType, currentLine, newLine, prevLine, passLineBytes, bytesPerPixel) {
3543
+ switch (filterType) {
3544
+ case 0:
3545
+ unfilterNone(currentLine, newLine, passLineBytes);
3546
+ break;
3547
+ case 1:
3548
+ unfilterSub(currentLine, newLine, passLineBytes, bytesPerPixel);
3549
+ break;
3550
+ case 2:
3551
+ unfilterUp(currentLine, newLine, prevLine, passLineBytes);
3552
+ break;
3553
+ case 3:
3554
+ unfilterAverage(currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
3555
+ break;
3556
+ case 4:
3557
+ unfilterPaeth(currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
3558
+ break;
3559
+ default:
3560
+ throw new Error(`Unsupported filter: ${filterType}`);
3561
+ }
3562
+ }
3563
+
3564
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/decode_interlace_adam7.js
3565
+ var uint16 = new Uint16Array([255]);
3566
+ var uint8 = new Uint8Array(uint16.buffer);
3567
+ var osIsLittleEndian = uint8[0] === 255;
3568
+ function decodeInterlaceAdam7(params) {
3569
+ const { data, width, height, channels, depth } = params;
3570
+ const passes = [
3571
+ { x: 0, y: 0, xStep: 8, yStep: 8 },
3572
+ // Pass 1
3573
+ { x: 4, y: 0, xStep: 8, yStep: 8 },
3574
+ // Pass 2
3575
+ { x: 0, y: 4, xStep: 4, yStep: 8 },
3576
+ // Pass 3
3577
+ { x: 2, y: 0, xStep: 4, yStep: 4 },
3578
+ // Pass 4
3579
+ { x: 0, y: 2, xStep: 2, yStep: 4 },
3580
+ // Pass 5
3581
+ { x: 1, y: 0, xStep: 2, yStep: 2 },
3582
+ // Pass 6
3583
+ { x: 0, y: 1, xStep: 1, yStep: 2 }
3584
+ // Pass 7
3585
+ ];
3586
+ const bytesPerPixel = Math.ceil(depth / 8) * channels;
3587
+ const resultData = new Uint8Array(height * width * bytesPerPixel);
3588
+ let offset = 0;
3589
+ for (let passIndex = 0; passIndex < 7; passIndex++) {
3590
+ const pass = passes[passIndex];
3591
+ const passWidth = Math.ceil((width - pass.x) / pass.xStep);
3592
+ const passHeight = Math.ceil((height - pass.y) / pass.yStep);
3593
+ if (passWidth <= 0 || passHeight <= 0)
3594
+ continue;
3595
+ const passLineBytes = passWidth * bytesPerPixel;
3596
+ const prevLine = new Uint8Array(passLineBytes);
3597
+ for (let y = 0; y < passHeight; y++) {
3598
+ const filterType = data[offset++];
3599
+ const currentLine = data.subarray(offset, offset + passLineBytes);
3600
+ offset += passLineBytes;
3601
+ const newLine = new Uint8Array(passLineBytes);
3602
+ applyUnfilter(filterType, currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
3603
+ prevLine.set(newLine);
3604
+ for (let x = 0; x < passWidth; x++) {
3605
+ const outputX = pass.x + x * pass.xStep;
3606
+ const outputY = pass.y + y * pass.yStep;
3607
+ if (outputX >= width || outputY >= height)
3608
+ continue;
3609
+ for (let i = 0; i < bytesPerPixel; i++) {
3610
+ resultData[(outputY * width + outputX) * bytesPerPixel + i] = newLine[x * bytesPerPixel + i];
3611
+ }
3612
+ }
3613
+ }
3614
+ }
3615
+ if (depth === 16) {
3616
+ const uint16Data = new Uint16Array(resultData.buffer);
3617
+ if (osIsLittleEndian) {
3618
+ for (let k = 0; k < uint16Data.length; k++) {
3619
+ uint16Data[k] = swap16(uint16Data[k]);
3620
+ }
3621
+ }
3622
+ return uint16Data;
3623
+ } else {
3624
+ return resultData;
3625
+ }
3626
+ }
3627
+ function swap16(val) {
3628
+ return (val & 255) << 8 | val >> 8 & 255;
3629
+ }
3630
+
3631
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/decode_interlace_null.js
3632
+ var uint162 = new Uint16Array([255]);
3633
+ var uint82 = new Uint8Array(uint162.buffer);
3634
+ var osIsLittleEndian2 = uint82[0] === 255;
3635
+ var empty = new Uint8Array(0);
3636
+ function decodeInterlaceNull(params) {
3637
+ const { data, width, height, channels, depth } = params;
3638
+ const bytesPerPixel = Math.ceil(depth / 8) * channels;
3639
+ const bytesPerLine = Math.ceil(depth / 8 * channels * width);
3640
+ const newData = new Uint8Array(height * bytesPerLine);
3641
+ let prevLine = empty;
3642
+ let offset = 0;
3643
+ let currentLine;
3644
+ let newLine;
3645
+ for (let i = 0; i < height; i++) {
3646
+ currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);
3647
+ newLine = newData.subarray(i * bytesPerLine, (i + 1) * bytesPerLine);
3648
+ switch (data[offset]) {
3649
+ case 0:
3650
+ unfilterNone(currentLine, newLine, bytesPerLine);
3651
+ break;
3652
+ case 1:
3653
+ unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel);
3654
+ break;
3655
+ case 2:
3656
+ unfilterUp(currentLine, newLine, prevLine, bytesPerLine);
3657
+ break;
3658
+ case 3:
3659
+ unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
3660
+ break;
3661
+ case 4:
3662
+ unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
3663
+ break;
3664
+ default:
3665
+ throw new Error(`Unsupported filter: ${data[offset]}`);
3666
+ }
3667
+ prevLine = newLine;
3668
+ offset += bytesPerLine + 1;
3669
+ }
3670
+ if (depth === 16) {
3671
+ const uint16Data = new Uint16Array(newData.buffer);
3672
+ if (osIsLittleEndian2) {
3673
+ for (let k = 0; k < uint16Data.length; k++) {
3674
+ uint16Data[k] = swap162(uint16Data[k]);
3675
+ }
3676
+ }
3677
+ return uint16Data;
3678
+ } else {
3679
+ return newData;
3680
+ }
3681
+ }
3682
+ function swap162(val) {
3683
+ return (val & 255) << 8 | val >> 8 & 255;
3684
+ }
3685
+
3686
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/signature.js
3687
+ var pngSignature = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
3688
+ function checkSignature(buffer) {
3689
+ if (!hasPngSignature(buffer.readBytes(pngSignature.length))) {
3690
+ throw new Error("wrong PNG signature");
3691
+ }
3692
+ }
3693
+ function hasPngSignature(array) {
3694
+ if (array.length < pngSignature.length) {
3695
+ return false;
3696
+ }
3697
+ for (let i = 0; i < pngSignature.length; i++) {
3698
+ if (array[i] !== pngSignature[i]) {
3699
+ return false;
3700
+ }
3701
+ }
3702
+ return true;
3703
+ }
3704
+
3705
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/text.js
3706
+ var textChunkName = "tEXt";
3707
+ var NULL = 0;
3708
+ var latin1Decoder = new TextDecoder("latin1");
3709
+ function validateKeyword(keyword) {
3710
+ validateLatin1(keyword);
3711
+ if (keyword.length === 0 || keyword.length > 79) {
3712
+ throw new Error("keyword length must be between 1 and 79");
3713
+ }
3714
+ }
3715
+ var latin1Regex = /^[\u0000-\u00FF]*$/;
3716
+ function validateLatin1(text2) {
3717
+ if (!latin1Regex.test(text2)) {
3718
+ throw new Error("invalid latin1 text");
3719
+ }
3720
+ }
3721
+ function decodetEXt(text2, buffer, length) {
3722
+ const keyword = readKeyword(buffer);
3723
+ text2[keyword] = readLatin1(buffer, length - keyword.length - 1);
3724
+ }
3725
+ function readKeyword(buffer) {
3726
+ buffer.mark();
3727
+ while (buffer.readByte() !== NULL) {
3728
+ }
3729
+ const end = buffer.offset;
3730
+ buffer.reset();
3731
+ const keyword = latin1Decoder.decode(buffer.readBytes(end - buffer.offset - 1));
3732
+ buffer.skip(1);
3733
+ validateKeyword(keyword);
3734
+ return keyword;
3735
+ }
3736
+ function readLatin1(buffer, length) {
3737
+ return latin1Decoder.decode(buffer.readBytes(length));
3738
+ }
3739
+
3740
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/internal_types.js
3741
+ var ColorType = {
3742
+ UNKNOWN: -1,
3743
+ GREYSCALE: 0,
3744
+ TRUECOLOUR: 2,
3745
+ INDEXED_COLOUR: 3,
3746
+ GREYSCALE_ALPHA: 4,
3747
+ TRUECOLOUR_ALPHA: 6
3748
+ };
3749
+ var CompressionMethod = {
3750
+ UNKNOWN: -1,
3751
+ DEFLATE: 0
3752
+ };
3753
+ var FilterMethod = {
3754
+ UNKNOWN: -1,
3755
+ ADAPTIVE: 0
3756
+ };
3757
+ var InterlaceMethod = {
3758
+ UNKNOWN: -1,
3759
+ NO_INTERLACE: 0,
3760
+ ADAM7: 1
3761
+ };
3762
+ var DisposeOpType = {
3763
+ NONE: 0,
3764
+ BACKGROUND: 1,
3765
+ PREVIOUS: 2
3766
+ };
3767
+ var BlendOpType = {
3768
+ SOURCE: 0,
3769
+ OVER: 1
3770
+ };
3771
+
3772
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/png_decoder.js
3773
+ var PngDecoder = class extends IOBuffer {
3774
+ _checkCrc;
3775
+ _inflator;
3776
+ _png;
3777
+ _apng;
3778
+ _end;
3779
+ _hasPalette;
3780
+ _palette;
3781
+ _hasTransparency;
3782
+ _transparency;
3783
+ _compressionMethod;
3784
+ _filterMethod;
3785
+ _interlaceMethod;
3786
+ _colorType;
3787
+ _isAnimated;
3788
+ _numberOfFrames;
3789
+ _numberOfPlays;
3790
+ _frames;
3791
+ _writingDataChunks;
3792
+ _chunks;
3793
+ _inflatorResult;
3794
+ constructor(data, options = {}) {
3795
+ super(data);
3796
+ const { checkCrc: checkCrc2 = false } = options;
3797
+ this._checkCrc = checkCrc2;
3798
+ this._inflator = new import_fflate.Unzlib((chunk, final) => {
3799
+ this._chunks.push(chunk);
3800
+ if (final) {
3801
+ const totalLength = this._chunks.reduce((sum, c) => sum + c.length, 0);
3802
+ this._inflatorResult = new Uint8Array(totalLength);
3803
+ let offset = 0;
3804
+ for (const chunk2 of this._chunks) {
3805
+ this._inflatorResult.set(chunk2, offset);
3806
+ offset += chunk2.length;
3807
+ }
3808
+ this._chunks = [];
3809
+ }
3810
+ });
3811
+ this._chunks = [];
3812
+ this._png = {
3813
+ width: -1,
3814
+ height: -1,
3815
+ channels: -1,
3816
+ data: new Uint8Array(0),
3817
+ depth: 1,
3818
+ text: {}
3819
+ };
3820
+ this._apng = {
3821
+ width: -1,
3822
+ height: -1,
3823
+ channels: -1,
3824
+ depth: 1,
3825
+ numberOfFrames: 1,
3826
+ numberOfPlays: 0,
3827
+ text: {},
3828
+ frames: []
3829
+ };
3830
+ this._end = false;
3831
+ this._hasPalette = false;
3832
+ this._palette = [];
3833
+ this._hasTransparency = false;
3834
+ this._transparency = new Uint16Array(0);
3835
+ this._compressionMethod = CompressionMethod.UNKNOWN;
3836
+ this._filterMethod = FilterMethod.UNKNOWN;
3837
+ this._interlaceMethod = InterlaceMethod.UNKNOWN;
3838
+ this._colorType = ColorType.UNKNOWN;
3839
+ this._isAnimated = false;
3840
+ this._numberOfFrames = 1;
3841
+ this._numberOfPlays = 0;
3842
+ this._frames = [];
3843
+ this._writingDataChunks = false;
3844
+ this._inflatorResult = new Uint8Array(0);
3845
+ this.setBigEndian();
3846
+ }
3847
+ decode() {
3848
+ checkSignature(this);
3849
+ while (!this._end) {
3850
+ const length = this.readUint32();
3851
+ const type = this.readChars(4);
3852
+ this.decodeChunk(length, type);
3853
+ }
3854
+ this._inflator.push(new Uint8Array(0), true);
3855
+ this.decodeImage();
3856
+ return this._png;
3857
+ }
3858
+ decodeApng() {
3859
+ checkSignature(this);
3860
+ while (!this._end) {
3861
+ const length = this.readUint32();
3862
+ const type = this.readChars(4);
3863
+ this.decodeApngChunk(length, type);
3864
+ }
3865
+ this.decodeApngImage();
3866
+ return this._apng;
3867
+ }
3868
+ // https://www.w3.org/TR/PNG/#5Chunk-layout
3869
+ decodeChunk(length, type) {
3870
+ const offset = this.offset;
3871
+ switch (type) {
3872
+ // 11.2 Critical chunks
3873
+ case "IHDR":
3874
+ this.decodeIHDR();
3875
+ break;
3876
+ case "PLTE":
3877
+ this.decodePLTE(length);
3878
+ break;
3879
+ case "IDAT":
3880
+ this.decodeIDAT(length);
3881
+ break;
3882
+ case "IEND":
3883
+ this._end = true;
3884
+ break;
3885
+ // 11.3 Ancillary chunks
3886
+ case "tRNS":
3887
+ this.decodetRNS(length);
3888
+ break;
3889
+ case "iCCP":
3890
+ this.decodeiCCP(length);
3891
+ break;
3892
+ case textChunkName:
3893
+ decodetEXt(this._png.text, this, length);
3894
+ break;
3895
+ case "pHYs":
3896
+ this.decodepHYs();
3897
+ break;
3898
+ default:
3899
+ this.skip(length);
3900
+ break;
3901
+ }
3902
+ if (this.offset - offset !== length) {
3903
+ throw new Error(`Length mismatch while decoding chunk ${type}`);
3904
+ }
3905
+ if (this._checkCrc) {
3906
+ checkCrc(this, length + 4, type);
3907
+ } else {
3908
+ this.skip(4);
3909
+ }
3910
+ }
3911
+ decodeApngChunk(length, type) {
3912
+ const offset = this.offset;
3913
+ if (type !== "fdAT" && type !== "IDAT" && this._writingDataChunks) {
3914
+ this.pushDataToFrame();
3915
+ }
3916
+ switch (type) {
3917
+ case "acTL":
3918
+ this.decodeACTL();
3919
+ break;
3920
+ case "fcTL":
3921
+ this.decodeFCTL();
3922
+ break;
3923
+ case "fdAT":
3924
+ this.decodeFDAT(length);
3925
+ break;
3926
+ default:
3927
+ this.decodeChunk(length, type);
3928
+ this.offset = offset + length;
3929
+ break;
3930
+ }
3931
+ if (this.offset - offset !== length) {
3932
+ throw new Error(`Length mismatch while decoding chunk ${type}`);
3933
+ }
3934
+ if (this._checkCrc) {
3935
+ checkCrc(this, length + 4, type);
3936
+ } else {
3937
+ this.skip(4);
3938
+ }
3939
+ }
3940
+ // https://www.w3.org/TR/PNG/#11IHDR
3941
+ decodeIHDR() {
3942
+ const image2 = this._png;
3943
+ image2.width = this.readUint32();
3944
+ image2.height = this.readUint32();
3945
+ image2.depth = checkBitDepth(this.readUint8());
3946
+ const colorType = this.readUint8();
3947
+ this._colorType = colorType;
3948
+ let channels;
3949
+ switch (colorType) {
3950
+ case ColorType.GREYSCALE:
3951
+ channels = 1;
3952
+ break;
3953
+ case ColorType.TRUECOLOUR:
3954
+ channels = 3;
3955
+ break;
3956
+ case ColorType.INDEXED_COLOUR:
3957
+ channels = 1;
3958
+ break;
3959
+ case ColorType.GREYSCALE_ALPHA:
3960
+ channels = 2;
3961
+ break;
3962
+ case ColorType.TRUECOLOUR_ALPHA:
3963
+ channels = 4;
3964
+ break;
3965
+ // Kept for exhaustiveness.
3966
+ // eslint-disable-next-line unicorn/no-useless-switch-case
3967
+ case ColorType.UNKNOWN:
3968
+ default:
3969
+ throw new Error(`Unknown color type: ${colorType}`);
3970
+ }
3971
+ this._png.channels = channels;
3972
+ this._compressionMethod = this.readUint8();
3973
+ if (this._compressionMethod !== CompressionMethod.DEFLATE) {
3974
+ throw new Error(`Unsupported compression method: ${this._compressionMethod}`);
3975
+ }
3976
+ this._filterMethod = this.readUint8();
3977
+ this._interlaceMethod = this.readUint8();
3978
+ }
3979
+ decodeACTL() {
3980
+ this._numberOfFrames = this.readUint32();
3981
+ this._numberOfPlays = this.readUint32();
3982
+ this._isAnimated = true;
3983
+ }
3984
+ decodeFCTL() {
3985
+ const image2 = {
3986
+ sequenceNumber: this.readUint32(),
3987
+ width: this.readUint32(),
3988
+ height: this.readUint32(),
3989
+ xOffset: this.readUint32(),
3990
+ yOffset: this.readUint32(),
3991
+ delayNumber: this.readUint16(),
3992
+ delayDenominator: this.readUint16(),
3993
+ disposeOp: this.readUint8(),
3994
+ blendOp: this.readUint8(),
3995
+ data: new Uint8Array(0)
3996
+ };
3997
+ this._frames.push(image2);
3998
+ }
3999
+ // https://www.w3.org/TR/PNG/#11PLTE
4000
+ decodePLTE(length) {
4001
+ if (length % 3 !== 0) {
4002
+ throw new RangeError(`PLTE field length must be a multiple of 3. Got ${length}`);
4003
+ }
4004
+ const l = length / 3;
4005
+ this._hasPalette = true;
4006
+ const palette = [];
4007
+ this._palette = palette;
4008
+ for (let i = 0; i < l; i++) {
4009
+ palette.push([this.readUint8(), this.readUint8(), this.readUint8()]);
4010
+ }
4011
+ }
4012
+ // https://www.w3.org/TR/PNG/#11IDAT
4013
+ decodeIDAT(length) {
4014
+ this._writingDataChunks = true;
4015
+ const dataLength = length;
4016
+ const dataOffset = this.offset + this.byteOffset;
4017
+ try {
4018
+ this._inflator.push(new Uint8Array(this.buffer, dataOffset, dataLength), false);
4019
+ } catch (error) {
4020
+ throw new Error("Error while decompressing the data:", { cause: error });
4021
+ }
4022
+ this.skip(length);
4023
+ }
4024
+ decodeFDAT(length) {
4025
+ this._writingDataChunks = true;
4026
+ let dataLength = length;
4027
+ let dataOffset = this.offset + this.byteOffset;
4028
+ dataOffset += 4;
4029
+ dataLength -= 4;
4030
+ try {
4031
+ this._inflator.push(new Uint8Array(this.buffer, dataOffset, dataLength), false);
4032
+ } catch (error) {
4033
+ throw new Error("Error while decompressing the data:", { cause: error });
4034
+ }
4035
+ this.skip(length);
4036
+ }
4037
+ // https://www.w3.org/TR/PNG/#11tRNS
4038
+ decodetRNS(length) {
4039
+ switch (this._colorType) {
4040
+ case ColorType.GREYSCALE:
4041
+ case ColorType.TRUECOLOUR: {
4042
+ if (length % 2 !== 0) {
4043
+ throw new RangeError(`tRNS chunk length must be a multiple of 2. Got ${length}`);
4044
+ }
4045
+ if (length / 2 > this._png.width * this._png.height) {
4046
+ throw new Error(`tRNS chunk contains more alpha values than there are pixels (${length / 2} vs ${this._png.width * this._png.height})`);
4047
+ }
4048
+ this._hasTransparency = true;
4049
+ this._transparency = new Uint16Array(length / 2);
4050
+ for (let i = 0; i < length / 2; i++) {
4051
+ this._transparency[i] = this.readUint16();
4052
+ }
4053
+ break;
4054
+ }
4055
+ case ColorType.INDEXED_COLOUR: {
4056
+ if (length > this._palette.length) {
4057
+ throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${length} vs ${this._palette.length})`);
4058
+ }
4059
+ let i = 0;
4060
+ for (; i < length; i++) {
4061
+ const alpha = this.readByte();
4062
+ this._palette[i].push(alpha);
4063
+ }
4064
+ for (; i < this._palette.length; i++) {
4065
+ this._palette[i].push(255);
4066
+ }
4067
+ break;
4068
+ }
4069
+ // Kept for exhaustiveness.
4070
+ /* eslint-disable unicorn/no-useless-switch-case */
4071
+ case ColorType.UNKNOWN:
4072
+ case ColorType.GREYSCALE_ALPHA:
4073
+ case ColorType.TRUECOLOUR_ALPHA:
4074
+ default: {
4075
+ throw new Error(`tRNS chunk is not supported for color type ${this._colorType}`);
4076
+ }
4077
+ }
4078
+ }
4079
+ // https://www.w3.org/TR/PNG/#11iCCP
4080
+ decodeiCCP(length) {
4081
+ const name = readKeyword(this);
4082
+ const compressionMethod = this.readUint8();
4083
+ if (compressionMethod !== CompressionMethod.DEFLATE) {
4084
+ throw new Error(`Unsupported iCCP compression method: ${compressionMethod}`);
4085
+ }
4086
+ const compressedProfile = this.readBytes(length - name.length - 2);
4087
+ this._png.iccEmbeddedProfile = {
4088
+ name,
4089
+ profile: (0, import_fflate.unzlibSync)(compressedProfile)
4090
+ };
4091
+ }
4092
+ // https://www.w3.org/TR/PNG/#11pHYs
4093
+ decodepHYs() {
4094
+ const ppuX = this.readUint32();
4095
+ const ppuY = this.readUint32();
4096
+ const unitSpecifier = this.readByte();
4097
+ this._png.resolution = {
4098
+ x: ppuX,
4099
+ y: ppuY,
4100
+ unit: unitSpecifier
4101
+ };
4102
+ }
4103
+ decodeApngImage() {
4104
+ this._apng.width = this._png.width;
4105
+ this._apng.height = this._png.height;
4106
+ this._apng.channels = this._png.channels;
4107
+ this._apng.depth = this._png.depth;
4108
+ this._apng.numberOfFrames = this._numberOfFrames;
4109
+ this._apng.numberOfPlays = this._numberOfPlays;
4110
+ this._apng.text = this._png.text;
4111
+ this._apng.resolution = this._png.resolution;
4112
+ for (let i = 0; i < this._numberOfFrames; i++) {
4113
+ const newFrame = {
4114
+ sequenceNumber: this._frames[i].sequenceNumber,
4115
+ delayNumber: this._frames[i].delayNumber,
4116
+ delayDenominator: this._frames[i].delayDenominator,
4117
+ data: this._apng.depth === 8 ? new Uint8Array(this._apng.width * this._apng.height * this._apng.channels) : new Uint16Array(this._apng.width * this._apng.height * this._apng.channels)
4118
+ };
4119
+ const frame = this._frames.at(i);
4120
+ if (frame) {
4121
+ frame.data = decodeInterlaceNull({
4122
+ data: frame.data,
4123
+ width: frame.width,
4124
+ height: frame.height,
4125
+ channels: this._apng.channels,
4126
+ depth: this._apng.depth
4127
+ });
4128
+ if (this._hasPalette) {
4129
+ this._apng.palette = this._palette;
4130
+ }
4131
+ if (this._hasTransparency) {
4132
+ this._apng.transparency = this._transparency;
4133
+ }
4134
+ if (i === 0 || frame.xOffset === 0 && frame.yOffset === 0 && frame.width === this._png.width && frame.height === this._png.height) {
4135
+ newFrame.data = frame.data;
4136
+ } else {
4137
+ const prevFrame = this._apng.frames.at(i - 1);
4138
+ this.disposeFrame(frame, prevFrame, newFrame);
4139
+ this.addFrameDataToCanvas(newFrame, frame);
4140
+ }
4141
+ this._apng.frames.push(newFrame);
4142
+ }
4143
+ }
4144
+ return this._apng;
4145
+ }
4146
+ disposeFrame(frame, prevFrame, imageFrame) {
4147
+ switch (frame.disposeOp) {
4148
+ case DisposeOpType.NONE:
4149
+ break;
4150
+ case DisposeOpType.BACKGROUND:
4151
+ for (let row = 0; row < this._png.height; row++) {
4152
+ for (let col = 0; col < this._png.width; col++) {
4153
+ const index = (row * frame.width + col) * this._png.channels;
4154
+ for (let channel = 0; channel < this._png.channels; channel++) {
4155
+ imageFrame.data[index + channel] = 0;
4156
+ }
4157
+ }
4158
+ }
4159
+ break;
4160
+ case DisposeOpType.PREVIOUS:
4161
+ imageFrame.data.set(prevFrame.data);
4162
+ break;
4163
+ default:
4164
+ throw new Error("Unknown disposeOp");
4165
+ }
4166
+ }
4167
+ addFrameDataToCanvas(imageFrame, frame) {
4168
+ const maxValue = 1 << this._png.depth;
4169
+ const calculatePixelIndices = (row, col) => {
4170
+ const index = ((row + frame.yOffset) * this._png.width + frame.xOffset + col) * this._png.channels;
4171
+ const frameIndex = (row * frame.width + col) * this._png.channels;
4172
+ return { index, frameIndex };
4173
+ };
4174
+ switch (frame.blendOp) {
4175
+ case BlendOpType.SOURCE:
4176
+ for (let row = 0; row < frame.height; row++) {
4177
+ for (let col = 0; col < frame.width; col++) {
4178
+ const { index, frameIndex } = calculatePixelIndices(row, col);
4179
+ for (let channel = 0; channel < this._png.channels; channel++) {
4180
+ imageFrame.data[index + channel] = frame.data[frameIndex + channel];
4181
+ }
4182
+ }
4183
+ }
4184
+ break;
4185
+ // https://www.w3.org/TR/png-3/#13Alpha-channel-processing
4186
+ case BlendOpType.OVER:
4187
+ for (let row = 0; row < frame.height; row++) {
4188
+ for (let col = 0; col < frame.width; col++) {
4189
+ const { index, frameIndex } = calculatePixelIndices(row, col);
4190
+ for (let channel = 0; channel < this._png.channels; channel++) {
4191
+ const sourceAlpha = frame.data[frameIndex + this._png.channels - 1] / maxValue;
4192
+ const foregroundValue = channel % (this._png.channels - 1) === 0 ? 1 : frame.data[frameIndex + channel];
4193
+ const value = Math.floor(sourceAlpha * foregroundValue + (1 - sourceAlpha) * imageFrame.data[index + channel]);
4194
+ imageFrame.data[index + channel] += value;
4195
+ }
4196
+ }
4197
+ }
4198
+ break;
4199
+ default:
4200
+ throw new Error("Unknown blendOp");
4201
+ }
4202
+ }
4203
+ decodeImage() {
4204
+ const data = this._inflatorResult;
4205
+ if (this._filterMethod !== FilterMethod.ADAPTIVE) {
4206
+ throw new Error(`Filter method ${this._filterMethod} not supported`);
4207
+ }
4208
+ if (this._interlaceMethod === InterlaceMethod.NO_INTERLACE) {
4209
+ this._png.data = decodeInterlaceNull({
4210
+ data,
4211
+ width: this._png.width,
4212
+ height: this._png.height,
4213
+ channels: this._png.channels,
4214
+ depth: this._png.depth
4215
+ });
4216
+ } else if (this._interlaceMethod === InterlaceMethod.ADAM7) {
4217
+ this._png.data = decodeInterlaceAdam7({
4218
+ data,
4219
+ width: this._png.width,
4220
+ height: this._png.height,
4221
+ channels: this._png.channels,
4222
+ depth: this._png.depth
4223
+ });
4224
+ } else {
4225
+ throw new Error(`Interlace method ${this._interlaceMethod} not supported`);
4226
+ }
4227
+ if (this._hasPalette) {
4228
+ this._png.palette = this._palette;
4229
+ }
4230
+ if (this._hasTransparency) {
4231
+ this._png.transparency = this._transparency;
4232
+ }
4233
+ }
4234
+ pushDataToFrame() {
4235
+ this._inflator.push(new Uint8Array(0), true);
4236
+ const result = this._inflatorResult;
4237
+ const lastFrame = this._frames.at(-1);
4238
+ if (lastFrame) {
4239
+ lastFrame.data = result;
4240
+ } else {
4241
+ this._frames.push({
4242
+ sequenceNumber: 0,
4243
+ width: this._png.width,
4244
+ height: this._png.height,
4245
+ xOffset: 0,
4246
+ yOffset: 0,
4247
+ delayNumber: 0,
4248
+ delayDenominator: 0,
4249
+ disposeOp: DisposeOpType.NONE,
4250
+ blendOp: BlendOpType.SOURCE,
4251
+ data: result
4252
+ });
4253
+ }
4254
+ this._inflator = new import_fflate.Unzlib((chunk, final) => {
4255
+ this._chunks.push(chunk);
4256
+ if (final) {
4257
+ const totalLength = this._chunks.reduce((sum, c) => sum + c.length, 0);
4258
+ this._inflatorResult = new Uint8Array(totalLength);
4259
+ let offset = 0;
4260
+ for (const chunk2 of this._chunks) {
4261
+ this._inflatorResult.set(chunk2, offset);
4262
+ offset += chunk2.length;
4263
+ }
4264
+ this._chunks = [];
4265
+ }
4266
+ });
4267
+ this._chunks = [];
4268
+ this._writingDataChunks = false;
4269
+ }
4270
+ };
4271
+ function checkBitDepth(value) {
4272
+ if (value !== 1 && value !== 2 && value !== 4 && value !== 8 && value !== 16) {
4273
+ throw new Error(`invalid bit depth: ${value}`);
4274
+ }
4275
+ return value;
4276
+ }
4277
+
4278
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/png_encoder.js
4279
+ var import_fflate2 = require("fflate");
4280
+
4281
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/index.js
4282
+ function decodePng(data, options) {
4283
+ const decoder = new PngDecoder(data, options);
4284
+ return decoder.decode();
4285
+ }
4286
+
4287
+ // src/stage/image.ts
4288
+ var import_fflate3 = require("fflate");
4289
+ var ImageAssetError = class extends Error {
4290
+ constructor(message) {
4291
+ super(message);
4292
+ this.name = "ImageAssetError";
4293
+ }
4294
+ };
4295
+ var MAX_BYTES = 16 * 1024 * 1024;
4296
+ var MAX_PIXELS = 16 * 1024 * 1024;
4297
+ var PREFIX = "data:image/png;base64,";
4298
+ var RUNTIME = /* @__PURE__ */ Symbol.for("vizmatic.stage.image.runtime.v1");
4299
+ var host = globalThis;
4300
+ var runtime = host[RUNTIME] ?? Object.freeze({ prepared: /* @__PURE__ */ new WeakSet(), browserSources: /* @__PURE__ */ new WeakMap() });
4301
+ if (!host[RUNTIME]) Object.defineProperty(host, RUNTIME, { value: runtime });
4302
+ var { prepared, browserSources } = runtime;
4303
+ var visibility = /* @__PURE__ */ new WeakMap();
4304
+ var VISIBILITY = /* @__PURE__ */ Symbol.for("vizmatic.stage.image.visibility.v1");
4305
+ function freezeAsset(fields, alpha) {
4306
+ if (alpha !== void 0) {
4307
+ const carried = typeof alpha === "boolean" ? alpha : Object.freeze({ width: alpha.width, height: alpha.height, bits: base64(alpha.mask) });
4308
+ Object.defineProperty(fields, VISIBILITY, { value: carried });
4309
+ visibility.set(fields, alpha);
4310
+ }
4311
+ return Object.freeze(fields);
4312
+ }
4313
+ function fail(message) {
4314
+ throw new ImageAssetError(message);
4315
+ }
4316
+ function base64(bytes) {
4317
+ const chunks = [];
4318
+ for (let at = 0; at < bytes.length; at += 8192) chunks.push(String.fromCharCode(...bytes.subarray(at, at + 8192)));
4319
+ return btoa(chunks.join(""));
4320
+ }
4321
+ function dataUri(bytes, mediaType = "image/png") {
4322
+ return `data:${mediaType};base64,${base64(bytes)}`;
4323
+ }
4324
+ async function sourceBytes(source, options) {
4325
+ if (source instanceof Uint8Array) {
4326
+ if (source.byteLength > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes.`);
4327
+ return Uint8Array.from(source);
4328
+ }
4329
+ if (typeof source !== "string" || !source) fail("Image asset needs encoded bytes, a PNG data URI, or a local filename.");
4330
+ if (source.startsWith("data:")) {
4331
+ if (!source.startsWith(PREFIX)) fail("Image assets currently support only image/png base64 data URIs.");
4332
+ const encoded = source.slice(PREFIX.length);
4333
+ if (!encoded.length || encoded.length > Math.ceil(MAX_BYTES / 3) * 4 || encoded.length % 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) fail("Image asset contains invalid or oversized base64 data.");
4334
+ const bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));
4335
+ if (bytes.length > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes.`);
4336
+ return bytes;
4337
+ }
4338
+ if (/^[a-z][\w+.-]*:/i.test(source) || source.startsWith("//")) fail("Image assets must use local files or embedded bytes; remote URLs are not loaded.");
4339
+ if (typeof process === "undefined" || !process.versions?.node) fail("Resolve browser image assets from embedded bytes or a data URI before compiling.");
4340
+ const fsModule = "node:fs/promises", pathModule = "node:path";
4341
+ const [fs, path] = await Promise.all([import(fsModule), import(pathModule)]);
4342
+ const filename = path.resolve(options.baseDir ?? process.cwd(), source);
4343
+ try {
4344
+ if ((await fs.stat(filename)).size > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes: ${filename}`);
4345
+ const bytes = await fs.readFile(filename);
4346
+ if (bytes.length > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes: ${filename}`);
4347
+ return Uint8Array.from(bytes);
4348
+ } catch (error) {
4349
+ if (error instanceof ImageAssetError) throw error;
4350
+ fail(`Could not read image asset ${JSON.stringify(filename)}: ${error.message}`);
4351
+ }
4352
+ }
4353
+ function inspectPng(bytes, strict = true) {
4354
+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];
4355
+ if (bytes.length < 33 || signature.some((value, i) => bytes[i] !== value)) fail("Image asset is not a PNG.");
4356
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4357
+ const name = (at) => String.fromCharCode(...bytes.subarray(at + 4, at + 8));
4358
+ if (view.getUint32(8) !== 13 || name(8) !== "IHDR") fail("Image PNG must begin with one IHDR chunk.");
4359
+ const width = view.getUint32(16), height = view.getUint32(20);
4360
+ if (!width || !height || width * height > MAX_PIXELS) fail(`Image PNG must contain at most ${MAX_PIXELS} pixels with positive dimensions.`);
4361
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[bytes[25]];
4362
+ const depth = bytes[24], interlace = bytes[28];
4363
+ if (strict && (depth !== 8 || interlace !== 0)) {
4364
+ fail("Image assets support noninterlaced 8-bit PNGs, including RGB, RGBA, grayscale and palette images.");
4365
+ }
4366
+ const depths = bytes[25] === 0 ? [1, 2, 4, 8, 16] : bytes[25] === 3 ? [1, 2, 4, 8] : [8, 16];
4367
+ if (!channels || !depths.includes(depth) || bytes[26] !== 0 || bytes[27] !== 0 || interlace > 1) fail("Image PNG has unsupported header fields.");
4368
+ const passes = interlace ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] : [[0, 0, 1, 1]];
4369
+ const expected = passes.reduce((sum, [x, y, dx, dy]) => {
4370
+ const w = Math.max(0, Math.ceil((width - x) / dx)), h = Math.max(0, Math.ceil((height - y) / dy));
4371
+ return sum + (w && h ? h * (1 + Math.ceil(w * channels * depth / 8)) : 0);
4372
+ }, 0);
4373
+ let expanded = 0, data = false, dataEnded = false, ended = false;
4374
+ const inflater = new import_fflate3.Unzlib((chunk) => {
4375
+ expanded += chunk.length;
4376
+ if (expanded > expected) fail("Image PNG expands beyond its declared dimensions.");
4377
+ });
4378
+ for (let at = 8; at + 12 <= bytes.length; ) {
4379
+ const length = view.getUint32(at), type = name(at), end = at + length + 12;
4380
+ if (end > bytes.length) fail("Image PNG chunk exceeds the encoded bytes.");
4381
+ if (type === "IHDR" && at !== 8) fail("Image PNG has more than one IHDR chunk.");
4382
+ if (strict && ["iCCP", "acTL", "fcTL", "fdAT"].includes(type)) fail("Image assets do not support compressed color profiles or animated PNGs.");
4383
+ if (type === "iCCP") {
4384
+ let start = at + 8;
4385
+ while (start < end - 4 && bytes[start] !== 0) start++;
4386
+ if (start + 2 >= end - 4 || bytes[start + 1] !== 0) fail("Image PNG color profile is invalid.");
4387
+ let profileSize = 0;
4388
+ const profile = new import_fflate3.Unzlib((chunk) => {
4389
+ profileSize += chunk.length;
4390
+ if (profileSize > MAX_BYTES) fail("Image PNG color profile exceeds the decoded byte limit.");
4391
+ });
4392
+ for (let part = start + 2; part < end - 4; part += 1024) profile.push(bytes.subarray(part, Math.min(part + 1024, end - 4)), false);
4393
+ profile.push(new Uint8Array(0), true);
4394
+ }
4395
+ if (type === "IDAT") {
4396
+ if (dataEnded) fail("Image PNG data chunks must be consecutive.");
4397
+ data = true;
4398
+ for (let part = at + 8; part < end - 4; part += 1024) inflater.push(bytes.subarray(part, Math.min(part + 1024, end - 4)), false);
4399
+ } else if (data) dataEnded = true;
4400
+ if (type === "IEND") {
4401
+ if (length || end !== bytes.length) fail("Image PNG has an invalid end chunk.");
4402
+ ended = true;
4403
+ break;
4404
+ }
4405
+ at = end;
4406
+ }
4407
+ if (!data || !ended) fail("Image PNG is missing its data or end chunk.");
4408
+ inflater.push(new Uint8Array(0), true);
4409
+ if (expanded !== expected) fail("Image PNG scanlines do not match its dimensions.");
4410
+ return { width, height };
4411
+ }
4412
+ async function resolveImageAsset(source, options = {}) {
4413
+ if (options.mediaType !== void 0 && options.mediaType !== "image/png") fail(`Unsupported image asset media type: ${options.mediaType}. Use image/png.`);
4414
+ if (options.sha256 !== void 0 && (typeof options.sha256 !== "string" || !/^[a-f\d]{64}$/i.test(options.sha256))) fail("Image asset SHA-256 must contain 64 hexadecimal digits.");
4415
+ if (options.id !== void 0 && (typeof options.id !== "string" || !options.id.trim())) fail("Image asset ID must be a nonempty string.");
4416
+ const bytes = await sourceBytes(source, options);
4417
+ let dimensions;
4418
+ let visible;
4419
+ try {
4420
+ dimensions = inspectPng(bytes);
4421
+ const decoded = decodePng(bytes, { checkCrc: true });
4422
+ visible = pngVisibility(decoded);
4423
+ if (decoded.width !== dimensions.width || decoded.height !== dimensions.height) fail("Decoded image dimensions differ from the PNG header.");
4424
+ } catch (error) {
4425
+ if (error instanceof ImageAssetError) throw error;
4426
+ fail(`Could not decode image asset: ${error.message}`);
4427
+ }
4428
+ for (const key of ["width", "height"]) {
4429
+ if (options[key] !== void 0 && options[key] !== dimensions[key]) fail(`Image asset ${key} is ${dimensions[key]}, not the declared ${options[key]}.`);
4430
+ }
4431
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes).buffer);
4432
+ const sha256 = Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
4433
+ if (options.sha256 !== void 0 && sha256 !== options.sha256.toLowerCase()) fail(`Image asset SHA-256 mismatch: expected ${options.sha256.toLowerCase()}, received ${sha256}.`);
4434
+ const asset = freezeAsset({ ...options.id ? { id: options.id } : {}, src: dataUri(bytes), mediaType: "image/png", ...dimensions, sha256 }, visible);
4435
+ await preloadBrowserImage(asset, bytes);
4436
+ prepared.add(asset);
4437
+ return asset;
4438
+ }
4439
+ async function preloadBrowserImage(asset, bytes) {
4440
+ const swapped = asset.mediaType === "image/jpeg" && jpegOrientation(bytes) >= 5;
4441
+ const width = swapped ? asset.height : asset.width, height = swapped ? asset.width : asset.height;
4442
+ if (asset.mediaType === "image/gif" && typeof createImageBitmap !== "undefined") {
4443
+ try {
4444
+ const bitmap = await createImageBitmap(new Blob([Uint8Array.from(bytes).buffer], { type: asset.mediaType }));
4445
+ if (bitmap.width !== width || bitmap.height !== height) fail("Browser image dimensions differ from the validated asset.");
4446
+ browserSources.set(asset, bitmap);
4447
+ } catch (error) {
4448
+ if (error instanceof ImageAssetError) throw error;
4449
+ fail(`Browser could not decode image asset: ${error.message}`);
4450
+ }
4451
+ } else if (typeof Image !== "undefined") {
4452
+ const element = new Image();
4453
+ element.src = asset.src;
4454
+ try {
4455
+ await element.decode();
4456
+ } catch (error) {
4457
+ fail(`Browser could not decode image asset: ${error.message}`);
4458
+ }
4459
+ if (element.naturalWidth !== width || element.naturalHeight !== height) fail("Browser image dimensions differ from the validated asset.");
4460
+ if (asset.mediaType === "image/gif") {
4461
+ const canvas = document.createElement("canvas");
4462
+ canvas.width = asset.width;
4463
+ canvas.height = asset.height;
4464
+ canvas.getContext("2d").drawImage(element, 0, 0);
4465
+ browserSources.set(asset, canvas);
4466
+ } else browserSources.set(asset, element);
4467
+ } else if (typeof createImageBitmap !== "undefined") {
4468
+ try {
4469
+ const bitmap = await createImageBitmap(new Blob([Uint8Array.from(bytes).buffer], { type: asset.mediaType }));
4470
+ if (bitmap.width !== width || bitmap.height !== height) fail("Browser image dimensions differ from the validated asset.");
4471
+ browserSources.set(asset, bitmap);
4472
+ } catch (error) {
4473
+ if (error instanceof ImageAssetError) throw error;
4474
+ fail(`Browser could not decode image asset: ${error.message}`);
4475
+ }
4476
+ }
4477
+ }
4478
+ function jpegOrientation(bytes) {
4479
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4480
+ for (let at = 2; at + 4 <= bytes.length; ) {
4481
+ if (bytes[at++] !== 255) break;
4482
+ while (bytes[at] === 255) at++;
4483
+ const marker = bytes[at++];
4484
+ if (marker === 218 || marker === 217 || at + 2 > bytes.length) break;
4485
+ const length = view.getUint16(at), start = at + 2, end = at + length;
4486
+ if (length < 2 || end > bytes.length) break;
4487
+ if (marker === 225 && end - start >= 14 && String.fromCharCode(...bytes.subarray(start, start + 6)) === "Exif\0\0") {
4488
+ const tiff = start + 6, order = view.getUint16(tiff), little = order === 18761;
4489
+ if (![18761, 19789].includes(order) || view.getUint16(tiff + 2, little) !== 42) return 1;
4490
+ const ifd = tiff + view.getUint32(tiff + 4, little);
4491
+ if (ifd < tiff + 8 || ifd + 2 > end) return 1;
4492
+ const count = view.getUint16(ifd, little);
4493
+ for (let entry = ifd + 2; entry + 12 <= end && entry < ifd + 2 + count * 12; entry += 12) {
4494
+ if (view.getUint16(entry, little) === 274 && view.getUint16(entry + 2, little) === 3 && view.getUint32(entry + 4, little) === 1) {
4495
+ const orientation = view.getUint16(entry + 8, little);
4496
+ return orientation >= 1 && orientation <= 8 ? orientation : 1;
4497
+ }
4498
+ }
4499
+ }
4500
+ at = end;
4501
+ }
4502
+ return 1;
4503
+ }
4504
+ async function resolveLegacyImage(source, allowNetwork) {
4505
+ let bytes, declared;
4506
+ if (source.startsWith("data:")) {
4507
+ const match = /^data:(image\/(?:png|jpe?g|gif));base64,([A-Za-z0-9+/]+={0,2})$/.exec(source);
4508
+ if (!match || match[2].length % 4 || match[2].length > Math.ceil(MAX_BYTES / 3) * 4) fail("Image contains invalid, unsupported or oversized base64 data.");
4509
+ declared = match[1] === "image/jpg" ? "image/jpeg" : match[1];
4510
+ bytes = Uint8Array.from(atob(match[2]), (character) => character.charCodeAt(0));
4511
+ } else if (/^https?:\/\//i.test(source) || source.startsWith("//") || typeof window !== "undefined") {
4512
+ const offline = typeof process !== "undefined" && (process.env?.VIZMATIC_DISABLE_NETWORK === "1" || process.env?.VIZMATIC_OFFLINE === "1");
4513
+ if (!allowNetwork || offline) fail("Network image loading is disabled by imageNetwork: deny or the offline environment.");
4514
+ try {
4515
+ const url = typeof document !== "undefined" ? new URL(source, document.baseURI).href : source;
4516
+ if (!/^https?:\/\//i.test(url)) fail("Network images require an HTTP or HTTPS URL.");
4517
+ const response = await fetch(url, { signal: AbortSignal.timeout(1e4) });
4518
+ if (!response.ok) fail(`Image request failed with HTTP ${response.status}: ${url}`);
4519
+ const length = response.headers.get("content-length");
4520
+ if (length && Number(length) > MAX_BYTES) fail(`Image exceeds ${MAX_BYTES} encoded bytes.`);
4521
+ declared = response.headers.get("content-type")?.split(";")[0].trim();
4522
+ const reader = response.body?.getReader();
4523
+ if (!reader) fail("Image request returned no body.");
4524
+ const chunks = [];
4525
+ let total = 0;
4526
+ for (; ; ) {
4527
+ const { value, done } = await reader.read();
4528
+ if (done) break;
4529
+ total += value.length;
4530
+ if (total > MAX_BYTES) {
4531
+ await reader.cancel();
4532
+ fail(`Image exceeds ${MAX_BYTES} encoded bytes.`);
4533
+ }
4534
+ chunks.push(value);
4535
+ }
4536
+ bytes = new Uint8Array(total);
4537
+ let at = 0;
4538
+ for (const chunk of chunks) {
4539
+ bytes.set(chunk, at);
4540
+ at += chunk.length;
4541
+ }
4542
+ } catch (error) {
4543
+ if (error instanceof ImageAssetError) throw error;
4544
+ fail(`Could not load image ${JSON.stringify(source)}: ${error.message}`);
4545
+ }
4546
+ } else bytes = await sourceBytes(source, {});
4547
+ const { visible, ...info } = legacyImageHeader(bytes);
4548
+ if (declared?.startsWith("image/") && declared !== info.mediaType) fail(`Image MIME type ${declared} does not match ${info.mediaType} bytes.`);
4549
+ const hash = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes).buffer);
4550
+ const sha256 = Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
4551
+ const asset = freezeAsset({ src: dataUri(bytes, info.mediaType), sha256, ...info }, visible);
4552
+ if (typeof process !== "undefined" && process.versions?.node) {
4553
+ const moduleName = "@resvg/resvg-js";
4554
+ const { Resvg } = await import(moduleName);
4555
+ try {
4556
+ const raster = new Resvg(`<svg xmlns="http://www.w3.org/2000/svg" width="${asset.width}" height="${asset.height}"><image width="${asset.width}" height="${asset.height}" href="${asset.src}"/></svg>`, { font: { loadSystemFonts: false } });
4557
+ if (!raster.innerBBox()) fail("Image decoder rejected the encoded image.");
4558
+ const rendered = raster.render();
4559
+ if (asset.mediaType === "image/jpeg" && !rendered.pixels.some((alpha, i) => i % 4 === 3 && alpha > 0)) fail("Image decoder rejected the JPEG pixel data.");
4560
+ } catch (error) {
4561
+ if (error instanceof ImageAssetError) throw error;
4562
+ fail(`Could not decode image: ${error.message}`);
4563
+ }
4564
+ }
4565
+ await preloadBrowserImage(asset, bytes);
4566
+ prepared.add(asset);
4567
+ return asset;
4568
+ }
4569
+ function legacyImageHeader(bytes) {
4570
+ if (!bytes.length || bytes.length > MAX_BYTES) fail("Image bytes are empty or oversized.");
4571
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4572
+ let width = 0, height = 0, mediaType;
4573
+ let visible;
4574
+ if (bytes.length >= 33 && [137, 80, 78, 71, 13, 10, 26, 10].every((v, i) => bytes[i] === v)) {
4575
+ mediaType = "image/png";
4576
+ try {
4577
+ ;
4578
+ ({ width, height } = inspectPng(bytes, false));
4579
+ visible = pngVisibility(decodePng(bytes, { checkCrc: true }));
4580
+ } catch (error) {
4581
+ if (error instanceof ImageAssetError) throw error;
4582
+ fail(`Could not decode image PNG: ${error.message}`);
4583
+ }
4584
+ } else if (bytes.length >= 14 && /^GIF8[79]a$/.test(String.fromCharCode(...bytes.subarray(0, 6)))) {
4585
+ width = view.getUint16(6, true);
4586
+ height = view.getUint16(8, true);
4587
+ mediaType = "image/gif";
4588
+ let at = 13 + (bytes[10] & 128 ? 3 * 2 ** ((bytes[10] & 7) + 1) : 0), frames = 0, ended = false;
4589
+ const blocks = (capture = false) => {
4590
+ const chunks = [];
4591
+ let total = 0;
4592
+ for (; ; ) {
4593
+ if (at >= bytes.length) fail("Image GIF data is truncated.");
4594
+ const length = bytes[at++];
4595
+ if (!length) break;
4596
+ if (capture) {
4597
+ chunks.push(bytes.subarray(at, at + length));
4598
+ total += length;
4599
+ }
4600
+ at += length;
4601
+ if (at > bytes.length) fail("Image GIF block exceeds the encoded bytes.");
4602
+ }
4603
+ const out = new Uint8Array(total);
4604
+ let offset = 0;
4605
+ for (const chunk of chunks) {
4606
+ out.set(chunk, offset);
4607
+ offset += chunk.length;
4608
+ }
4609
+ return out;
4610
+ };
4611
+ while (at < bytes.length) {
4612
+ const tag = bytes[at++];
4613
+ if (tag === 59) {
4614
+ ended = true;
4615
+ break;
4616
+ }
4617
+ if (tag === 33) {
4618
+ at++;
4619
+ blocks();
4620
+ } else if (tag === 44) {
4621
+ if (at + 9 > bytes.length) fail("Image GIF descriptor is truncated.");
4622
+ const fw = view.getUint16(at + 4, true), fh = view.getUint16(at + 6, true), flags = bytes[at + 8];
4623
+ if (!fw || !fh || fw * fh > MAX_PIXELS) fail("Image GIF frame dimensions are invalid.");
4624
+ at += 9 + (flags & 128 ? 3 * 2 ** ((flags & 7) + 1) : 0);
4625
+ if (bytes[at] < 2 || bytes[at] > 8) fail("Image GIF compression code size is invalid.");
4626
+ const codeSize = bytes[at++];
4627
+ validateGifData(blocks(true), codeSize, fw * fh);
4628
+ frames++;
4629
+ } else fail("Image GIF contains an invalid block.");
4630
+ }
4631
+ if (!frames || !ended) fail("Image GIF is missing its frame data or trailer.");
4632
+ } else if (bytes[0] === 255 && bytes[1] === 216) {
4633
+ mediaType = "image/jpeg";
4634
+ for (let at = 2; at + 3 < bytes.length; ) {
4635
+ if (bytes[at++] !== 255) fail("Image JPEG contains an invalid marker.");
4636
+ while (bytes[at] === 255) at++;
4637
+ if (at + 3 > bytes.length) fail("Image JPEG marker is truncated.");
4638
+ const marker = bytes[at++];
4639
+ if (marker === 218 || marker === 217) break;
4640
+ const length = view.getUint16(at);
4641
+ if (length < 2 || at + length > bytes.length) fail("Image JPEG segment is truncated.");
4642
+ if (marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker)) {
4643
+ if (length < 8) fail("Image JPEG frame is truncated.");
4644
+ height = view.getUint16(at + 3);
4645
+ width = view.getUint16(at + 5);
4646
+ }
4647
+ at += length;
4648
+ }
4649
+ if (!bytes.some((value, i) => i > 0 && value === 217 && bytes[i - 1] === 255)) fail("Image JPEG is missing its end marker.");
4650
+ } else fail("Image bytes are not a supported PNG, JPEG or GIF.");
4651
+ if (!width || !height || width * height > MAX_PIXELS) fail(`Image must contain at most ${MAX_PIXELS} pixels with positive dimensions.`);
4652
+ return { width, height, mediaType, visible };
4653
+ }
4654
+ function pngVisibility(png) {
4655
+ const { width, height, channels, depth, data, palette, transparency } = png;
4656
+ if (channels !== 2 && channels !== 4 && !palette && !transparency) return true;
4657
+ const mask = new Uint8Array(Math.ceil(width * height / 8));
4658
+ const sample = (x, y, channel = 0) => depth >= 8 ? data[(y * width + x) * channels + channel] : data[y * Math.ceil(width * depth / 8) + (x * depth >> 3)] >> 8 - depth - x * depth % 8 & (1 << depth) - 1;
4659
+ let count = 0;
4660
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
4661
+ let visible;
4662
+ if (channels === 2 || channels === 4) visible = sample(x, y, channels - 1) > 0;
4663
+ else if (palette) {
4664
+ const color = palette[sample(x, y)];
4665
+ if (!color) fail("Image PNG references a missing palette color.");
4666
+ visible = (color[3] ?? 255) > 0;
4667
+ } else visible = !transparency.every((value, channel) => sample(x, y, channel) === value);
4668
+ if (visible) {
4669
+ const index = y * width + x;
4670
+ mask[index >> 3] |= 1 << (index & 7);
4671
+ count++;
4672
+ }
4673
+ }
4674
+ return count === 0 ? false : count === width * height ? true : { width, height, mask, crops: /* @__PURE__ */ new Map() };
4675
+ }
4676
+ function imageHasVisiblePixels(asset, crop) {
4677
+ let value = asset ? visibility.get(asset) : void 0;
4678
+ if (value === void 0 && asset) {
4679
+ const carried = asset[VISIBILITY];
4680
+ value = typeof carried === "boolean" ? carried : carried ? { width: carried.width, height: carried.height, mask: Uint8Array.from(atob(carried.bits), (c) => c.charCodeAt(0)), crops: /* @__PURE__ */ new Map() } : void 0;
4681
+ if (value !== void 0) visibility.set(asset, value);
4682
+ }
4683
+ if (value === void 0) return true;
4684
+ if (typeof value === "boolean") return value;
4685
+ if (!crop || crop.x === 0 && crop.y === 0 && crop.width === value.width && crop.height === value.height) return true;
4686
+ const key = `${crop.x},${crop.y},${crop.width},${crop.height}`, cached = value.crops.get(key);
4687
+ if (cached !== void 0) return cached;
4688
+ for (let y = Math.floor(crop.y); y < Math.ceil(crop.y + crop.height); y++) for (let x = Math.floor(crop.x); x < Math.ceil(crop.x + crop.width); x++) {
4689
+ const index = y * value.width + x;
4690
+ if (value.mask[index >> 3] & 1 << (index & 7)) {
4691
+ value.crops.set(key, true);
4692
+ return true;
4693
+ }
4694
+ }
4695
+ value.crops.set(key, false);
4696
+ return false;
4697
+ }
4698
+ function validateGifData(data, minimum, pixels) {
4699
+ const clear = 1 << minimum, end = clear + 1, lengths = new Uint16Array(4096);
4700
+ let bits = minimum + 1, next = end + 1, previous = 0, offset = 0, written = 0;
4701
+ for (; ; ) {
4702
+ if (offset + bits > data.length * 8) fail("Image GIF compressed data is truncated.");
4703
+ let code = 0;
4704
+ for (let bit = 0; bit < bits; bit++) code |= (data[offset + bit >> 3] >> (offset + bit & 7) & 1) << bit;
4705
+ offset += bits;
4706
+ if (code === clear) {
4707
+ bits = minimum + 1;
4708
+ next = end + 1;
4709
+ previous = 0;
4710
+ continue;
4711
+ }
4712
+ if (code === end) {
4713
+ if (written !== pixels) fail("Image GIF decoded length does not match its frame dimensions.");
4714
+ return;
4715
+ }
4716
+ const length = code < clear ? 1 : code < next ? lengths[code] : code === next && previous ? previous + 1 : 0;
4717
+ if (!length) fail("Image GIF contains an invalid compression reference.");
4718
+ written += length;
4719
+ if (written > pixels) fail("Image GIF expands beyond its frame dimensions.");
4720
+ if (previous && next < 4096) {
4721
+ lengths[next++] = previous + 1;
4722
+ if (next === 1 << bits && bits < 12) bits++;
4723
+ }
4724
+ previous = length;
4725
+ }
4726
+ }
4727
+ function isImageAsset(value) {
4728
+ return !!value && typeof value === "object" && prepared.has(value);
4729
+ }
4730
+ function browserImageSource(asset) {
4731
+ return asset ? browserSources.get(asset) : void 0;
4732
+ }
4733
+ function validateStageImage(value, asset) {
4734
+ if (![value.width, value.height].every((n) => Number.isFinite(n) && n > 0)) fail("Image destination dimensions must be positive finite numbers.");
4735
+ const crop = value.crop;
4736
+ if (crop && (![crop.x, crop.y, crop.width, crop.height].every(Number.isFinite) || crop.x < 0 || crop.y < 0 || crop.width <= 0 || crop.height <= 0 || crop.x + crop.width > asset.width || crop.y + crop.height > asset.height)) {
4737
+ fail("Image crop must be a nonempty region inside the intrinsic image pixels.");
4738
+ }
4739
+ }
4740
+ function imageFromAsset(asset, options = {}) {
4741
+ if (!isImageAsset(asset)) fail("Call and await resolveImageAsset before creating an image node.");
4742
+ if (options.fit !== void 0 && options.fit !== "contain" && options.fit !== "cover") fail("Image fit must be contain or cover.");
4743
+ let crop = { ...options.crop ?? { x: 0, y: 0, width: asset.width, height: asset.height } };
4744
+ let width = options.width ?? (options.height === void 0 ? crop.width : options.height * crop.width / crop.height);
4745
+ let height = options.height ?? width * crop.height / crop.width;
4746
+ validateStageImage({ src: asset.src, width, height, crop }, asset);
4747
+ if (options.fit === "cover") {
4748
+ const ratio = width / height, sourceRatio = crop.width / crop.height;
4749
+ if (sourceRatio > ratio) {
4750
+ const next = crop.height * ratio;
4751
+ crop = { ...crop, x: crop.x + (crop.width - next) / 2, width: next };
4752
+ } else {
4753
+ const next = crop.width / ratio;
4754
+ crop = { ...crop, y: crop.y + (crop.height - next) / 2, height: next };
4755
+ }
4756
+ } else {
4757
+ const scale = Math.min(width / crop.width, height / crop.height);
4758
+ width = crop.width * scale;
4759
+ height = crop.height * scale;
4760
+ }
4761
+ const node = new Node().set("image", Object.freeze({ src: asset.src, width, height, crop: Object.freeze(crop), asset }));
4762
+ node.set("px", width / 2).set("py", height / 2);
4763
+ node.label = asset.id ?? "image";
4764
+ return node;
4765
+ }
4766
+
2807
4767
  // src/stage/display.ts
2808
4768
  var clockNow = () => clock.now;
2809
4769
  var ALONG_PIECE_LENGTH = 14;
@@ -2895,7 +4855,7 @@ function walk(node, parent, screen, alpha, ops) {
2895
4855
  const path = node.get("path");
2896
4856
  if (path && path.length > 0) emit(node, path, m, opacity, ops);
2897
4857
  const image2 = node.get("image");
2898
- if (image2) ops.push({ kind: "image", image: image2, matrix: m, alpha: opacity });
4858
+ if (image2) ops.push({ kind: "image", image: image2, matrix: m, alpha: opacity, node });
2899
4859
  if (node.rawOps) node.rawOps(m, opacity, ops);
2900
4860
  if (node.draw) {
2901
4861
  const built = node.draw(clockNow());
@@ -2988,7 +4948,11 @@ function frameToSvg(frame, options = {}) {
2988
4948
  for (const op of frame.ops) {
2989
4949
  if (op.kind === "image") {
2990
4950
  const m = op.matrix;
2991
- body.push(`<image href="${escapeAttr(op.image.src)}" width="${op.image.width}" height="${op.image.height}" transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""} preserveAspectRatio="none"/>`);
4951
+ const { image: image2 } = op, crop = image2.crop;
4952
+ if (crop && !image2.asset) throw new ImageAssetError("Cropped image SVG needs a prepared image asset.");
4953
+ const picture = `<image href="${escapeAttr(image2.src)}" width="${crop ? image2.asset.width : image2.width}" height="${crop ? image2.asset.height : image2.height}" preserveAspectRatio="none"/>`;
4954
+ const content = crop ? `<svg width="${fmt2(image2.width)}" height="${fmt2(image2.height)}" viewBox="${[crop.x, crop.y, crop.width, crop.height].map(fmt2).join(" ")}" preserveAspectRatio="none" overflow="hidden">${picture}</svg>` : picture;
4955
+ body.push(`<g transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""}>${content}</g>`);
2992
4956
  continue;
2993
4957
  }
2994
4958
  const style = op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
@@ -3055,13 +5019,16 @@ function paintFrame(ctx, frame, scale = 1, images) {
3055
5019
  }
3056
5020
  for (const op of frame.ops) {
3057
5021
  if (op.kind === "image") {
3058
- const source = images?.(op.image);
3059
- if (!source) continue;
5022
+ const source = images?.(op.image) ?? browserImageSource(op.image.asset);
5023
+ if (!source) throw new ImageAssetError("Image pixels are unavailable. Await image preparation and provide an ImageLookup outside the browser.");
3060
5024
  const m = op.matrix;
3061
5025
  ctx.save();
3062
5026
  ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
3063
5027
  ctx.globalAlpha = op.alpha;
3064
- ctx.drawImage(source, 0, 0, op.image.width, op.image.height);
5028
+ ctx.globalCompositeOperation = "source-over";
5029
+ const crop = op.image.crop;
5030
+ if (crop) ctx.drawImage(source, crop.x, crop.y, crop.width, crop.height, 0, 0, op.image.width, op.image.height);
5031
+ else ctx.drawImage(source, 0, 0, op.image.width, op.image.height);
3065
5032
  ctx.restore();
3066
5033
  continue;
3067
5034
  }
@@ -3107,10 +5074,10 @@ function paintFrame(ctx, frame, scale = 1, images) {
3107
5074
  function frameInkBounds(frame) {
3108
5075
  let result = null;
3109
5076
  for (const op of frame.ops) {
3110
- if (op.kind !== "path") continue;
3111
- const b = pathBounds(op.path);
5077
+ if (op.kind === "image" && !imageHasVisiblePixels(op.image.asset, op.image.crop)) continue;
5078
+ const b = op.kind === "image" ? imageOpBounds(op) : pathBounds(op.path);
3112
5079
  if (!b) continue;
3113
- const pad2 = op.stroke ? op.strokeWidth / 2 : 0;
5080
+ const pad2 = op.kind === "path" && op.stroke ? op.strokeWidth / 2 : 0;
3114
5081
  const next = { x: b.x - pad2, y: b.y - pad2, width: b.width + pad2 * 2, height: b.height + pad2 * 2 };
3115
5082
  if (!result) result = next;
3116
5083
  else {
@@ -3120,6 +5087,13 @@ function frameInkBounds(frame) {
3120
5087
  }
3121
5088
  return result;
3122
5089
  }
5090
+ function imageOpBounds(op) {
5091
+ const { width, height } = op.image;
5092
+ const corners = [[0, 0], [width, 0], [0, height], [width, height]].map(([x2, y2]) => apply(op.matrix, x2, y2));
5093
+ const xs = corners.map((p) => p[0]), ys = corners.map((p) => p[1]);
5094
+ const x = Math.min(...xs), y = Math.min(...ys);
5095
+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
5096
+ }
3123
5097
 
3124
5098
  // src/stage/stage.ts
3125
5099
  var ASPECTS = {
@@ -3245,12 +5219,12 @@ var Stage = class {
3245
5219
  return new Value(initial);
3246
5220
  }
3247
5221
  /** Re-run a function each frame while the node shows. It can set any property on the node. */
3248
- update(node, fn, window = {}) {
5222
+ update(node, fn, window2 = {}) {
3249
5223
  this.updaters.push({
3250
5224
  node,
3251
5225
  fn,
3252
- from: window.from ?? this.time,
3253
- to: window.to ?? Infinity
5226
+ from: window2.from ?? this.time,
5227
+ to: window2.to ?? Infinity
3254
5228
  });
3255
5229
  return node;
3256
5230
  }
@@ -3285,6 +5259,9 @@ function isSuspend(error) {
3285
5259
  return typeof error === "object" && error !== null && error.isVizmaticSuspend === true;
3286
5260
  }
3287
5261
  var CompiledFilm = class {
5262
+ allowImageNetwork;
5263
+ imageAssets = /* @__PURE__ */ new Map();
5264
+ imageLoads = /* @__PURE__ */ new Map();
3288
5265
  width;
3289
5266
  height;
3290
5267
  fps;
@@ -3302,6 +5279,7 @@ var CompiledFilm = class {
3302
5279
  captions;
3303
5280
  stage;
3304
5281
  constructor(stage, options, overrides) {
5282
+ this.allowImageNetwork = (overrides.imageNetwork ?? options.imageNetwork ?? "allow") === "allow";
3305
5283
  this.stage = stage;
3306
5284
  this.width = stage.width;
3307
5285
  this.height = stage.height;
@@ -3322,6 +5300,32 @@ var CompiledFilm = class {
3322
5300
  get frameCount() {
3323
5301
  return Math.max(1, Math.round(this.duration * this.fps));
3324
5302
  }
5303
+ async prepareImage(image2) {
5304
+ if (image2.asset) {
5305
+ if (!isImageAsset(image2.asset)) throw new ImageAssetError("Image asset was not prepared by resolveImageAsset.");
5306
+ validateStageImage(image2, image2.asset);
5307
+ return image2.asset;
5308
+ }
5309
+ let pending2 = this.imageLoads.get(image2.src);
5310
+ if (!pending2) {
5311
+ pending2 = resolveLegacyImage(image2.src, this.allowImageNetwork).then((asset2) => {
5312
+ this.imageAssets.set(image2.src, asset2);
5313
+ return asset2;
5314
+ });
5315
+ this.imageLoads.set(image2.src, pending2);
5316
+ }
5317
+ const asset = await pending2;
5318
+ validateStageImage(image2, asset);
5319
+ return asset;
5320
+ }
5321
+ /** Preload static and keyed images, including those not visible in the first frame. */
5322
+ async preloadImages() {
5323
+ for (const node of this.stage.root.all()) {
5324
+ const track = node.tracks?.get("image");
5325
+ const images = [node.base.image, track?.initial, ...track?.keys.map((key) => key.to) ?? []];
5326
+ for (const image2 of images) if (image2) await this.prepareImage(image2);
5327
+ }
5328
+ }
3325
5329
  /** The draw list at a time in seconds. May throw Suspend if a drawing needs a new asset. */
3326
5330
  frame(time) {
3327
5331
  const t = Math.max(0, Math.min(this.duration, time));
@@ -3342,7 +5346,15 @@ var CompiledFilm = class {
3342
5346
  zoom: camera.get("sx"),
3343
5347
  rotation: camera.get("rotation")
3344
5348
  }, stage.width, stage.height);
3345
- return { width: stage.width, height: stage.height, background: this.background, bloom: this.bloom, dark: stage.look.dark, ops };
5349
+ const preparedOps = ops.map((op) => {
5350
+ if (op.kind !== "image") return op;
5351
+ const asset = op.image.asset ?? this.imageAssets.get(op.image.src);
5352
+ if (!asset) throw new Suspend(this.prepareImage(op.image));
5353
+ if (!isImageAsset(asset)) throw new ImageAssetError("Image asset was not prepared by resolveImageAsset.");
5354
+ validateStageImage(op.image, asset);
5355
+ return { ...op, image: { ...op.image, src: asset.src, asset } };
5356
+ });
5357
+ return { width: stage.width, height: stage.height, background: this.background, bloom: this.bloom, dark: stage.look.dark, ops: preparedOps };
3346
5358
  } finally {
3347
5359
  clock.mode = previous.mode;
3348
5360
  clock.now = previous.now;
@@ -3366,6 +5378,7 @@ async function compileFilm(definition, overrides = {}) {
3366
5378
  clock.mode = saved.mode;
3367
5379
  clock.now = saved.now;
3368
5380
  const compiled = new CompiledFilm(stage, options, overrides);
5381
+ await compiled.preloadImages();
3369
5382
  await probe(compiled);
3370
5383
  return compiled;
3371
5384
  } catch (error) {
@@ -4339,6 +6352,12 @@ function intrinsicSize(src) {
4339
6352
  return null;
4340
6353
  }
4341
6354
  function image(src, options = {}) {
6355
+ if (typeof src !== "string") {
6356
+ const node = imageFromAsset(src, options);
6357
+ if (options.opacity !== void 0) node.opacity(options.opacity);
6358
+ return node;
6359
+ }
6360
+ if (options.crop !== void 0 || options.fit !== void 0) throw new Error("Await resolveImageAsset before using image fit or crop options.");
4342
6361
  const natural = intrinsicSize(src);
4343
6362
  let width = options.width, height = options.height;
4344
6363
  if (width === void 0 && height === void 0) {
@@ -4631,6 +6650,9 @@ var MIN_RESTING_MOMENTS = 5;
4631
6650
  var AUTO_SAMPLES = 12;
4632
6651
  var CUBIC_STEPS = 6;
4633
6652
  var CROSSING_ERROR_WIDTH = 2;
6653
+ var BLANK_ALPHA = 0.25;
6654
+ var BLANK_EDGE_SECONDS = 0.5;
6655
+ var BLANK_MIN_SECONDS = 0.2;
4634
6656
  var CROSSING_ERROR_CONTRAST = 2;
4635
6657
  var MIN_STROKE_CONTRAST = 1.6;
4636
6658
  var OPAQUE = 0.9;
@@ -4784,6 +6806,20 @@ function inspect(frame, time, zoomed, bleed) {
4784
6806
  const off = /* @__PURE__ */ new Map();
4785
6807
  let outsideMarks = 0;
4786
6808
  ops.forEach((op, order) => {
6809
+ if (op.kind === "image") {
6810
+ if (op.alpha < MIN_ALPHA || !imageHasVisiblePixels(op.image.asset, op.image.crop)) return;
6811
+ const box2 = imageOpBounds(op);
6812
+ const outside2 = box2.x < -EDGE_TOLERANCE || box2.y < -EDGE_TOLERANCE || box2.x + box2.width > width + EDGE_TOLERANCE || box2.y + box2.height > height + EDGE_TOLERANCE;
6813
+ if (outside2 && !zoomed && !bleed) findings.push({
6814
+ key: `film.off_canvas:image:${ownerKey(op.node)}`,
6815
+ code: "film.off_canvas",
6816
+ severity: "warning",
6817
+ time,
6818
+ box: box2,
6819
+ message: `Image ${JSON.stringify(op.image.asset?.id ?? op.node?.label ?? "image")} runs off the canvas.`
6820
+ });
6821
+ return;
6822
+ }
4787
6823
  if (op.kind !== "path" || op.path.length === 0) return;
4788
6824
  const glyph = isGlyph(op);
4789
6825
  const alpha = Math.max(op.fillAlpha, op.strokeAlpha);
@@ -4907,7 +6943,45 @@ function inspect(frame, time, zoomed, bleed) {
4907
6943
  }
4908
6944
  return findings;
4909
6945
  }
6946
+ function hasContent(frame, top) {
6947
+ return frame.ops.some((op) => {
6948
+ if (op.kind === "image") {
6949
+ const box2 = imageOpBounds(op);
6950
+ return op.alpha >= BLANK_ALPHA && imageHasVisiblePixels(op.image.asset, op.image.crop) && box2.y + box2.height > top && box2.y < frame.height && box2.x + box2.width > 0 && box2.x < frame.width;
6951
+ }
6952
+ const filled = op.fill !== null && op.fillAlpha >= BLANK_ALPHA;
6953
+ const stroked = op.stroke !== null && op.strokeAlpha >= BLANK_ALPHA && op.strokeWidth > 0;
6954
+ if (!filled && !stroked) return false;
6955
+ const box = pathBounds(filled ? op.path : op.strokePath);
6956
+ return box !== null && box.y + box.height > top && box.y < frame.height && box.x + box.width > 0 && box.x < frame.width;
6957
+ });
6958
+ }
4910
6959
  async function checkFilm(film2, options = {}) {
6960
+ try {
6961
+ return await inspectFilm(film2, options);
6962
+ } catch (error) {
6963
+ if (!(error instanceof ImageAssetError) && error?.name !== "ImageAssetError") throw error;
6964
+ const dimensions = isFilm(film2) ? new Stage(film2.options) : film2;
6965
+ return {
6966
+ ok: false,
6967
+ width: dimensions.width,
6968
+ height: dimensions.height,
6969
+ duration: isFilm(film2) ? 0 : film2.duration,
6970
+ sampled: [],
6971
+ diagnostics: [{
6972
+ code: "film.image_asset",
6973
+ severity: "error",
6974
+ message: error.message,
6975
+ time: 0,
6976
+ until: 0,
6977
+ box: { x: 0, y: 0, width: 0, height: 0 },
6978
+ stage: { x: 0, y: 0 }
6979
+ }],
6980
+ summary: { errors: 1, warnings: 0 }
6981
+ };
6982
+ }
6983
+ }
6984
+ async function inspectFilm(film2, options) {
4911
6985
  const compiled = isFilm(film2) ? await film2.compile(options) : film2;
4912
6986
  const times = options.times ? [...options.times] : restingMoments(compiled, options.samples ?? 0);
4913
6987
  const merged = /* @__PURE__ */ new Map();
@@ -4927,6 +7001,57 @@ async function checkFilm(film2, options = {}) {
4927
7001
  }
4928
7002
  }
4929
7003
  }
7004
+ const frameCount = options.motion ? Math.max(1, Math.round(compiled.duration * compiled.fps)) : 0;
7005
+ const step = 1 / compiled.fps;
7006
+ if (options.motion) {
7007
+ const top = options.contentTop ?? 0;
7008
+ const moving = /* @__PURE__ */ new Map();
7009
+ const blanks = [];
7010
+ for (let index = 0; index < frameCount; index++) {
7011
+ const time = index * step;
7012
+ const frame = await frameAt(compiled, time);
7013
+ for (const finding of inspect(frame, time, zoomAt(compiled, time) !== 1, compiled.bleed)) {
7014
+ if (merged.has(finding.key)) continue;
7015
+ let runs = moving.get(finding.key);
7016
+ if (!runs) moving.set(finding.key, runs = []);
7017
+ const last = runs[runs.length - 1];
7018
+ if (last && last.to === index - 1) last.to = index;
7019
+ else runs.push({ from: index, to: index, first: finding });
7020
+ }
7021
+ const edge = time < BLANK_EDGE_SECONDS || time > compiled.duration - BLANK_EDGE_SECONDS;
7022
+ if (!edge && !hasContent(frame, top)) {
7023
+ const last = blanks[blanks.length - 1];
7024
+ if (last && last.to === index - 1) last.to = index;
7025
+ else blanks.push({ from: index, to: index });
7026
+ }
7027
+ }
7028
+ const seconds = (frames) => Math.round(frames * step * 100) / 100;
7029
+ for (const [key, runs] of moving) {
7030
+ const longest = runs.reduce((best, run2) => run2.to - run2.from > best.to - best.from ? run2 : best);
7031
+ const { key: _, ...finding } = longest.first;
7032
+ merged.set(key, {
7033
+ ...finding,
7034
+ severity: "warning",
7035
+ until: longest.to * step,
7036
+ stage: { x: 0, y: 0 },
7037
+ motion: { spans: runs.length, seconds: seconds(runs.reduce((sum, run2) => sum + run2.to - run2.from + 1, 0)) }
7038
+ });
7039
+ }
7040
+ for (const run2 of blanks) {
7041
+ const length = seconds(run2.to - run2.from + 1);
7042
+ if (length < BLANK_MIN_SECONDS) continue;
7043
+ merged.set(`film.blank:${run2.from}`, {
7044
+ code: "film.blank",
7045
+ severity: "warning",
7046
+ message: `Nothing is visible${top > 0 ? ` below y=${top}` : ""} for ${length} s.`,
7047
+ time: run2.from * step,
7048
+ until: run2.to * step,
7049
+ box: { x: 0, y: top, width: compiled.width, height: compiled.height - top },
7050
+ stage: { x: 0, y: 0 },
7051
+ motion: { spans: 1, seconds: length }
7052
+ });
7053
+ }
7054
+ }
4930
7055
  const round = (value) => Math.round(value * 100) / 100;
4931
7056
  const diagnostics = [...merged.values()].map((entry) => ({
4932
7057
  ...entry,
@@ -4945,6 +7070,7 @@ async function checkFilm(film2, options = {}) {
4945
7070
  height: compiled.height,
4946
7071
  duration: compiled.duration,
4947
7072
  sampled: times.map((time) => Math.round(time * 1e3) / 1e3),
7073
+ ...options.motion ? { frames: frameCount } : {},
4948
7074
  diagnostics,
4949
7075
  summary: { errors, warnings: diagnostics.length - errors }
4950
7076
  };
@@ -5328,12 +7454,12 @@ var StreamLines = class extends Node {
5328
7454
  const buckets = Array.from({ length: colorBands * fadeBands }, () => []);
5329
7455
  for (const entry of lines) {
5330
7456
  const count = entry.points.length;
5331
- const window = Math.max(3, Math.floor(count * tail));
5332
- const travel = count + window;
7457
+ const window2 = Math.max(3, Math.floor(count * tail));
7458
+ const travel = count + window2;
5333
7459
  const head = (time * speed * entry.speedRate + entry.phase) % 1 * travel;
5334
7460
  for (let band = 0; band < fadeBands; band++) {
5335
- const from = Math.floor(head - window * (1 - band / fadeBands));
5336
- const to2 = Math.floor(head - window * (1 - (band + 1) / fadeBands));
7461
+ const from = Math.floor(head - window2 * (1 - band / fadeBands));
7462
+ const to2 = Math.floor(head - window2 * (1 - (band + 1) / fadeBands));
5337
7463
  const a = Math.max(0, from), b = Math.min(count - 1, to2);
5338
7464
  if (b - a < 1) continue;
5339
7465
  buckets[entry.color * fadeBands + band].push(polylineRing(entry.points.slice(a, b + 1)));
@@ -8185,7 +10311,7 @@ function highlightSweep(target, options = {}) {
8185
10311
  }
8186
10312
 
8187
10313
  // src/stage/svg-import.ts
8188
- function decode(value) {
10314
+ function decode2(value) {
8189
10315
  return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g, (_, code) => String.fromCodePoint(parseInt(code, 16))).replace(/&amp;/g, "&");
8190
10316
  }
8191
10317
  function parseXml(source) {
@@ -8202,12 +10328,12 @@ function parseXml(source) {
8202
10328
  } else if (opening) {
8203
10329
  const element = { name: opening.replace(/^.*:/, ""), attrs: {}, children: [], text: "" };
8204
10330
  for (const attr of (attributes ?? "").matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
8205
- element.attrs[attr[1]] = decode(attr[2] ?? attr[3] ?? "");
10331
+ element.attrs[attr[1]] = decode2(attr[2] ?? attr[3] ?? "");
8206
10332
  }
8207
10333
  top.children.push(element);
8208
10334
  if (!selfClosing) stack.push(element);
8209
10335
  } else if (content) {
8210
- top.text += decode(content);
10336
+ top.text += decode2(content);
8211
10337
  }
8212
10338
  }
8213
10339
  return root;
@@ -9745,6 +11871,7 @@ function label3d(content, position, options = {}) {
9745
11871
  Heatmap,
9746
11872
  Histogram,
9747
11873
  IDENTITY,
11874
+ ImageAssetError,
9748
11875
  InfoBox,
9749
11876
  LOOKS,
9750
11877
  Label3D,
@@ -9918,6 +12045,7 @@ function label3d(content, position, options = {}) {
9918
12045
  rect,
9919
12046
  rectPath,
9920
12047
  regularPolygon,
12048
+ resolveImageAsset,
9921
12049
  resolveLook,
9922
12050
  retime,
9923
12051
  reverseRing,