@poe-platform/safe-bash 0.1.772 → 0.1.774

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.
Files changed (45) hide show
  1. package/dist/image-ast/index.browser.js +3543 -706
  2. package/dist/image-ast/index.js +3543 -706
  3. package/dist/pdf-ast/ast.d.ts +7 -0
  4. package/dist/pdf-ast/content/evaluator.d.ts +1 -0
  5. package/dist/pdf-ast/index.js +3587 -718
  6. package/dist/pdf-ast/render/raster.d.ts +1 -0
  7. package/dist/pdf-ast/vendor/pdfjs-fonts.d.mts +36 -0
  8. package/dist/pdf-ast/vendor/pdfjs-fonts.mjs +3323 -0
  9. package/dist/safe-bash/command-chunks/{chunk-M2XU2YCK.js → chunk-4ZHDCMQX.js} +2 -2
  10. package/dist/safe-bash/command-chunks/{chunk-NBENXODJ.js → chunk-HH5QPKIN.js} +1 -1
  11. package/dist/safe-bash/command-chunks/{chunk-C4AAJTXF.js → chunk-PM63UJE6.js} +3546 -706
  12. package/dist/safe-bash/core.browser.js +101 -45
  13. package/dist/safe-bash/core.d.ts +1 -1
  14. package/dist/safe-bash/plugins/composition.d.ts +2 -0
  15. package/dist/safe-bash/plugins/composition.js +2 -1
  16. package/dist/safe-bash/shell/runtime.js +17 -9
  17. package/dist/safe-bash/shell/sync-posix-regex.d.ts +3 -0
  18. package/dist/safe-bash/shell/sync-posix-regex.js +48 -0
  19. package/dist/safe-bash-command-ffmpeg/index.js +11032 -9579
  20. package/dist/safe-bash-command-gh/index.d.ts +1 -0
  21. package/dist/safe-bash-command-gh/index.js +43 -13
  22. package/dist/safe-bash-command-gh/types.d.ts +1 -0
  23. package/dist/safe-bash-command-git/git_rust.wasm +0 -0
  24. package/dist/safe-bash-command-git/index.js +22 -15
  25. package/dist/safe-bash-command-git/wasm.generated.js +1 -1
  26. package/dist/safe-bash-command-gpg/index.js +28 -7
  27. package/dist/safe-bash-command-imagemagick/index.js +2 -2
  28. package/dist/safe-bash-command-openssl/index.js +24 -6
  29. package/dist/safe-bash-command-pandoc/command.js +3 -3
  30. package/dist/safe-bash-command-pandoc/index.js +3 -3
  31. package/dist/safe-bash-command-pdfimages/index.js +3542 -660
  32. package/dist/safe-bash-command-pdfinfo/index.js +3584 -718
  33. package/dist/safe-bash-command-pdftk/index.js +3542 -660
  34. package/dist/safe-bash-command-pdftoppm/index.js +3589 -787
  35. package/dist/safe-bash-command-pdftotext/index.js +3542 -660
  36. package/dist/safe-bash-command-qpdf/index.js +3542 -660
  37. package/dist/safe-bash-command-sips/index.js +2 -2
  38. package/dist/safe-bash-command-soffice/index.js +1 -1
  39. package/dist/safe-bash-command-ssconvert/index.js +3553 -716
  40. package/dist/safe-bash-command-ssh/index.js +124 -23
  41. package/dist/safe-bash-command-wkhtmltopdf/index.js +3581 -660
  42. package/dist/safe-bash-mcp/index.d.ts +8 -2
  43. package/dist/safe-bash-mcp/index.js +13 -6
  44. package/package.json +7 -7
  45. package/third-party/pdf-ast/THIRD_PARTY_NOTICES.md +84 -1
@@ -13652,16 +13652,16 @@ var require_JpegEmbedder = __commonJS({
13652
13652
  65486,
13653
13653
  65487
13654
13654
  ];
13655
- var ColorSpace;
13656
- (function(ColorSpace2) {
13657
- ColorSpace2["DeviceGray"] = "DeviceGray";
13658
- ColorSpace2["DeviceRGB"] = "DeviceRGB";
13659
- ColorSpace2["DeviceCMYK"] = "DeviceCMYK";
13660
- })(ColorSpace || (ColorSpace = {}));
13655
+ var ColorSpace2;
13656
+ (function(ColorSpace3) {
13657
+ ColorSpace3["DeviceGray"] = "DeviceGray";
13658
+ ColorSpace3["DeviceRGB"] = "DeviceRGB";
13659
+ ColorSpace3["DeviceCMYK"] = "DeviceCMYK";
13660
+ })(ColorSpace2 || (ColorSpace2 = {}));
13661
13661
  var ChannelToColorSpace = {
13662
- 1: ColorSpace.DeviceGray,
13663
- 3: ColorSpace.DeviceRGB,
13664
- 4: ColorSpace.DeviceCMYK
13662
+ 1: ColorSpace2.DeviceGray,
13663
+ 3: ColorSpace2.DeviceRGB,
13664
+ 4: ColorSpace2.DeviceCMYK
13665
13665
  };
13666
13666
  var JpegEmbedder = (
13667
13667
  /** @class */
@@ -13726,7 +13726,7 @@ var require_JpegEmbedder = __commonJS({
13726
13726
  //
13727
13727
  // Applying a swap here as a hedge that most bytes passing
13728
13728
  // through this method will benefit from it.
13729
- Decode: this.colorSpace === ColorSpace.DeviceCMYK ? [1, 0, 1, 0, 1, 0, 1, 0] : void 0
13729
+ Decode: this.colorSpace === ColorSpace2.DeviceCMYK ? [1, 0, 1, 0, 1, 0, 1, 0] : void 0
13730
13730
  });
13731
13731
  if (ref) {
13732
13732
  context.assign(ref, xObject);
@@ -177092,6 +177092,11 @@ var FONT_IDENTITY_MATRIX = [1e-3, 0, 0, 1e-3, 0, 0];
177092
177092
  var LINE_FACTOR = 1.35;
177093
177093
  var LINE_DESCENT_FACTOR = 0.35;
177094
177094
  var BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
177095
+ var MeshFigureType = {
177096
+ TRIANGLES: 1,
177097
+ LATTICE: 2,
177098
+ PATCH: 3
177099
+ };
177095
177100
  var VerbosityLevel = {
177096
177101
  ERRORS: 0,
177097
177102
  WARNINGS: 1,
@@ -196016,6 +196021,3308 @@ var getFontBasicMetrics = getLookupTableFactory(function(t) {
196016
196021
  xHeight: Math.NaN
196017
196022
  };
196018
196023
  });
196024
+ function resizeRgbImage(src, dest, w1, h1, w2, h2, alpha01) {
196025
+ const COMPONENTS = 3;
196026
+ alpha01 = alpha01 !== 1 ? 0 : alpha01;
196027
+ const xRatio = w1 / w2;
196028
+ const yRatio = h1 / h2;
196029
+ let newIndex = 0, oldIndex;
196030
+ const xScaled = new Uint16Array(w2);
196031
+ const w1Scanline = w1 * COMPONENTS;
196032
+ for (let i = 0; i < w2; i++) {
196033
+ xScaled[i] = Math.floor(i * xRatio) * COMPONENTS;
196034
+ }
196035
+ for (let i = 0; i < h2; i++) {
196036
+ const py = Math.floor(i * yRatio) * w1Scanline;
196037
+ for (let j = 0; j < w2; j++) {
196038
+ oldIndex = py + xScaled[j];
196039
+ dest[newIndex++] = src[oldIndex++];
196040
+ dest[newIndex++] = src[oldIndex++];
196041
+ dest[newIndex++] = src[oldIndex++];
196042
+ newIndex += alpha01;
196043
+ }
196044
+ }
196045
+ }
196046
+ function isDefaultDecodeHelper(decode3, expectedLen) {
196047
+ if (!Array.isArray(decode3)) {
196048
+ return true;
196049
+ }
196050
+ const decodeLen = decode3.length;
196051
+ if (decodeLen < expectedLen) {
196052
+ warn2("Decode map length is too short.");
196053
+ return true;
196054
+ }
196055
+ if (decodeLen > expectedLen) {
196056
+ info("Truncating too long decode map.");
196057
+ decode3.length = expectedLen;
196058
+ }
196059
+ return false;
196060
+ }
196061
+ var ColorSpace = class _ColorSpace {
196062
+ static #rgbBuf = new Uint8ClampedArray(3);
196063
+ constructor(name, numComps) {
196064
+ if ((typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) && this.constructor === _ColorSpace) {
196065
+ unreachable2("Cannot initialize ColorSpace.");
196066
+ }
196067
+ this.name = name;
196068
+ this.numComps = numComps;
196069
+ }
196070
+ /**
196071
+ * Converts the color value to the RGB color. The color components are
196072
+ * located in the src array starting from the srcOffset. Returns the array
196073
+ * of the rgb components, each value ranging from [0,255].
196074
+ */
196075
+ getRgb(src, srcOffset, output2 = new Uint8ClampedArray(3)) {
196076
+ this.getRgbItem(src, srcOffset, output2, 0);
196077
+ return output2;
196078
+ }
196079
+ getRgbHex(src, srcOffset) {
196080
+ const buffer = this.getRgb(src, srcOffset, _ColorSpace.#rgbBuf);
196081
+ return Util.makeHexColor(buffer[0], buffer[1], buffer[2]);
196082
+ }
196083
+ /**
196084
+ * Converts the color value to the RGB color, similar to the getRgb method.
196085
+ * The result placed into the dest array starting from the destOffset.
196086
+ */
196087
+ getRgbItem(src, srcOffset, dest, destOffset) {
196088
+ unreachable2("Should not call ColorSpace.getRgbItem");
196089
+ }
196090
+ /**
196091
+ * Converts the specified number of the color values to the RGB colors.
196092
+ * The colors are located in the src array starting from the srcOffset.
196093
+ * The result is placed into the dest array starting from the destOffset.
196094
+ * The src array items shall be in [0,2^bits) range, the dest array items
196095
+ * will be in [0,255] range. alpha01 indicates how many alpha components
196096
+ * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
196097
+ * array).
196098
+ */
196099
+ getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
196100
+ unreachable2("Should not call ColorSpace.getRgbBuffer");
196101
+ }
196102
+ /**
196103
+ * Converts `count` unscaled colors to RGB, starting at `destOffset`.
196104
+ * Components use the native color-space ranges expected by `getRgbItem`,
196105
+ * and each output has a `3 + alpha01` byte stride.
196106
+ * Subclasses may override this to batch expensive conversions.
196107
+ */
196108
+ getRgbItems(src, count, dest, destOffset, alpha01) {
196109
+ const { numComps } = this;
196110
+ for (let i = 0, srcOffset = 0; i < count; i++, srcOffset += numComps) {
196111
+ this.getRgbItem(src, srcOffset, dest, destOffset);
196112
+ destOffset += 3 + alpha01;
196113
+ }
196114
+ }
196115
+ /**
196116
+ * Returns true if source data will be equal the result/output data.
196117
+ */
196118
+ isPassthrough(bits) {
196119
+ return false;
196120
+ }
196121
+ /**
196122
+ * Refer to the static `ColorSpace.isDefaultDecode` method below.
196123
+ */
196124
+ isDefaultDecode(decode3, bpc) {
196125
+ return _ColorSpace.isDefaultDecode(decode3, this.numComps);
196126
+ }
196127
+ /**
196128
+ * Fills in the RGB colors in the destination buffer. alpha01 indicates
196129
+ * how many alpha components there are in the dest array; it will be either
196130
+ * 0 (RGB array) or 1 (RGBA array).
196131
+ */
196132
+ fillRgb(dest, originalWidth, originalHeight, width2, height, actualHeight, bpc, comps, alpha01) {
196133
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196134
+ assert2(
196135
+ dest instanceof Uint8ClampedArray,
196136
+ 'ColorSpace.fillRgb: Unsupported "dest" type.'
196137
+ );
196138
+ }
196139
+ const count = originalWidth * originalHeight;
196140
+ let rgbBuf = null;
196141
+ const numComponentColors = 1 << bpc;
196142
+ const needsResizing = originalHeight !== height || originalWidth !== width2;
196143
+ if (this.isPassthrough(bpc)) {
196144
+ rgbBuf = comps;
196145
+ } else if (this.numComps === 1 && count > numComponentColors && this.name !== "DeviceGray" && this.name !== "DeviceRGB") {
196146
+ const allColors = bpc <= 8 ? new Uint8Array(numComponentColors) : new Uint16Array(numComponentColors);
196147
+ for (let i = 0; i < numComponentColors; i++) {
196148
+ allColors[i] = i;
196149
+ }
196150
+ const colorMap = new Uint8ClampedArray(numComponentColors * 3);
196151
+ this.getRgbBuffer(
196152
+ allColors,
196153
+ 0,
196154
+ numComponentColors,
196155
+ colorMap,
196156
+ 0,
196157
+ bpc,
196158
+ /* alpha01 = */
196159
+ 0
196160
+ );
196161
+ if (!needsResizing) {
196162
+ let destPos = 0;
196163
+ for (let i = 0; i < count; ++i) {
196164
+ const key = comps[i] * 3;
196165
+ dest[destPos++] = colorMap[key];
196166
+ dest[destPos++] = colorMap[key + 1];
196167
+ dest[destPos++] = colorMap[key + 2];
196168
+ destPos += alpha01;
196169
+ }
196170
+ } else {
196171
+ rgbBuf = new Uint8Array(count * 3);
196172
+ let rgbPos = 0;
196173
+ for (let i = 0; i < count; ++i) {
196174
+ const key = comps[i] * 3;
196175
+ rgbBuf[rgbPos++] = colorMap[key];
196176
+ rgbBuf[rgbPos++] = colorMap[key + 1];
196177
+ rgbBuf[rgbPos++] = colorMap[key + 2];
196178
+ }
196179
+ }
196180
+ } else if (!needsResizing) {
196181
+ this.getRgbBuffer(comps, 0, width2 * actualHeight, dest, 0, bpc, alpha01);
196182
+ } else {
196183
+ rgbBuf = new Uint8ClampedArray(count * 3);
196184
+ this.getRgbBuffer(
196185
+ comps,
196186
+ 0,
196187
+ count,
196188
+ rgbBuf,
196189
+ 0,
196190
+ bpc,
196191
+ /* alpha01 = */
196192
+ 0
196193
+ );
196194
+ }
196195
+ if (rgbBuf) {
196196
+ if (needsResizing) {
196197
+ resizeRgbImage(
196198
+ rgbBuf,
196199
+ dest,
196200
+ originalWidth,
196201
+ originalHeight,
196202
+ width2,
196203
+ height,
196204
+ alpha01
196205
+ );
196206
+ } else {
196207
+ let destPos = 0, rgbPos = 0;
196208
+ for (let i = 0, ii = width2 * actualHeight; i < ii; i++) {
196209
+ dest[destPos++] = rgbBuf[rgbPos++];
196210
+ dest[destPos++] = rgbBuf[rgbPos++];
196211
+ dest[destPos++] = rgbBuf[rgbPos++];
196212
+ destPos += alpha01;
196213
+ }
196214
+ }
196215
+ }
196216
+ }
196217
+ /**
196218
+ * True if the colorspace has components in the default range of [0, 1].
196219
+ * This should be true for all colorspaces except for lab color spaces
196220
+ * which are [0,100], [-128, 127], [-128, 127].
196221
+ */
196222
+ get usesZeroToOneRange() {
196223
+ return shadow2(this, "usesZeroToOneRange", true);
196224
+ }
196225
+ /**
196226
+ * Checks if a decode map matches the default decode map for a color space.
196227
+ * This handles the general decode maps where there are two values per
196228
+ * component, e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
196229
+ * This does not handle Lab, Indexed, or Pattern decode maps since they are
196230
+ * slightly different.
196231
+ * @param {Array} decode - Decode map (usually from an image).
196232
+ * @param {number} numComps - Number of components the color space has.
196233
+ */
196234
+ static isDefaultDecode(decode3, numComps) {
196235
+ if (isDefaultDecodeHelper(decode3, numComps * 2)) {
196236
+ return true;
196237
+ }
196238
+ for (let i = 0, ii = decode3.length; i < ii; i += 2) {
196239
+ if (decode3[i] !== 0 || decode3[i + 1] !== 1) {
196240
+ return false;
196241
+ }
196242
+ }
196243
+ return true;
196244
+ }
196245
+ };
196246
+ var DeviceCmykCS = class extends ColorSpace {
196247
+ constructor() {
196248
+ super("DeviceCMYK", 4);
196249
+ }
196250
+ // The coefficients below was found using numerical analysis: the method of
196251
+ // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
196252
+ // where color_value is the tabular value from the table of sampled RGB colors
196253
+ // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
196254
+ // CMYK color conversion using the estimation below:
196255
+ // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
196256
+ #toRgb(src, srcOffset, srcScale, dest, destOffset) {
196257
+ const c4 = src[srcOffset] * srcScale;
196258
+ const m = src[srcOffset + 1] * srcScale;
196259
+ const y = src[srcOffset + 2] * srcScale;
196260
+ const k = src[srcOffset + 3] * srcScale;
196261
+ dest[destOffset] = 255 + c4 * (-4.387332384609988 * c4 + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k + -285.2331026137004) + m * (1.7149763477362134 * m - 5.6096736904047315 * y + -17.873870861415444 * k - 5.497006427196366) + y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) + k * (-21.86122147463605 * k - 189.48180835922747);
196262
+ dest[destOffset + 1] = 255 + c4 * (8.841041422036149 * c4 + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k + -79.2970844816548) + m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) + y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) + k * (-20.737325471181034 * k - 187.80453709719578);
196263
+ dest[destOffset + 2] = 255 + c4 * (0.8842522430003296 * c4 + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k + -14.183576799673286) + m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) + y * (0.03296041114873217 * y + 115.60384449646641 * k + -193.58209356861505) + k * (-22.33816807309886 * k - 180.12613974708367);
196264
+ }
196265
+ getRgbItem(src, srcOffset, dest, destOffset) {
196266
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196267
+ assert2(
196268
+ dest instanceof Uint8ClampedArray,
196269
+ 'DeviceCmykCS.getRgbItem: Unsupported "dest" type.'
196270
+ );
196271
+ }
196272
+ this.#toRgb(src, srcOffset, 1, dest, destOffset);
196273
+ }
196274
+ getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
196275
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196276
+ assert2(
196277
+ dest instanceof Uint8ClampedArray,
196278
+ 'DeviceCmykCS.getRgbBuffer: Unsupported "dest" type.'
196279
+ );
196280
+ }
196281
+ const scale2 = 1 / ((1 << bits) - 1);
196282
+ for (let i = 0; i < count; i++) {
196283
+ this.#toRgb(src, srcOffset, scale2, dest, destOffset);
196284
+ srcOffset += 4;
196285
+ destOffset += 3 + alpha01;
196286
+ }
196287
+ }
196288
+ };
196289
+ var CalGrayCS = class extends ColorSpace {
196290
+ constructor(whitePoint, blackPoint, gamma2) {
196291
+ super("CalGray", 1);
196292
+ if (!whitePoint) {
196293
+ throw new FormatError(
196294
+ "WhitePoint missing - required for color space CalGray"
196295
+ );
196296
+ }
196297
+ [this.XW, this.YW, this.ZW] = whitePoint;
196298
+ [this.XB, this.YB, this.ZB] = blackPoint || [0, 0, 0];
196299
+ this.G = gamma2 || 1;
196300
+ if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
196301
+ throw new FormatError(
196302
+ `Invalid WhitePoint components for ${this.name}, no fallback available`
196303
+ );
196304
+ }
196305
+ if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
196306
+ info(`Invalid BlackPoint for ${this.name}, falling back to default.`);
196307
+ this.XB = this.YB = this.ZB = 0;
196308
+ }
196309
+ if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
196310
+ warn2(
196311
+ `${this.name}, BlackPoint: XB: ${this.XB}, YB: ${this.YB}, ZB: ${this.ZB}, only default values are supported.`
196312
+ );
196313
+ }
196314
+ if (this.G < 1) {
196315
+ info(
196316
+ `Invalid Gamma: ${this.G} for ${this.name}, falling back to default.`
196317
+ );
196318
+ this.G = 1;
196319
+ }
196320
+ }
196321
+ #toRgb(src, srcOffset, dest, destOffset, scale2) {
196322
+ const A = src[srcOffset] * scale2;
196323
+ const AG = A ** this.G;
196324
+ const L = this.YW * AG;
196325
+ const val = Math.max(295.8 * L ** 0.3333333333333333 - 40.8, 0);
196326
+ dest[destOffset] = val;
196327
+ dest[destOffset + 1] = val;
196328
+ dest[destOffset + 2] = val;
196329
+ }
196330
+ getRgbItem(src, srcOffset, dest, destOffset) {
196331
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196332
+ assert2(
196333
+ dest instanceof Uint8ClampedArray,
196334
+ 'CalGrayCS.getRgbItem: Unsupported "dest" type.'
196335
+ );
196336
+ }
196337
+ this.#toRgb(src, srcOffset, dest, destOffset, 1);
196338
+ }
196339
+ getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
196340
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196341
+ assert2(
196342
+ dest instanceof Uint8ClampedArray,
196343
+ 'CalGrayCS.getRgbBuffer: Unsupported "dest" type.'
196344
+ );
196345
+ }
196346
+ const scale2 = 1 / ((1 << bits) - 1);
196347
+ for (let i = 0; i < count; ++i) {
196348
+ this.#toRgb(src, srcOffset, dest, destOffset, scale2);
196349
+ srcOffset += 1;
196350
+ destOffset += 3 + alpha01;
196351
+ }
196352
+ }
196353
+ };
196354
+ var CalRGBCS = class _CalRGBCS extends ColorSpace {
196355
+ // See http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html for these
196356
+ // matrices.
196357
+ // prettier-ignore
196358
+ static #BRADFORD_SCALE_MATRIX = new Float32Array([
196359
+ 0.8951,
196360
+ 0.2664,
196361
+ -0.1614,
196362
+ -0.7502,
196363
+ 1.7135,
196364
+ 0.0367,
196365
+ 0.0389,
196366
+ -0.0685,
196367
+ 1.0296
196368
+ ]);
196369
+ // prettier-ignore
196370
+ static #BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([
196371
+ 0.9869929,
196372
+ -0.1470543,
196373
+ 0.1599627,
196374
+ 0.4323053,
196375
+ 0.5183603,
196376
+ 0.0492912,
196377
+ -85287e-7,
196378
+ 0.0400428,
196379
+ 0.9684867
196380
+ ]);
196381
+ // See http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html.
196382
+ // prettier-ignore
196383
+ static #SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([
196384
+ 3.2404542,
196385
+ -1.5371385,
196386
+ -0.4985314,
196387
+ -0.969266,
196388
+ 1.8760108,
196389
+ 0.041556,
196390
+ 0.0556434,
196391
+ -0.2040259,
196392
+ 1.0572252
196393
+ ]);
196394
+ static #FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
196395
+ static #tempNormalizeMatrix = new Float32Array(3);
196396
+ static #tempConvertMatrix1 = new Float32Array(3);
196397
+ static #tempConvertMatrix2 = new Float32Array(3);
196398
+ static #DECODE_L_CONSTANT = ((8 + 16) / 116) ** 3 / 8;
196399
+ constructor(whitePoint, blackPoint, gamma2, matrix2) {
196400
+ super("CalRGB", 3);
196401
+ if (!whitePoint) {
196402
+ throw new FormatError(
196403
+ "WhitePoint missing - required for color space CalRGB"
196404
+ );
196405
+ }
196406
+ const [XW, YW, ZW] = this.whitePoint = whitePoint;
196407
+ const [XB, YB, ZB] = this.blackPoint = blackPoint || new Float32Array(3);
196408
+ [this.GR, this.GG, this.GB] = gamma2 || new Float32Array([1, 1, 1]);
196409
+ [
196410
+ this.MXA,
196411
+ this.MYA,
196412
+ this.MZA,
196413
+ this.MXB,
196414
+ this.MYB,
196415
+ this.MZB,
196416
+ this.MXC,
196417
+ this.MYC,
196418
+ this.MZC
196419
+ ] = matrix2 || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
196420
+ if (XW < 0 || ZW < 0 || YW !== 1) {
196421
+ throw new FormatError(
196422
+ `Invalid WhitePoint components for ${this.name}, no fallback available`
196423
+ );
196424
+ }
196425
+ if (XB < 0 || YB < 0 || ZB < 0) {
196426
+ info(
196427
+ `Invalid BlackPoint for ${this.name} [${XB}, ${YB}, ${ZB}], falling back to default.`
196428
+ );
196429
+ this.blackPoint = new Float32Array(3);
196430
+ }
196431
+ if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
196432
+ info(
196433
+ `Invalid Gamma [${this.GR}, ${this.GG}, ${this.GB}] for ${this.name}, falling back to default.`
196434
+ );
196435
+ this.GR = this.GG = this.GB = 1;
196436
+ }
196437
+ }
196438
+ #matrixProduct(a3, b3, result2) {
196439
+ result2[0] = a3[0] * b3[0] + a3[1] * b3[1] + a3[2] * b3[2];
196440
+ result2[1] = a3[3] * b3[0] + a3[4] * b3[1] + a3[5] * b3[2];
196441
+ result2[2] = a3[6] * b3[0] + a3[7] * b3[1] + a3[8] * b3[2];
196442
+ }
196443
+ #toFlat(sourceWhitePoint, LMS, result2) {
196444
+ result2[0] = LMS[0] * 1 / sourceWhitePoint[0];
196445
+ result2[1] = LMS[1] * 1 / sourceWhitePoint[1];
196446
+ result2[2] = LMS[2] * 1 / sourceWhitePoint[2];
196447
+ }
196448
+ #toD65(sourceWhitePoint, LMS, result2) {
196449
+ const D65X = 0.95047;
196450
+ const D65Y = 1;
196451
+ const D65Z = 1.08883;
196452
+ result2[0] = LMS[0] * D65X / sourceWhitePoint[0];
196453
+ result2[1] = LMS[1] * D65Y / sourceWhitePoint[1];
196454
+ result2[2] = LMS[2] * D65Z / sourceWhitePoint[2];
196455
+ }
196456
+ #sRGBTransferFunction(color5) {
196457
+ if (color5 <= 31308e-7) {
196458
+ return MathClamp(12.92 * color5, 0, 1);
196459
+ }
196460
+ return color5 >= 0.99554525 ? 1 : MathClamp((1 + 0.055) * color5 ** (1 / 2.4) - 0.055, 0, 1);
196461
+ }
196462
+ #decodeL(L) {
196463
+ if (L < 0) {
196464
+ return -this.#decodeL(-L);
196465
+ }
196466
+ return L > 8 ? ((L + 16) / 116) ** 3 : L * _CalRGBCS.#DECODE_L_CONSTANT;
196467
+ }
196468
+ #compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result2) {
196469
+ if (sourceBlackPoint[0] === 0 && sourceBlackPoint[1] === 0 && sourceBlackPoint[2] === 0) {
196470
+ result2[0] = XYZ_Flat[0];
196471
+ result2[1] = XYZ_Flat[1];
196472
+ result2[2] = XYZ_Flat[2];
196473
+ return;
196474
+ }
196475
+ const zeroDecodeL = this.#decodeL(0);
196476
+ const X_DST = zeroDecodeL;
196477
+ const X_SRC = this.#decodeL(sourceBlackPoint[0]);
196478
+ const Y_DST = zeroDecodeL;
196479
+ const Y_SRC = this.#decodeL(sourceBlackPoint[1]);
196480
+ const Z_DST = zeroDecodeL;
196481
+ const Z_SRC = this.#decodeL(sourceBlackPoint[2]);
196482
+ const X_Scale = (1 - X_DST) / (1 - X_SRC);
196483
+ const X_Offset = 1 - X_Scale;
196484
+ const Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
196485
+ const Y_Offset = 1 - Y_Scale;
196486
+ const Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
196487
+ const Z_Offset = 1 - Z_Scale;
196488
+ result2[0] = XYZ_Flat[0] * X_Scale + X_Offset;
196489
+ result2[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
196490
+ result2[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
196491
+ }
196492
+ #normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result2) {
196493
+ if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
196494
+ result2[0] = XYZ_In[0];
196495
+ result2[1] = XYZ_In[1];
196496
+ result2[2] = XYZ_In[2];
196497
+ return;
196498
+ }
196499
+ const LMS = result2;
196500
+ this.#matrixProduct(_CalRGBCS.#BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
196501
+ const LMS_Flat = _CalRGBCS.#tempNormalizeMatrix;
196502
+ this.#toFlat(sourceWhitePoint, LMS, LMS_Flat);
196503
+ this.#matrixProduct(
196504
+ _CalRGBCS.#BRADFORD_SCALE_INVERSE_MATRIX,
196505
+ LMS_Flat,
196506
+ result2
196507
+ );
196508
+ }
196509
+ #normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result2) {
196510
+ const LMS = result2;
196511
+ this.#matrixProduct(_CalRGBCS.#BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
196512
+ const LMS_D65 = _CalRGBCS.#tempNormalizeMatrix;
196513
+ this.#toD65(sourceWhitePoint, LMS, LMS_D65);
196514
+ this.#matrixProduct(
196515
+ _CalRGBCS.#BRADFORD_SCALE_INVERSE_MATRIX,
196516
+ LMS_D65,
196517
+ result2
196518
+ );
196519
+ }
196520
+ #toRgb(src, srcOffset, dest, destOffset, scale2) {
196521
+ const A = MathClamp(src[srcOffset] * scale2, 0, 1);
196522
+ const B = MathClamp(src[srcOffset + 1] * scale2, 0, 1);
196523
+ const C = MathClamp(src[srcOffset + 2] * scale2, 0, 1);
196524
+ const AGR = A === 1 ? 1 : A ** this.GR;
196525
+ const BGG = B === 1 ? 1 : B ** this.GG;
196526
+ const CGB = C === 1 ? 1 : C ** this.GB;
196527
+ const X = this.MXA * AGR + this.MXB * BGG + this.MXC * CGB;
196528
+ const Y = this.MYA * AGR + this.MYB * BGG + this.MYC * CGB;
196529
+ const Z = this.MZA * AGR + this.MZB * BGG + this.MZC * CGB;
196530
+ const XYZ = _CalRGBCS.#tempConvertMatrix1;
196531
+ XYZ[0] = X;
196532
+ XYZ[1] = Y;
196533
+ XYZ[2] = Z;
196534
+ const XYZ_Flat = _CalRGBCS.#tempConvertMatrix2;
196535
+ this.#normalizeWhitePointToFlat(this.whitePoint, XYZ, XYZ_Flat);
196536
+ const XYZ_Black = _CalRGBCS.#tempConvertMatrix1;
196537
+ this.#compensateBlackPoint(this.blackPoint, XYZ_Flat, XYZ_Black);
196538
+ const XYZ_D65 = _CalRGBCS.#tempConvertMatrix2;
196539
+ this.#normalizeWhitePointToD65(
196540
+ _CalRGBCS.#FLAT_WHITEPOINT_MATRIX,
196541
+ XYZ_Black,
196542
+ XYZ_D65
196543
+ );
196544
+ const SRGB = _CalRGBCS.#tempConvertMatrix1;
196545
+ this.#matrixProduct(_CalRGBCS.#SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
196546
+ dest[destOffset] = this.#sRGBTransferFunction(SRGB[0]) * 255;
196547
+ dest[destOffset + 1] = this.#sRGBTransferFunction(SRGB[1]) * 255;
196548
+ dest[destOffset + 2] = this.#sRGBTransferFunction(SRGB[2]) * 255;
196549
+ }
196550
+ getRgbItem(src, srcOffset, dest, destOffset) {
196551
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196552
+ assert2(
196553
+ dest instanceof Uint8ClampedArray,
196554
+ 'CalRGBCS.getRgbItem: Unsupported "dest" type.'
196555
+ );
196556
+ }
196557
+ this.#toRgb(src, srcOffset, dest, destOffset, 1);
196558
+ }
196559
+ getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
196560
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196561
+ assert2(
196562
+ dest instanceof Uint8ClampedArray,
196563
+ 'CalRGBCS.getRgbBuffer: Unsupported "dest" type.'
196564
+ );
196565
+ }
196566
+ const scale2 = 1 / ((1 << bits) - 1);
196567
+ for (let i = 0; i < count; ++i) {
196568
+ this.#toRgb(src, srcOffset, dest, destOffset, scale2);
196569
+ srcOffset += 3;
196570
+ destOffset += 3 + alpha01;
196571
+ }
196572
+ }
196573
+ };
196574
+ var LabCS = class extends ColorSpace {
196575
+ constructor(whitePoint, blackPoint, range3) {
196576
+ super("Lab", 3);
196577
+ if (!whitePoint) {
196578
+ throw new FormatError(
196579
+ "WhitePoint missing - required for color space Lab"
196580
+ );
196581
+ }
196582
+ [this.XW, this.YW, this.ZW] = whitePoint;
196583
+ [this.amin, this.amax, this.bmin, this.bmax] = range3 || [
196584
+ -100,
196585
+ 100,
196586
+ -100,
196587
+ 100
196588
+ ];
196589
+ [this.XB, this.YB, this.ZB] = blackPoint || [0, 0, 0];
196590
+ if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
196591
+ throw new FormatError(
196592
+ "Invalid WhitePoint components, no fallback available"
196593
+ );
196594
+ }
196595
+ if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
196596
+ info("Invalid BlackPoint, falling back to default");
196597
+ this.XB = this.YB = this.ZB = 0;
196598
+ }
196599
+ if (this.amin > this.amax || this.bmin > this.bmax) {
196600
+ info("Invalid Range, falling back to defaults");
196601
+ this.amin = -100;
196602
+ this.amax = 100;
196603
+ this.bmin = -100;
196604
+ this.bmax = 100;
196605
+ }
196606
+ }
196607
+ // Function g(x) from spec
196608
+ #fn_g(x) {
196609
+ return x >= 6 / 29 ? x ** 3 : 108 / 841 * (x - 4 / 29);
196610
+ }
196611
+ #decode(value3, high1, low2, high2) {
196612
+ return low2 + value3 * (high2 - low2) / high1;
196613
+ }
196614
+ // If decoding is needed maxVal should be 2^bits per component - 1.
196615
+ #toRgb(src, srcOffset, maxVal, dest, destOffset) {
196616
+ let Ls = src[srcOffset];
196617
+ let as = src[srcOffset + 1];
196618
+ let bs = src[srcOffset + 2];
196619
+ if (maxVal !== false) {
196620
+ Ls = this.#decode(Ls, maxVal, 0, 100);
196621
+ as = this.#decode(as, maxVal, this.amin, this.amax);
196622
+ bs = this.#decode(bs, maxVal, this.bmin, this.bmax);
196623
+ }
196624
+ if (as > this.amax) {
196625
+ as = this.amax;
196626
+ } else if (as < this.amin) {
196627
+ as = this.amin;
196628
+ }
196629
+ if (bs > this.bmax) {
196630
+ bs = this.bmax;
196631
+ } else if (bs < this.bmin) {
196632
+ bs = this.bmin;
196633
+ }
196634
+ const M = (Ls + 16) / 116;
196635
+ const L = M + as / 500;
196636
+ const N = M - bs / 200;
196637
+ const X = this.XW * this.#fn_g(L);
196638
+ const Y = this.YW * this.#fn_g(M);
196639
+ const Z = this.ZW * this.#fn_g(N);
196640
+ let r, g, b3;
196641
+ if (this.ZW < 1) {
196642
+ r = X * 3.1339 + Y * -1.617 + Z * -0.4906;
196643
+ g = X * -0.9785 + Y * 1.916 + Z * 0.0333;
196644
+ b3 = X * 0.072 + Y * -0.229 + Z * 1.4057;
196645
+ } else {
196646
+ r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
196647
+ g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
196648
+ b3 = X * 0.0557 + Y * -0.204 + Z * 1.057;
196649
+ }
196650
+ dest[destOffset] = Math.sqrt(r) * 255;
196651
+ dest[destOffset + 1] = Math.sqrt(g) * 255;
196652
+ dest[destOffset + 2] = Math.sqrt(b3) * 255;
196653
+ }
196654
+ getRgbItem(src, srcOffset, dest, destOffset) {
196655
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196656
+ assert2(
196657
+ dest instanceof Uint8ClampedArray,
196658
+ 'LabCS.getRgbItem: Unsupported "dest" type.'
196659
+ );
196660
+ }
196661
+ this.#toRgb(src, srcOffset, false, dest, destOffset);
196662
+ }
196663
+ getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
196664
+ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
196665
+ assert2(
196666
+ dest instanceof Uint8ClampedArray,
196667
+ 'LabCS.getRgbBuffer: Unsupported "dest" type.'
196668
+ );
196669
+ }
196670
+ const maxVal = (1 << bits) - 1;
196671
+ for (let i = 0; i < count; i++) {
196672
+ this.#toRgb(src, srcOffset, maxVal, dest, destOffset);
196673
+ srcOffset += 3;
196674
+ destOffset += 3 + alpha01;
196675
+ }
196676
+ }
196677
+ isDefaultDecode(decode3, bpc) {
196678
+ return true;
196679
+ }
196680
+ get usesZeroToOneRange() {
196681
+ return shadow2(this, "usesZeroToOneRange", false);
196682
+ }
196683
+ };
196684
+ var TOKEN = {
196685
+ // Structural tokens — not keyword operators
196686
+ number: 0,
196687
+ lbrace: 1,
196688
+ rbrace: 2,
196689
+ // Boolean literals
196690
+ true: 3,
196691
+ false: 4,
196692
+ // Arithmetic binary operators
196693
+ add: 5,
196694
+ sub: 6,
196695
+ mul: 7,
196696
+ div: 8,
196697
+ idiv: 9,
196698
+ mod: 10,
196699
+ exp: 11,
196700
+ // Comparison binary operators
196701
+ eq: 12,
196702
+ ne: 13,
196703
+ gt: 14,
196704
+ ge: 15,
196705
+ lt: 16,
196706
+ le: 17,
196707
+ // Bitwise / boolean binary operators
196708
+ and: 18,
196709
+ or: 19,
196710
+ xor: 20,
196711
+ bitshift: 21,
196712
+ // Unary arithmetic operators
196713
+ abs: 22,
196714
+ neg: 23,
196715
+ ceiling: 24,
196716
+ floor: 25,
196717
+ round: 26,
196718
+ truncate: 27,
196719
+ // Unary boolean / bitwise operator
196720
+ not: 28,
196721
+ // Mathematical functions — unary
196722
+ sqrt: 29,
196723
+ sin: 30,
196724
+ cos: 31,
196725
+ ln: 32,
196726
+ log: 33,
196727
+ // Mathematical function — binary
196728
+ atan: 34,
196729
+ // Type conversion operators
196730
+ cvi: 35,
196731
+ cvr: 36,
196732
+ // Stack operators
196733
+ dup: 37,
196734
+ exch: 38,
196735
+ pop: 39,
196736
+ copy: 40,
196737
+ index: 41,
196738
+ roll: 42,
196739
+ // Control flow
196740
+ if: 43,
196741
+ ifelse: 44,
196742
+ // End of input
196743
+ eof: 45,
196744
+ // Synthetic: produced by the optimizer, never emitted by the lexer.
196745
+ min: 46,
196746
+ max: 47
196747
+ };
196748
+ var Token = class {
196749
+ constructor(id, value3 = null) {
196750
+ this.id = id;
196751
+ this.value = value3;
196752
+ }
196753
+ };
196754
+ var Lexer = class _Lexer {
196755
+ // Singletons for every non-number token, built lazily on first construction.
196756
+ // Keyword operator tokens carry their name as `value`; structural tokens
196757
+ // (lbrace, rbrace, eof) carry null.
196758
+ static #singletons = null;
196759
+ static #operatorSingletons = null;
196760
+ static #initSingletons() {
196761
+ const singletons = /* @__PURE__ */ Object.create(null);
196762
+ const operatorSingletons = /* @__PURE__ */ Object.create(null);
196763
+ for (const [name, id] of Object.entries(TOKEN)) {
196764
+ if (name === "number") {
196765
+ continue;
196766
+ }
196767
+ const isOperator = id >= TOKEN.true && id <= TOKEN.ifelse;
196768
+ const token = new Token(id, isOperator ? name : null);
196769
+ singletons[name] = token;
196770
+ if (isOperator) {
196771
+ operatorSingletons[name] = token;
196772
+ }
196773
+ }
196774
+ this.#singletons = singletons;
196775
+ this.#operatorSingletons = operatorSingletons;
196776
+ }
196777
+ constructor(data3) {
196778
+ if (!_Lexer.#singletons) {
196779
+ _Lexer.#initSingletons();
196780
+ }
196781
+ this.data = data3;
196782
+ this.pos = 0;
196783
+ this.len = data3.length;
196784
+ this._numberPattern = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/iy;
196785
+ this._identifierPattern = /[a-z]+/y;
196786
+ }
196787
+ // Skip a % comment, advancing past the next \n or \r (or to EOF).
196788
+ _skipComment() {
196789
+ const lf = this.data.indexOf("\n", this.pos);
196790
+ const cr = this.data.indexOf("\r", this.pos);
196791
+ const eol = Math.min(lf < 0 ? this.len : lf, cr < 0 ? this.len : cr);
196792
+ this.pos = Math.min(eol + 1, this.len);
196793
+ }
196794
+ _getNumber() {
196795
+ this._numberPattern.lastIndex = this.pos;
196796
+ const match3 = this._numberPattern.exec(this.data);
196797
+ if (!match3) {
196798
+ return new Token(TOKEN.number, 0);
196799
+ }
196800
+ const number5 = parseFloat(match3[0]);
196801
+ if (!Number.isFinite(number5)) {
196802
+ return new Token(TOKEN.number, 0);
196803
+ }
196804
+ this.pos = this._numberPattern.lastIndex;
196805
+ return new Token(TOKEN.number, number5);
196806
+ }
196807
+ _getOperator() {
196808
+ this._identifierPattern.lastIndex = this.pos;
196809
+ const match3 = this._identifierPattern.exec(this.data);
196810
+ if (!match3) {
196811
+ return new Token(TOKEN.number, 0);
196812
+ }
196813
+ this.pos = this._identifierPattern.lastIndex;
196814
+ const op = match3[0];
196815
+ const token = _Lexer.#operatorSingletons[op];
196816
+ return token ?? new Token(TOKEN.number, 0);
196817
+ }
196818
+ // Return the next token, or Lexer.#singletons.eof at end of input.
196819
+ next() {
196820
+ while (this.pos < this.len) {
196821
+ const ch3 = this.data.charCodeAt(this.pos++);
196822
+ switch (ch3) {
196823
+ // PostScript white-space characters (PDF32000 §7.2.2)
196824
+ case 0:
196825
+ case 9:
196826
+ case 10:
196827
+ case 12:
196828
+ case 13:
196829
+ case 32:
196830
+ break;
196831
+ case 37:
196832
+ this._skipComment();
196833
+ break;
196834
+ case 123:
196835
+ return _Lexer.#singletons.lbrace;
196836
+ case 125:
196837
+ return _Lexer.#singletons.rbrace;
196838
+ case 43:
196839
+ case 45:
196840
+ this.pos--;
196841
+ return this._getNumber();
196842
+ case 46:
196843
+ this.pos--;
196844
+ return this._getNumber();
196845
+ default:
196846
+ if (ch3 >= 48 && ch3 <= 57) {
196847
+ this.pos--;
196848
+ return this._getNumber();
196849
+ }
196850
+ if (ch3 >= 97 && ch3 <= 122) {
196851
+ this.pos--;
196852
+ return this._getOperator();
196853
+ }
196854
+ return new Token(TOKEN.number, 0);
196855
+ }
196856
+ }
196857
+ return _Lexer.#singletons.eof;
196858
+ }
196859
+ };
196860
+ var PS_VALUE_TYPE = {
196861
+ numeric: 0,
196862
+ // known to be a number (f64 in Wasm)
196863
+ boolean: 1,
196864
+ // known to be a boolean (0.0 = false, 1.0 = true in f64)
196865
+ unknown: 2
196866
+ // indeterminate at compile time
196867
+ };
196868
+ var PS_NODE = {
196869
+ // Parser AST node types (produced by Parser / parsePostScriptFunction)
196870
+ program: 0,
196871
+ block: 1,
196872
+ number: 2,
196873
+ operator: 3,
196874
+ if: 4,
196875
+ ifelse: 5,
196876
+ // Tree AST node types (produced by PSStackToTree)
196877
+ arg: 6,
196878
+ const: 7,
196879
+ unary: 8,
196880
+ binary: 9,
196881
+ ternary: 10
196882
+ };
196883
+ var PsNode = class {
196884
+ constructor(type) {
196885
+ this.type = type;
196886
+ }
196887
+ };
196888
+ var PsProgram = class extends PsNode {
196889
+ constructor(body) {
196890
+ super(PS_NODE.program);
196891
+ this.body = body;
196892
+ }
196893
+ };
196894
+ var PsBlock = class extends PsNode {
196895
+ constructor(instructions) {
196896
+ super(PS_NODE.block);
196897
+ this.instructions = instructions;
196898
+ }
196899
+ };
196900
+ var PsNumber = class extends PsNode {
196901
+ /** @param {number} value */
196902
+ constructor(value3) {
196903
+ super(PS_NODE.number);
196904
+ this.value = value3;
196905
+ }
196906
+ };
196907
+ var PsOperator = class extends PsNode {
196908
+ /** @param {number} op — one of the TOKEN.* constants from lexer.js */
196909
+ constructor(op) {
196910
+ super(PS_NODE.operator);
196911
+ this.op = op;
196912
+ }
196913
+ };
196914
+ var PsIf = class extends PsNode {
196915
+ /** @param {PsBlock} then */
196916
+ constructor(then) {
196917
+ super(PS_NODE.if);
196918
+ this.then = then;
196919
+ }
196920
+ };
196921
+ var PsIfElse = class extends PsNode {
196922
+ /**
196923
+ * @param {PsBlock} then
196924
+ * @param {PsBlock} otherwise
196925
+ */
196926
+ constructor(then, otherwise) {
196927
+ super(PS_NODE.ifelse);
196928
+ this.then = then;
196929
+ this.otherwise = otherwise;
196930
+ }
196931
+ };
196932
+ var PsArgNode = class extends PsNode {
196933
+ /** @param {number} index */
196934
+ constructor(index2) {
196935
+ super(PS_NODE.arg);
196936
+ this.index = index2;
196937
+ this.valueType = PS_VALUE_TYPE.numeric;
196938
+ }
196939
+ };
196940
+ var PsConstNode = class extends PsNode {
196941
+ /** @param {number|boolean} value */
196942
+ constructor(value3) {
196943
+ super(PS_NODE.const);
196944
+ this.value = value3;
196945
+ this.valueType = typeof value3 === "boolean" ? PS_VALUE_TYPE.boolean : PS_VALUE_TYPE.numeric;
196946
+ }
196947
+ };
196948
+ var PsUnaryNode = class extends PsNode {
196949
+ /**
196950
+ * @param {number} op — TOKEN.* constant
196951
+ * @param {PsNode} operand
196952
+ * @param {number} [valueType]
196953
+ */
196954
+ constructor(op, operand, valueType = PS_VALUE_TYPE.unknown) {
196955
+ super(PS_NODE.unary);
196956
+ this.op = op;
196957
+ this.operand = operand;
196958
+ this.valueType = valueType;
196959
+ }
196960
+ };
196961
+ var PsBinaryNode = class extends PsNode {
196962
+ /**
196963
+ * @param {number} op — TOKEN.* constant
196964
+ * @param {PsNode} first — was on top of stack
196965
+ * @param {PsNode} second — was below top
196966
+ * @param {number} [valueType]
196967
+ */
196968
+ constructor(op, first, second, valueType = PS_VALUE_TYPE.unknown) {
196969
+ super(PS_NODE.binary);
196970
+ this.op = op;
196971
+ this.first = first;
196972
+ this.second = second;
196973
+ this.valueType = valueType;
196974
+ }
196975
+ };
196976
+ var PsTernaryNode = class extends PsNode {
196977
+ /**
196978
+ * @param {PsNode} cond
196979
+ * @param {PsNode} then
196980
+ * @param {PsNode} otherwise
196981
+ * @param {number} [valueType]
196982
+ */
196983
+ constructor(cond, then, otherwise, valueType = PS_VALUE_TYPE.unknown) {
196984
+ super(PS_NODE.ternary);
196985
+ this.cond = cond;
196986
+ this.then = then;
196987
+ this.otherwise = otherwise;
196988
+ this.valueType = valueType;
196989
+ }
196990
+ };
196991
+ var Parser2 = class _Parser {
196992
+ constructor(lexer) {
196993
+ this.lexer = lexer;
196994
+ this._token = null;
196995
+ }
196996
+ static _isRegularOperator(id) {
196997
+ return id >= TOKEN.true && id < TOKEN.if;
196998
+ }
196999
+ // Fetch the next token from the lexer.
197000
+ _advance() {
197001
+ this._token = this.lexer.next();
197002
+ }
197003
+ // Assert that the current token has the given id, consume it, and return it.
197004
+ _expect(id) {
197005
+ if (this._token.id !== id) {
197006
+ throw new FormatError(
197007
+ `PostScript function: expected token id ${id}, got ${this._token.id}.`
197008
+ );
197009
+ }
197010
+ const tok = this._token;
197011
+ this._advance();
197012
+ return tok;
197013
+ }
197014
+ /**
197015
+ * Parse the full Type 4 function body.
197016
+ *
197017
+ * Grammar (simplified):
197018
+ * program ::= '{' block '}'
197019
+ * block ::= instruction*
197020
+ * instruction ::= number
197021
+ * | operator (any PS_OPERATOR except if / ifelse)
197022
+ * | '{' block '}' 'if'
197023
+ * | '{' block '}' '{' block '}' 'ifelse'
197024
+ * @returns {PsProgram}
197025
+ */
197026
+ parse() {
197027
+ this._advance();
197028
+ this._expect(TOKEN.lbrace);
197029
+ const block2 = this._parseBlock();
197030
+ this._expect(TOKEN.rbrace);
197031
+ if (this._token.id !== TOKEN.eof) {
197032
+ warn2("PostScript function: unexpected content after closing brace.");
197033
+ }
197034
+ return new PsProgram(block2);
197035
+ }
197036
+ _parseBlock() {
197037
+ const instructions = [];
197038
+ while (true) {
197039
+ const tok = this._token;
197040
+ switch (tok.id) {
197041
+ case TOKEN.number:
197042
+ instructions.push(new PsNumber(tok.value));
197043
+ this._advance();
197044
+ break;
197045
+ case TOKEN.lbrace: {
197046
+ this._advance();
197047
+ const thenBlock = this._parseBlock();
197048
+ this._expect(TOKEN.rbrace);
197049
+ if (this._token.id === TOKEN.if) {
197050
+ this._advance();
197051
+ instructions.push(new PsIf(thenBlock));
197052
+ } else if (this._token.id === TOKEN.lbrace) {
197053
+ this._advance();
197054
+ const elseBlock = this._parseBlock();
197055
+ this._expect(TOKEN.rbrace);
197056
+ this._expect(TOKEN.ifelse);
197057
+ instructions.push(new PsIfElse(thenBlock, elseBlock));
197058
+ } else {
197059
+ throw new FormatError(
197060
+ "PostScript function: a procedure block must be followed by 'if' or '{\u2026} ifelse'."
197061
+ );
197062
+ }
197063
+ break;
197064
+ }
197065
+ case TOKEN.rbrace:
197066
+ case TOKEN.eof:
197067
+ return new PsBlock(instructions);
197068
+ case TOKEN.if:
197069
+ case TOKEN.ifelse:
197070
+ throw new FormatError(
197071
+ `PostScript function: unexpected '${tok.value}' operator.`
197072
+ );
197073
+ default:
197074
+ if (_Parser._isRegularOperator(tok.id)) {
197075
+ instructions.push(new PsOperator(tok.id));
197076
+ this._advance();
197077
+ break;
197078
+ }
197079
+ throw new FormatError(
197080
+ `PostScript function: unexpected token id ${tok.id}.`
197081
+ );
197082
+ }
197083
+ }
197084
+ }
197085
+ };
197086
+ function parsePostScriptFunction(source) {
197087
+ return new Parser2(new Lexer(source)).parse();
197088
+ }
197089
+ function _nodesEqual(a3, b3) {
197090
+ if (a3 === b3) {
197091
+ return true;
197092
+ }
197093
+ if (a3.type !== b3.type) {
197094
+ return false;
197095
+ }
197096
+ switch (a3.type) {
197097
+ case PS_NODE.arg:
197098
+ return a3.index === b3.index;
197099
+ case PS_NODE.const:
197100
+ return a3.value === b3.value;
197101
+ case PS_NODE.unary:
197102
+ return a3.op === b3.op && _nodesEqual(a3.operand, b3.operand);
197103
+ case PS_NODE.binary:
197104
+ return a3.op === b3.op && _nodesEqual(a3.first, b3.first) && _nodesEqual(a3.second, b3.second);
197105
+ case PS_NODE.ternary:
197106
+ return _nodesEqual(a3.cond, b3.cond) && _nodesEqual(a3.then, b3.then) && _nodesEqual(a3.otherwise, b3.otherwise);
197107
+ default:
197108
+ return false;
197109
+ }
197110
+ }
197111
+ function _evalBinaryConst(op, a3, b3) {
197112
+ switch (op) {
197113
+ case TOKEN.add:
197114
+ return a3 + b3;
197115
+ case TOKEN.sub:
197116
+ return a3 - b3;
197117
+ case TOKEN.mul:
197118
+ return a3 * b3;
197119
+ case TOKEN.div:
197120
+ return b3 !== 0 ? a3 / b3 : 0;
197121
+ // div by zero → 0
197122
+ case TOKEN.idiv:
197123
+ return b3 !== 0 ? Math.trunc(a3 / b3) : 0;
197124
+ // div by zero → 0
197125
+ case TOKEN.mod:
197126
+ return b3 !== 0 ? a3 - Math.trunc(a3 / b3) * b3 : 0;
197127
+ // div by zero → 0
197128
+ case TOKEN.exp: {
197129
+ const r = a3 ** b3;
197130
+ return Number.isFinite(r) ? r : void 0;
197131
+ }
197132
+ case TOKEN.atan: {
197133
+ let deg = Math.atan2(a3, b3) * (180 / Math.PI);
197134
+ if (deg < 0) {
197135
+ deg += 360;
197136
+ }
197137
+ return deg;
197138
+ }
197139
+ case TOKEN.eq:
197140
+ return a3 === b3;
197141
+ case TOKEN.ne:
197142
+ return a3 !== b3;
197143
+ case TOKEN.gt:
197144
+ return a3 > b3;
197145
+ case TOKEN.ge:
197146
+ return a3 >= b3;
197147
+ case TOKEN.lt:
197148
+ return a3 < b3;
197149
+ case TOKEN.le:
197150
+ return a3 <= b3;
197151
+ case TOKEN.and:
197152
+ return typeof a3 === "boolean" ? a3 && b3 : a3 & b3 | 0;
197153
+ case TOKEN.or:
197154
+ return typeof a3 === "boolean" ? a3 || b3 : a3 | b3 | 0;
197155
+ case TOKEN.xor:
197156
+ return typeof a3 === "boolean" ? a3 !== b3 : a3 ^ b3 | 0;
197157
+ case TOKEN.bitshift:
197158
+ return b3 >= 0 ? a3 << b3 | 0 : a3 >> -b3 | 0;
197159
+ case TOKEN.min:
197160
+ return Math.min(a3, b3);
197161
+ case TOKEN.max:
197162
+ return Math.max(a3, b3);
197163
+ default:
197164
+ return void 0;
197165
+ }
197166
+ }
197167
+ function _evalUnaryConst(op, v) {
197168
+ switch (op) {
197169
+ case TOKEN.abs:
197170
+ return Math.abs(v);
197171
+ case TOKEN.neg:
197172
+ return -v;
197173
+ case TOKEN.ceiling:
197174
+ return Math.ceil(v);
197175
+ case TOKEN.floor:
197176
+ return Math.floor(v);
197177
+ case TOKEN.round:
197178
+ return Math.round(v);
197179
+ case TOKEN.truncate:
197180
+ return Math.trunc(v);
197181
+ case TOKEN.sqrt: {
197182
+ const r = Math.sqrt(v);
197183
+ return Number.isFinite(r) ? r : void 0;
197184
+ }
197185
+ case TOKEN.sin:
197186
+ return Math.sin(v % 360 * Math.PI / 180);
197187
+ case TOKEN.cos:
197188
+ return Math.cos(v % 360 * Math.PI / 180);
197189
+ case TOKEN.ln: {
197190
+ const r = Math.log(v);
197191
+ return Number.isFinite(r) ? r : void 0;
197192
+ }
197193
+ case TOKEN.log: {
197194
+ const r = Math.log10(v);
197195
+ return Number.isFinite(r) ? r : void 0;
197196
+ }
197197
+ case TOKEN.cvi:
197198
+ return Math.trunc(v);
197199
+ case TOKEN.cvr:
197200
+ return v;
197201
+ case TOKEN.not:
197202
+ return typeof v === "boolean" ? !v : ~v;
197203
+ default:
197204
+ return void 0;
197205
+ }
197206
+ }
197207
+ var MAX_STACK_SIZE = 100;
197208
+ function _unaryValueType(op, operandType) {
197209
+ return op === TOKEN.not ? operandType : PS_VALUE_TYPE.numeric;
197210
+ }
197211
+ function _binaryValueType(op, firstType, secondType) {
197212
+ switch (op) {
197213
+ // Comparison operators always produce a boolean.
197214
+ case TOKEN.eq:
197215
+ case TOKEN.ne:
197216
+ case TOKEN.gt:
197217
+ case TOKEN.ge:
197218
+ case TOKEN.lt:
197219
+ case TOKEN.le:
197220
+ return PS_VALUE_TYPE.boolean;
197221
+ // and / or / xor preserve the type when both operands are the same known
197222
+ // type (both boolean or both numeric); otherwise the type is unknown.
197223
+ case TOKEN.and:
197224
+ case TOKEN.or:
197225
+ case TOKEN.xor:
197226
+ return firstType === secondType && firstType !== PS_VALUE_TYPE.unknown ? firstType : PS_VALUE_TYPE.unknown;
197227
+ // All arithmetic / bitshift operators produce a numeric result.
197228
+ default:
197229
+ return PS_VALUE_TYPE.numeric;
197230
+ }
197231
+ }
197232
+ var PSStackToTree = class _PSStackToTree {
197233
+ static #binaryOps = null;
197234
+ static #unaryOps = null;
197235
+ static #idempotentUnary = null;
197236
+ static #negatedComparison = null;
197237
+ static #init() {
197238
+ this.#binaryOps = /* @__PURE__ */ new Set([
197239
+ TOKEN.add,
197240
+ TOKEN.sub,
197241
+ TOKEN.mul,
197242
+ TOKEN.div,
197243
+ TOKEN.idiv,
197244
+ TOKEN.mod,
197245
+ TOKEN.exp,
197246
+ TOKEN.atan,
197247
+ TOKEN.eq,
197248
+ TOKEN.ne,
197249
+ TOKEN.gt,
197250
+ TOKEN.ge,
197251
+ TOKEN.lt,
197252
+ TOKEN.le,
197253
+ TOKEN.and,
197254
+ TOKEN.or,
197255
+ TOKEN.xor,
197256
+ TOKEN.bitshift
197257
+ ]);
197258
+ this.#unaryOps = /* @__PURE__ */ new Set([
197259
+ TOKEN.abs,
197260
+ TOKEN.neg,
197261
+ TOKEN.ceiling,
197262
+ TOKEN.floor,
197263
+ TOKEN.round,
197264
+ TOKEN.truncate,
197265
+ TOKEN.sqrt,
197266
+ TOKEN.sin,
197267
+ TOKEN.cos,
197268
+ TOKEN.ln,
197269
+ TOKEN.log,
197270
+ TOKEN.cvi,
197271
+ TOKEN.cvr,
197272
+ TOKEN.not
197273
+ ]);
197274
+ this.#idempotentUnary = /* @__PURE__ */ new Set([
197275
+ TOKEN.abs,
197276
+ TOKEN.ceiling,
197277
+ TOKEN.cvi,
197278
+ TOKEN.cvr,
197279
+ TOKEN.floor,
197280
+ TOKEN.round,
197281
+ TOKEN.truncate
197282
+ ]);
197283
+ this.#negatedComparison = /* @__PURE__ */ new Map([
197284
+ [TOKEN.eq, TOKEN.ne],
197285
+ [TOKEN.ne, TOKEN.eq],
197286
+ [TOKEN.lt, TOKEN.ge],
197287
+ [TOKEN.le, TOKEN.gt],
197288
+ [TOKEN.gt, TOKEN.le],
197289
+ [TOKEN.ge, TOKEN.lt]
197290
+ ]);
197291
+ }
197292
+ /**
197293
+ * @param {PsProgram} program
197294
+ * @param {number} numInputs — number of domain values placed on the stack
197295
+ * before the program runs (i.e. the length of the domain array / 2).
197296
+ * @returns {Array<PsNode>} — one tree node per output value.
197297
+ */
197298
+ evaluate(program, numInputs) {
197299
+ if (!_PSStackToTree.#binaryOps) {
197300
+ _PSStackToTree.#init();
197301
+ }
197302
+ this._failed = false;
197303
+ if (numInputs > MAX_STACK_SIZE) {
197304
+ return null;
197305
+ }
197306
+ const stack = [];
197307
+ for (let i = 0; i < numInputs; i++) {
197308
+ stack.push(new PsArgNode(i));
197309
+ }
197310
+ this._evalBlock(program.body, stack);
197311
+ if (this._failed) {
197312
+ return null;
197313
+ }
197314
+ _PSStackToTree.#markShared(stack);
197315
+ return stack;
197316
+ }
197317
+ // Set node.shared / sharedCount on non-atomic nodes referenced more than
197318
+ // once. arg/const are excluded — they are cheap to re-emit inline.
197319
+ static #markShared(outputs) {
197320
+ const refCount = /* @__PURE__ */ new Map();
197321
+ const visit = (node3) => {
197322
+ if (!node3 || node3.type === PS_NODE.arg || node3.type === PS_NODE.const) {
197323
+ return;
197324
+ }
197325
+ const prev = refCount.get(node3) ?? 0;
197326
+ refCount.set(node3, prev + 1);
197327
+ if (prev > 0) {
197328
+ return;
197329
+ }
197330
+ switch (node3.type) {
197331
+ case PS_NODE.unary:
197332
+ visit(node3.operand);
197333
+ break;
197334
+ case PS_NODE.binary:
197335
+ visit(node3.first);
197336
+ visit(node3.second);
197337
+ break;
197338
+ case PS_NODE.ternary:
197339
+ visit(node3.cond);
197340
+ visit(node3.then);
197341
+ visit(node3.otherwise);
197342
+ break;
197343
+ }
197344
+ };
197345
+ for (const output2 of outputs) {
197346
+ visit(output2);
197347
+ }
197348
+ for (const [node3, count] of refCount) {
197349
+ if (count > 1) {
197350
+ node3.shared = true;
197351
+ node3.sharedCount = count;
197352
+ }
197353
+ }
197354
+ }
197355
+ _evalBlock(block2, stack) {
197356
+ this._evalBlockFrom(block2.instructions, 0, stack);
197357
+ }
197358
+ /**
197359
+ * Core evaluation loop. Processes `instructions[startIdx…]` in order,
197360
+ * mutating `stack` as each instruction executes.
197361
+ *
197362
+ * When a `{ body } if` instruction grows the stack (the PostScript "early
197363
+ * exit / guard" idiom), the remaining instructions in the current array are
197364
+ * evaluated on **both** the true-branch stack and the false-branch stack,
197365
+ * then the two results are merged into PsTernaryNodes. This handles
197366
+ * patterns like:
197367
+ *
197368
+ * cond { pop R G B sentinel } if
197369
+ * … more guards …
197370
+ * sentinel 0 gt { defaultR defaultG defaultB } if
197371
+ */
197372
+ _evalBlockFrom(instructions, startIdx, stack) {
197373
+ for (let idx = startIdx; idx < instructions.length; idx++) {
197374
+ if (this._failed) {
197375
+ break;
197376
+ }
197377
+ const instr = instructions[idx];
197378
+ switch (instr.type) {
197379
+ case PS_NODE.number:
197380
+ stack.push(new PsConstNode(instr.value));
197381
+ if (stack.length > MAX_STACK_SIZE) {
197382
+ this._failed = true;
197383
+ }
197384
+ break;
197385
+ case PS_NODE.operator:
197386
+ this._evalOp(instr.op, stack);
197387
+ break;
197388
+ case PS_NODE.if: {
197389
+ if (stack.length < 1) {
197390
+ this._failed = true;
197391
+ break;
197392
+ }
197393
+ const cond = stack.pop();
197394
+ const saved = stack.slice();
197395
+ this._evalBlock(instr.then, stack);
197396
+ if (this._failed) {
197397
+ break;
197398
+ }
197399
+ if (stack.length === saved.length) {
197400
+ for (let i = 0; i < stack.length; i++) {
197401
+ if (stack[i] !== saved[i]) {
197402
+ stack[i] = this._makeTernary(cond, stack[i], saved[i]);
197403
+ }
197404
+ }
197405
+ } else if (stack.length > saved.length) {
197406
+ if (cond.type === PS_NODE.const) {
197407
+ if (!cond.value) {
197408
+ stack.length = 0;
197409
+ stack.push(...saved);
197410
+ }
197411
+ break;
197412
+ }
197413
+ const trueStack = stack.slice();
197414
+ this._evalBlockFrom(instructions, idx + 1, trueStack);
197415
+ if (this._failed) {
197416
+ break;
197417
+ }
197418
+ const falseStack = saved;
197419
+ this._evalBlockFrom(instructions, idx + 1, falseStack);
197420
+ if (this._failed) {
197421
+ break;
197422
+ }
197423
+ if (trueStack.length !== falseStack.length) {
197424
+ const zero222 = new PsConstNode(0);
197425
+ while (trueStack.length < falseStack.length) {
197426
+ trueStack.push(zero222);
197427
+ }
197428
+ while (falseStack.length < trueStack.length) {
197429
+ falseStack.push(zero222);
197430
+ }
197431
+ }
197432
+ stack.length = 0;
197433
+ for (let i = 0; i < trueStack.length; i++) {
197434
+ stack.push(this._makeTernary(cond, trueStack[i], falseStack[i]));
197435
+ }
197436
+ return;
197437
+ } else {
197438
+ this._failed = true;
197439
+ }
197440
+ break;
197441
+ }
197442
+ case PS_NODE.ifelse: {
197443
+ if (stack.length < 1) {
197444
+ this._failed = true;
197445
+ break;
197446
+ }
197447
+ const cond = stack.pop();
197448
+ const snapshot = stack.slice();
197449
+ const thenStack = snapshot.slice();
197450
+ this._evalBlock(instr.then, thenStack);
197451
+ if (this._failed) {
197452
+ break;
197453
+ }
197454
+ const elseStack = snapshot.slice();
197455
+ this._evalBlock(instr.otherwise, elseStack);
197456
+ if (this._failed) {
197457
+ break;
197458
+ }
197459
+ if (thenStack.length !== elseStack.length) {
197460
+ const zero222 = new PsConstNode(0);
197461
+ while (thenStack.length < elseStack.length) {
197462
+ thenStack.push(zero222);
197463
+ }
197464
+ while (elseStack.length < thenStack.length) {
197465
+ elseStack.push(zero222);
197466
+ }
197467
+ }
197468
+ stack.length = 0;
197469
+ for (let i = 0; i < thenStack.length; i++) {
197470
+ stack.push(this._makeTernary(cond, thenStack[i], elseStack[i]));
197471
+ }
197472
+ break;
197473
+ }
197474
+ }
197475
+ }
197476
+ }
197477
+ _evalOp(op, stack) {
197478
+ if (_PSStackToTree.#binaryOps.has(op)) {
197479
+ if (stack.length < 2) {
197480
+ this._failed = true;
197481
+ return;
197482
+ }
197483
+ const first = stack.pop();
197484
+ const second = stack.pop();
197485
+ stack.push(this._makeBinary(op, first, second));
197486
+ return;
197487
+ }
197488
+ if (_PSStackToTree.#unaryOps.has(op)) {
197489
+ if (stack.length < 1) {
197490
+ this._failed = true;
197491
+ return;
197492
+ }
197493
+ stack.push(this._makeUnary(op, stack.pop()));
197494
+ return;
197495
+ }
197496
+ switch (op) {
197497
+ case TOKEN.true:
197498
+ stack.push(new PsConstNode(true));
197499
+ if (stack.length > MAX_STACK_SIZE) {
197500
+ this._failed = true;
197501
+ }
197502
+ break;
197503
+ case TOKEN.false:
197504
+ stack.push(new PsConstNode(false));
197505
+ if (stack.length > MAX_STACK_SIZE) {
197506
+ this._failed = true;
197507
+ }
197508
+ break;
197509
+ case TOKEN.dup:
197510
+ if (stack.length < 1) {
197511
+ this._failed = true;
197512
+ break;
197513
+ }
197514
+ stack.push(stack.at(-1));
197515
+ if (stack.length > MAX_STACK_SIZE) {
197516
+ this._failed = true;
197517
+ }
197518
+ break;
197519
+ case TOKEN.exch: {
197520
+ if (stack.length < 2) {
197521
+ this._failed = true;
197522
+ break;
197523
+ }
197524
+ const a3 = stack.pop();
197525
+ const b3 = stack.pop();
197526
+ stack.push(a3, b3);
197527
+ break;
197528
+ }
197529
+ case TOKEN.pop:
197530
+ if (stack.length < 1) {
197531
+ this._failed = true;
197532
+ break;
197533
+ }
197534
+ stack.pop();
197535
+ break;
197536
+ case TOKEN.copy: {
197537
+ if (stack.length < 1) {
197538
+ this._failed = true;
197539
+ break;
197540
+ }
197541
+ const nNode = stack.pop();
197542
+ if (nNode.type === PS_NODE.const) {
197543
+ const n = nNode.value | 0;
197544
+ if (n === 0) {
197545
+ } else if (n < 0 || n > stack.length) {
197546
+ this._failed = true;
197547
+ } else {
197548
+ stack.push(...stack.slice(-n));
197549
+ if (stack.length > MAX_STACK_SIZE) {
197550
+ this._failed = true;
197551
+ }
197552
+ }
197553
+ } else {
197554
+ this._failed = true;
197555
+ }
197556
+ break;
197557
+ }
197558
+ case TOKEN.index: {
197559
+ if (stack.length < 1) {
197560
+ this._failed = true;
197561
+ break;
197562
+ }
197563
+ const nNode = stack.pop();
197564
+ if (nNode.type === PS_NODE.const) {
197565
+ const n = nNode.value | 0;
197566
+ if (n < 0 || n >= stack.length) {
197567
+ this._failed = true;
197568
+ } else {
197569
+ stack.push(stack.at(-n - 1));
197570
+ }
197571
+ } else {
197572
+ this._failed = true;
197573
+ }
197574
+ break;
197575
+ }
197576
+ case TOKEN.roll: {
197577
+ if (stack.length < 2) {
197578
+ this._failed = true;
197579
+ break;
197580
+ }
197581
+ const jNode = stack.pop();
197582
+ const nNode = stack.pop();
197583
+ if (nNode.type === PS_NODE.const && jNode.type === PS_NODE.const) {
197584
+ const n = nNode.value | 0;
197585
+ if (n === 0) {
197586
+ } else if (n < 0 || n > stack.length) {
197587
+ this._failed = true;
197588
+ } else {
197589
+ const j = ((jNode.value | 0) % n + n) % n;
197590
+ if (j > 0) {
197591
+ const slice = stack.splice(-n, n);
197592
+ stack.push(...slice.slice(n - j), ...slice.slice(0, n - j));
197593
+ }
197594
+ }
197595
+ } else {
197596
+ this._failed = true;
197597
+ }
197598
+ break;
197599
+ }
197600
+ default:
197601
+ this._failed = true;
197602
+ break;
197603
+ }
197604
+ }
197605
+ /**
197606
+ * Create a binary tree node, applying optimizations eagerly:
197607
+ *
197608
+ * 1. Constant folding — both operands are PsConstNode → fold to PsConstNode.
197609
+ * 2. Reflexive simplifications — x−x→0, x xor x→0, x eq x→true, etc.
197610
+ * 3. Algebraic simplifications with one known operand — identity elements
197611
+ * (x+0→x, x*1→x, …), absorbing elements (x*0→0, x and false→false, …),
197612
+ * and strength reductions (x*-1→neg(x), x^0.5→sqrt(x), x^2→x*x, …).
197613
+ *
197614
+ * Recall: `first` was on top of the stack (right operand for non-commutative
197615
+ * ops), `second` was below (left operand). So `a b sub` → second=a, first=b
197616
+ * → a − b.
197617
+ */
197618
+ _makeBinary(op, first, second) {
197619
+ if (first.type === PS_NODE.const && second.type === PS_NODE.const) {
197620
+ const v = _evalBinaryConst(op, second.value, first.value);
197621
+ if (v !== void 0) {
197622
+ return new PsConstNode(v);
197623
+ }
197624
+ }
197625
+ if (_nodesEqual(first, second)) {
197626
+ switch (op) {
197627
+ case TOKEN.sub:
197628
+ return new PsConstNode(0);
197629
+ // x − x → 0
197630
+ case TOKEN.xor:
197631
+ return new PsConstNode(
197632
+ /* eslint-disable unicorn/prefer-logical-operator-over-ternary */
197633
+ first.valueType === PS_VALUE_TYPE.boolean ? false : 0
197634
+ /* eslint-enable unicorn/prefer-logical-operator-over-ternary */
197635
+ );
197636
+ // TOKEN.mod, TOKEN.div, TOKEN.idiv are NOT simplified here:
197637
+ // x op x is undefined when x = 0, so we cannot fold without knowing
197638
+ // that x is non-zero.
197639
+ case TOKEN.and:
197640
+ case TOKEN.or:
197641
+ return first;
197642
+ // x and x → x; x or x → x
197643
+ case TOKEN.min:
197644
+ case TOKEN.max:
197645
+ return first;
197646
+ // min(x,x) → x; max(x,x) → x
197647
+ case TOKEN.eq:
197648
+ case TOKEN.ge:
197649
+ case TOKEN.le:
197650
+ return new PsConstNode(true);
197651
+ case TOKEN.ne:
197652
+ case TOKEN.gt:
197653
+ case TOKEN.lt:
197654
+ return new PsConstNode(false);
197655
+ }
197656
+ }
197657
+ if (first.type === PS_NODE.const) {
197658
+ const b3 = first.value;
197659
+ switch (op) {
197660
+ case TOKEN.add:
197661
+ if (b3 === 0) {
197662
+ return second;
197663
+ }
197664
+ break;
197665
+ case TOKEN.sub:
197666
+ if (b3 === 0) {
197667
+ return second;
197668
+ }
197669
+ break;
197670
+ case TOKEN.mul:
197671
+ if (b3 === 1) {
197672
+ return second;
197673
+ }
197674
+ if (b3 === 0) {
197675
+ return first;
197676
+ }
197677
+ if (b3 === -1) {
197678
+ return this._makeUnary(TOKEN.neg, second);
197679
+ }
197680
+ break;
197681
+ case TOKEN.div:
197682
+ if (b3 !== 0) {
197683
+ return this._makeBinary(TOKEN.mul, new PsConstNode(1 / b3), second);
197684
+ }
197685
+ break;
197686
+ case TOKEN.idiv:
197687
+ if (b3 === 1) {
197688
+ return second;
197689
+ }
197690
+ break;
197691
+ case TOKEN.exp:
197692
+ if (b3 === 1) {
197693
+ return second;
197694
+ }
197695
+ if (b3 === -1) {
197696
+ return this._makeBinary(TOKEN.div, second, new PsConstNode(1));
197697
+ }
197698
+ if (b3 === 0.5) {
197699
+ return this._makeUnary(TOKEN.sqrt, second);
197700
+ }
197701
+ if (b3 === 0.25) {
197702
+ const sqrtOnce = this._makeUnary(TOKEN.sqrt, second);
197703
+ return this._makeUnary(TOKEN.sqrt, sqrtOnce);
197704
+ }
197705
+ if (b3 === 2) {
197706
+ return this._makeBinary(TOKEN.mul, second, second);
197707
+ }
197708
+ if (b3 === 3) {
197709
+ return this._makeBinary(
197710
+ TOKEN.mul,
197711
+ this._makeBinary(TOKEN.mul, second, second),
197712
+ second
197713
+ );
197714
+ }
197715
+ if (b3 === 4) {
197716
+ const square2 = this._makeBinary(TOKEN.mul, second, second);
197717
+ return this._makeBinary(TOKEN.mul, square2, square2);
197718
+ }
197719
+ if (b3 === 0) {
197720
+ return new PsConstNode(1);
197721
+ }
197722
+ break;
197723
+ case TOKEN.and:
197724
+ if (b3 === true) {
197725
+ return second;
197726
+ }
197727
+ if (b3 === false) {
197728
+ return first;
197729
+ }
197730
+ break;
197731
+ case TOKEN.or:
197732
+ if (b3 === false) {
197733
+ return second;
197734
+ }
197735
+ if (b3 === true) {
197736
+ return first;
197737
+ }
197738
+ break;
197739
+ case TOKEN.min:
197740
+ if (second.type === PS_NODE.binary && second.op === TOKEN.max && second.first.type === PS_NODE.const && second.first.value >= b3) {
197741
+ return first;
197742
+ }
197743
+ break;
197744
+ case TOKEN.max:
197745
+ if (second.type === PS_NODE.binary && second.op === TOKEN.min && second.first.type === PS_NODE.const && second.first.value <= b3) {
197746
+ return first;
197747
+ }
197748
+ break;
197749
+ }
197750
+ }
197751
+ if (second.type === PS_NODE.const) {
197752
+ const a3 = second.value;
197753
+ switch (op) {
197754
+ case TOKEN.add:
197755
+ if (a3 === 0) {
197756
+ return first;
197757
+ }
197758
+ break;
197759
+ case TOKEN.sub:
197760
+ if (a3 === 0) {
197761
+ return this._makeUnary(TOKEN.neg, first);
197762
+ }
197763
+ break;
197764
+ case TOKEN.mul:
197765
+ if (a3 === 1) {
197766
+ return first;
197767
+ }
197768
+ if (a3 === 0) {
197769
+ return second;
197770
+ }
197771
+ if (a3 === -1) {
197772
+ return this._makeUnary(TOKEN.neg, first);
197773
+ }
197774
+ break;
197775
+ case TOKEN.and:
197776
+ if (a3 === true) {
197777
+ return first;
197778
+ }
197779
+ if (a3 === false) {
197780
+ return second;
197781
+ }
197782
+ break;
197783
+ case TOKEN.or:
197784
+ if (a3 === false) {
197785
+ return first;
197786
+ }
197787
+ if (a3 === true) {
197788
+ return second;
197789
+ }
197790
+ break;
197791
+ }
197792
+ }
197793
+ return new PsBinaryNode(
197794
+ op,
197795
+ first,
197796
+ second,
197797
+ _binaryValueType(op, first.valueType, second.valueType)
197798
+ );
197799
+ }
197800
+ /**
197801
+ * Create a unary tree node, applying optimizations eagerly:
197802
+ *
197803
+ * 1. Constant folding.
197804
+ * 2. not(comparison) → negated comparison: not(a eq b) → a ne b, etc.
197805
+ * 3. neg(a − b) → b − a.
197806
+ * 4. Double-negation: neg(neg(x)) → x, not(not(x)) → x.
197807
+ * 5. abs(neg(x)) → abs(x).
197808
+ * 6. Idempotent: f(f(x)) → f(x) for abs, ceiling, floor, round, etc.
197809
+ */
197810
+ _makeUnary(op, operand) {
197811
+ if (operand.type === PS_NODE.const) {
197812
+ const v = _evalUnaryConst(op, operand.value);
197813
+ if (v !== void 0) {
197814
+ return new PsConstNode(v);
197815
+ }
197816
+ }
197817
+ if (op === TOKEN.not && operand.type === PS_NODE.binary) {
197818
+ const negated = _PSStackToTree.#negatedComparison.get(operand.op);
197819
+ if (negated !== void 0) {
197820
+ return new PsBinaryNode(
197821
+ negated,
197822
+ operand.first,
197823
+ operand.second,
197824
+ PS_VALUE_TYPE.boolean
197825
+ );
197826
+ }
197827
+ }
197828
+ if (op === TOKEN.neg && operand.type === PS_NODE.binary && operand.op === TOKEN.sub) {
197829
+ return this._makeBinary(TOKEN.sub, operand.second, operand.first);
197830
+ }
197831
+ if (operand.type === PS_NODE.unary) {
197832
+ if (op === TOKEN.neg && operand.op === TOKEN.neg || op === TOKEN.not && operand.op === TOKEN.not) {
197833
+ return operand.operand;
197834
+ }
197835
+ if (op === TOKEN.abs && operand.op === TOKEN.neg) {
197836
+ return this._makeUnary(TOKEN.abs, operand.operand);
197837
+ }
197838
+ if (_PSStackToTree.#idempotentUnary.has(op) && op === operand.op) {
197839
+ return operand;
197840
+ }
197841
+ }
197842
+ return new PsUnaryNode(op, operand, _unaryValueType(op, operand.valueType));
197843
+ }
197844
+ /**
197845
+ * Create a ternary node, applying optimizations eagerly:
197846
+ *
197847
+ * 1. Constant condition — fold to the live branch.
197848
+ * 2. Identical branches — the condition is irrelevant, return either branch.
197849
+ * 3. Boolean branch constants — `cond ? true : false` → cond,
197850
+ * `cond ? false : true` → not(cond).
197851
+ * 4. Ternary → branchless min/max when the condition compares two numeric
197852
+ * expressions that are also the two branches.
197853
+ */
197854
+ _makeTernary(cond, then, otherwise) {
197855
+ if (cond.type === PS_NODE.const) {
197856
+ return cond.value ? then : otherwise;
197857
+ }
197858
+ if (_nodesEqual(then, otherwise)) {
197859
+ return then;
197860
+ }
197861
+ if (then.type === PS_NODE.const && otherwise.type === PS_NODE.const) {
197862
+ if (then.value === true && otherwise.value === false) {
197863
+ return cond;
197864
+ }
197865
+ if (then.value === false && otherwise.value === true) {
197866
+ return this._makeUnary(TOKEN.not, cond);
197867
+ }
197868
+ }
197869
+ if (cond.type === PS_NODE.binary) {
197870
+ const { op: cop, first: cf, second: cs } = cond;
197871
+ if (cop === TOKEN.gt || cop === TOKEN.ge) {
197872
+ if (_nodesEqual(then, cf) && _nodesEqual(otherwise, cs)) {
197873
+ return this._makeBinary(TOKEN.min, cf, cs);
197874
+ }
197875
+ if (_nodesEqual(then, cs) && _nodesEqual(otherwise, cf)) {
197876
+ return this._makeBinary(TOKEN.max, cf, cs);
197877
+ }
197878
+ } else if (cop === TOKEN.lt || cop === TOKEN.le) {
197879
+ if (_nodesEqual(then, cf) && _nodesEqual(otherwise, cs)) {
197880
+ return this._makeBinary(TOKEN.max, cf, cs);
197881
+ }
197882
+ if (_nodesEqual(then, cs) && _nodesEqual(otherwise, cf)) {
197883
+ return this._makeBinary(TOKEN.min, cf, cs);
197884
+ }
197885
+ }
197886
+ }
197887
+ return new PsTernaryNode(
197888
+ cond,
197889
+ then,
197890
+ otherwise,
197891
+ then.valueType === otherwise.valueType ? then.valueType : PS_VALUE_TYPE.unknown
197892
+ );
197893
+ }
197894
+ };
197895
+ var OP = {
197896
+ ARG: 0,
197897
+ // [ARG, idx]
197898
+ CONST: 1,
197899
+ // [CONST, val]
197900
+ STORE: 2,
197901
+ // [STORE, slot, min, max] clamp(pop()) → mem[slot]
197902
+ IF: 3,
197903
+ // [IF, target] jump when top-of-stack === 0
197904
+ JUMP: 4,
197905
+ // [JUMP, target] unconditional
197906
+ ABS: 5,
197907
+ NEG: 6,
197908
+ CEIL: 7,
197909
+ FLOOR: 8,
197910
+ ROUND: 9,
197911
+ // floor(x + 0.5)
197912
+ TRUNC: 10,
197913
+ NOT_B: 11,
197914
+ // boolean NOT
197915
+ NOT_N: 12,
197916
+ // bitwise NOT
197917
+ SQRT: 13,
197918
+ SIN: 14,
197919
+ // degrees in/out
197920
+ COS: 15,
197921
+ LN: 16,
197922
+ LOG10: 17,
197923
+ CVI: 18,
197924
+ SHIFT: 19,
197925
+ // [SHIFT, amount] +ve = left, −ve = right
197926
+ // Binary ops: second below, first on top; result = second OP first.
197927
+ ADD: 20,
197928
+ SUB: 21,
197929
+ MUL: 22,
197930
+ DIV: 23,
197931
+ // 0 when divisor is 0
197932
+ IDIV: 24,
197933
+ // 0 when divisor is 0
197934
+ MOD: 25,
197935
+ // 0 when divisor is 0
197936
+ POW: 26,
197937
+ EQ: 27,
197938
+ NE: 28,
197939
+ GT: 29,
197940
+ GE: 30,
197941
+ LT: 31,
197942
+ LE: 32,
197943
+ AND: 33,
197944
+ OR: 34,
197945
+ XOR: 35,
197946
+ ATAN: 36,
197947
+ // atan2(second, first) → degrees [0, 360)
197948
+ MIN: 37,
197949
+ MAX: 38,
197950
+ TEE_TMP: 39,
197951
+ // [TEE_TMP, slot] peek top of stack → tmp[slot], leave on stack
197952
+ LOAD_TMP: 40
197953
+ // [LOAD_TMP, slot] push tmp[slot]
197954
+ };
197955
+ var _DEG_TO_RAD = Math.PI / 180;
197956
+ var _RAD_TO_DEG = 180 / Math.PI;
197957
+ var PsJsCompiler = class {
197958
+ // Safe because JS is single-threaded.
197959
+ static #stack = new Float64Array(64);
197960
+ static #tmp = new Float64Array(64);
197961
+ constructor(domain, range3) {
197962
+ this.nIn = domain.length >> 1;
197963
+ this.nOut = range3.length >> 1;
197964
+ this.range = range3;
197965
+ this.ir = [];
197966
+ this._tmpMap = /* @__PURE__ */ new Map();
197967
+ this._nextTmp = 0;
197968
+ }
197969
+ _compileNode(node3) {
197970
+ if (node3.shared) {
197971
+ const cached = this._tmpMap.get(node3);
197972
+ if (cached !== void 0) {
197973
+ this.ir.push(OP.LOAD_TMP, cached);
197974
+ return true;
197975
+ }
197976
+ if (!this._compileNodeImpl(node3)) {
197977
+ return false;
197978
+ }
197979
+ const slot = this._nextTmp++;
197980
+ this._tmpMap.set(node3, slot);
197981
+ this.ir.push(OP.TEE_TMP, slot);
197982
+ return true;
197983
+ }
197984
+ return this._compileNodeImpl(node3);
197985
+ }
197986
+ _compileNodeImpl(node3) {
197987
+ switch (node3.type) {
197988
+ case PS_NODE.arg:
197989
+ this.ir.push(OP.ARG, node3.index);
197990
+ return true;
197991
+ case PS_NODE.const: {
197992
+ const v = node3.value;
197993
+ this.ir.push(OP.CONST, typeof v === "boolean" ? Number(v) : v);
197994
+ return true;
197995
+ }
197996
+ case PS_NODE.unary:
197997
+ return this._compileUnary(node3);
197998
+ case PS_NODE.binary:
197999
+ return this._compileBinary(node3);
198000
+ case PS_NODE.ternary:
198001
+ return this._compileTernary(node3);
198002
+ default:
198003
+ return false;
198004
+ }
198005
+ }
198006
+ _compileUnary(node3) {
198007
+ const { op, operand, valueType } = node3;
198008
+ if (op === TOKEN.cvr) {
198009
+ return this._compileNode(operand);
198010
+ }
198011
+ if (!this._compileNode(operand)) {
198012
+ return false;
198013
+ }
198014
+ switch (op) {
198015
+ case TOKEN.abs:
198016
+ this.ir.push(OP.ABS);
198017
+ break;
198018
+ case TOKEN.neg:
198019
+ this.ir.push(OP.NEG);
198020
+ break;
198021
+ case TOKEN.ceiling:
198022
+ this.ir.push(OP.CEIL);
198023
+ break;
198024
+ case TOKEN.floor:
198025
+ this.ir.push(OP.FLOOR);
198026
+ break;
198027
+ case TOKEN.round:
198028
+ this.ir.push(OP.ROUND);
198029
+ break;
198030
+ case TOKEN.truncate:
198031
+ this.ir.push(OP.TRUNC);
198032
+ break;
198033
+ case TOKEN.sqrt:
198034
+ this.ir.push(OP.SQRT);
198035
+ break;
198036
+ case TOKEN.sin:
198037
+ this.ir.push(OP.SIN);
198038
+ break;
198039
+ case TOKEN.cos:
198040
+ this.ir.push(OP.COS);
198041
+ break;
198042
+ case TOKEN.ln:
198043
+ this.ir.push(OP.LN);
198044
+ break;
198045
+ case TOKEN.log:
198046
+ this.ir.push(OP.LOG10);
198047
+ break;
198048
+ case TOKEN.cvi:
198049
+ this.ir.push(OP.CVI);
198050
+ break;
198051
+ case TOKEN.not:
198052
+ if (valueType === PS_VALUE_TYPE.boolean) {
198053
+ this.ir.push(OP.NOT_B);
198054
+ } else if (valueType === PS_VALUE_TYPE.numeric) {
198055
+ this.ir.push(OP.NOT_N);
198056
+ } else {
198057
+ return false;
198058
+ }
198059
+ break;
198060
+ default:
198061
+ return false;
198062
+ }
198063
+ return true;
198064
+ }
198065
+ _compileBinary(node3) {
198066
+ const { op, first, second } = node3;
198067
+ if (op === TOKEN.bitshift) {
198068
+ if (first.type !== PS_NODE.const || !Number.isInteger(first.value) || !this._compileNode(second)) {
198069
+ return false;
198070
+ }
198071
+ this.ir.push(OP.SHIFT, first.value);
198072
+ return true;
198073
+ }
198074
+ if (!this._compileNode(second) || !this._compileNode(first)) {
198075
+ return false;
198076
+ }
198077
+ switch (op) {
198078
+ case TOKEN.add:
198079
+ this.ir.push(OP.ADD);
198080
+ break;
198081
+ case TOKEN.sub:
198082
+ this.ir.push(OP.SUB);
198083
+ break;
198084
+ case TOKEN.mul:
198085
+ this.ir.push(OP.MUL);
198086
+ break;
198087
+ case TOKEN.div:
198088
+ this.ir.push(OP.DIV);
198089
+ break;
198090
+ case TOKEN.idiv:
198091
+ this.ir.push(OP.IDIV);
198092
+ break;
198093
+ case TOKEN.mod:
198094
+ this.ir.push(OP.MOD);
198095
+ break;
198096
+ case TOKEN.exp:
198097
+ this.ir.push(OP.POW);
198098
+ break;
198099
+ case TOKEN.eq:
198100
+ this.ir.push(OP.EQ);
198101
+ break;
198102
+ case TOKEN.ne:
198103
+ this.ir.push(OP.NE);
198104
+ break;
198105
+ case TOKEN.gt:
198106
+ this.ir.push(OP.GT);
198107
+ break;
198108
+ case TOKEN.ge:
198109
+ this.ir.push(OP.GE);
198110
+ break;
198111
+ case TOKEN.lt:
198112
+ this.ir.push(OP.LT);
198113
+ break;
198114
+ case TOKEN.le:
198115
+ this.ir.push(OP.LE);
198116
+ break;
198117
+ case TOKEN.and:
198118
+ this.ir.push(OP.AND);
198119
+ break;
198120
+ case TOKEN.or:
198121
+ this.ir.push(OP.OR);
198122
+ break;
198123
+ case TOKEN.xor:
198124
+ this.ir.push(OP.XOR);
198125
+ break;
198126
+ case TOKEN.atan:
198127
+ this.ir.push(OP.ATAN);
198128
+ break;
198129
+ case TOKEN.min:
198130
+ this.ir.push(OP.MIN);
198131
+ break;
198132
+ case TOKEN.max:
198133
+ this.ir.push(OP.MAX);
198134
+ break;
198135
+ default:
198136
+ return false;
198137
+ }
198138
+ return true;
198139
+ }
198140
+ _compileTernary(node3) {
198141
+ if (!this._compileNode(node3.cond)) {
198142
+ return false;
198143
+ }
198144
+ this.ir.push(OP.IF, 0);
198145
+ const ifPatch = this.ir.length - 1;
198146
+ if (!this._compileNode(node3.then)) {
198147
+ return false;
198148
+ }
198149
+ this.ir.push(OP.JUMP, 0);
198150
+ const jumpPatch = this.ir.length - 1;
198151
+ this.ir[ifPatch] = this.ir.length;
198152
+ if (!this._compileNode(node3.otherwise)) {
198153
+ return false;
198154
+ }
198155
+ this.ir[jumpPatch] = this.ir.length;
198156
+ return true;
198157
+ }
198158
+ compile(program) {
198159
+ const outputs = new PSStackToTree().evaluate(program, this.nIn);
198160
+ if (!outputs || outputs.length < this.nOut) {
198161
+ return null;
198162
+ }
198163
+ for (let i = 0; i < this.nOut; i++) {
198164
+ if (!this._compileNode(outputs[i])) {
198165
+ return null;
198166
+ }
198167
+ const min = this.range[i * 2];
198168
+ const max = this.range[i * 2 + 1];
198169
+ this.ir.push(OP.STORE, i, min, max);
198170
+ }
198171
+ return new Float64Array(this.ir);
198172
+ }
198173
+ static execute(ir, src, srcOffset, dest, destOffset) {
198174
+ let ip = 0, sp = 0;
198175
+ const n = ir.length;
198176
+ const stack = this.#stack;
198177
+ const tmp = this.#tmp;
198178
+ while (ip < n) {
198179
+ switch (ir[ip++] | 0) {
198180
+ case OP.ARG:
198181
+ stack[sp++] = src[srcOffset + (ir[ip++] | 0)];
198182
+ break;
198183
+ case OP.CONST:
198184
+ stack[sp++] = ir[ip++];
198185
+ break;
198186
+ case OP.STORE: {
198187
+ const slot = ir[ip++] | 0;
198188
+ const min = ir[ip++];
198189
+ const max = ir[ip++];
198190
+ dest[destOffset + slot] = MathClamp(stack[--sp], min, max);
198191
+ break;
198192
+ }
198193
+ case OP.IF: {
198194
+ const tgt = ir[ip++];
198195
+ if (stack[--sp] === 0) {
198196
+ ip = tgt;
198197
+ }
198198
+ break;
198199
+ }
198200
+ case OP.JUMP:
198201
+ ip = ir[ip];
198202
+ break;
198203
+ case OP.ABS:
198204
+ stack[sp - 1] = Math.abs(stack[sp - 1]);
198205
+ break;
198206
+ case OP.NEG:
198207
+ stack[sp - 1] = -stack[sp - 1];
198208
+ break;
198209
+ case OP.CEIL:
198210
+ stack[sp - 1] = Math.ceil(stack[sp - 1]);
198211
+ break;
198212
+ case OP.FLOOR:
198213
+ stack[sp - 1] = Math.floor(stack[sp - 1]);
198214
+ break;
198215
+ case OP.ROUND:
198216
+ stack[sp - 1] = Math.floor(stack[sp - 1] + 0.5);
198217
+ break;
198218
+ case OP.TRUNC:
198219
+ stack[sp - 1] = Math.trunc(stack[sp - 1]);
198220
+ break;
198221
+ case OP.NOT_B:
198222
+ stack[sp - 1] = stack[sp - 1] !== 0 ? 0 : 1;
198223
+ break;
198224
+ case OP.NOT_N:
198225
+ stack[sp - 1] = ~(stack[sp - 1] | 0);
198226
+ break;
198227
+ case OP.SQRT:
198228
+ stack[sp - 1] = Math.sqrt(stack[sp - 1]);
198229
+ break;
198230
+ case OP.SIN:
198231
+ stack[sp - 1] = Math.sin(stack[sp - 1] % 360 * _DEG_TO_RAD);
198232
+ break;
198233
+ case OP.COS:
198234
+ stack[sp - 1] = Math.cos(stack[sp - 1] % 360 * _DEG_TO_RAD);
198235
+ break;
198236
+ case OP.LN:
198237
+ stack[sp - 1] = Math.log(stack[sp - 1]);
198238
+ break;
198239
+ case OP.LOG10:
198240
+ stack[sp - 1] = Math.log10(stack[sp - 1]);
198241
+ break;
198242
+ case OP.CVI:
198243
+ stack[sp - 1] = Math.trunc(stack[sp - 1]) | 0;
198244
+ break;
198245
+ case OP.SHIFT: {
198246
+ const amt = ir[ip++];
198247
+ const v = stack[sp - 1] | 0;
198248
+ if (amt > 0) {
198249
+ stack[sp - 1] = v << amt;
198250
+ } else if (amt < 0) {
198251
+ stack[sp - 1] = v >> -amt;
198252
+ } else {
198253
+ stack[sp - 1] = v;
198254
+ }
198255
+ break;
198256
+ }
198257
+ case OP.ADD: {
198258
+ const b3 = stack[--sp];
198259
+ stack[sp - 1] += b3;
198260
+ break;
198261
+ }
198262
+ case OP.SUB: {
198263
+ const b3 = stack[--sp];
198264
+ stack[sp - 1] -= b3;
198265
+ break;
198266
+ }
198267
+ case OP.MUL: {
198268
+ const b3 = stack[--sp];
198269
+ stack[sp - 1] *= b3;
198270
+ break;
198271
+ }
198272
+ case OP.DIV: {
198273
+ const b3 = stack[--sp];
198274
+ stack[sp - 1] = b3 !== 0 ? stack[sp - 1] / b3 : 0;
198275
+ break;
198276
+ }
198277
+ case OP.IDIV: {
198278
+ const b3 = stack[--sp];
198279
+ stack[sp - 1] = b3 !== 0 ? Math.trunc(stack[sp - 1] / b3) : 0;
198280
+ break;
198281
+ }
198282
+ case OP.MOD: {
198283
+ const b3 = stack[--sp];
198284
+ stack[sp - 1] = b3 !== 0 ? stack[sp - 1] % b3 : 0;
198285
+ break;
198286
+ }
198287
+ case OP.POW: {
198288
+ const b3 = stack[--sp];
198289
+ stack[sp - 1] **= b3;
198290
+ break;
198291
+ }
198292
+ case OP.EQ: {
198293
+ const b3 = stack[--sp];
198294
+ stack[sp - 1] = stack[sp - 1] === b3 ? 1 : 0;
198295
+ break;
198296
+ }
198297
+ case OP.NE: {
198298
+ const b3 = stack[--sp];
198299
+ stack[sp - 1] = stack[sp - 1] !== b3 ? 1 : 0;
198300
+ break;
198301
+ }
198302
+ case OP.GT: {
198303
+ const b3 = stack[--sp];
198304
+ stack[sp - 1] = stack[sp - 1] > b3 ? 1 : 0;
198305
+ break;
198306
+ }
198307
+ case OP.GE: {
198308
+ const b3 = stack[--sp];
198309
+ stack[sp - 1] = stack[sp - 1] >= b3 ? 1 : 0;
198310
+ break;
198311
+ }
198312
+ case OP.LT: {
198313
+ const b3 = stack[--sp];
198314
+ stack[sp - 1] = stack[sp - 1] < b3 ? 1 : 0;
198315
+ break;
198316
+ }
198317
+ case OP.LE: {
198318
+ const b3 = stack[--sp];
198319
+ stack[sp - 1] = stack[sp - 1] <= b3 ? 1 : 0;
198320
+ break;
198321
+ }
198322
+ case OP.AND: {
198323
+ const b3 = stack[--sp] | 0;
198324
+ stack[sp - 1] = (stack[sp - 1] | 0) & b3;
198325
+ break;
198326
+ }
198327
+ case OP.OR: {
198328
+ const b3 = stack[--sp] | 0;
198329
+ stack[sp - 1] = stack[sp - 1] | 0 | b3;
198330
+ break;
198331
+ }
198332
+ case OP.XOR: {
198333
+ const b3 = stack[--sp] | 0;
198334
+ stack[sp - 1] = (stack[sp - 1] | 0) ^ b3;
198335
+ break;
198336
+ }
198337
+ case OP.ATAN: {
198338
+ const b3 = stack[--sp];
198339
+ const deg = Math.atan2(stack[sp - 1], b3) * _RAD_TO_DEG;
198340
+ stack[sp - 1] = deg < 0 ? deg + 360 : deg;
198341
+ break;
198342
+ }
198343
+ case OP.MIN: {
198344
+ const b3 = stack[--sp];
198345
+ stack[sp - 1] = Math.min(stack[sp - 1], b3);
198346
+ break;
198347
+ }
198348
+ case OP.MAX: {
198349
+ const b3 = stack[--sp];
198350
+ stack[sp - 1] = Math.max(stack[sp - 1], b3);
198351
+ break;
198352
+ }
198353
+ case OP.TEE_TMP:
198354
+ tmp[ir[ip++] | 0] = stack[sp - 1];
198355
+ break;
198356
+ case OP.LOAD_TMP:
198357
+ stack[sp++] = tmp[ir[ip++] | 0];
198358
+ break;
198359
+ }
198360
+ }
198361
+ }
198362
+ };
198363
+ var PSStackBasedInterpreter = class {
198364
+ // Safe: JS is single-threaded.
198365
+ static #stack = new Float64Array(100);
198366
+ static #sp = 0;
198367
+ static #push(v) {
198368
+ if (this.#sp < this.#stack.length) {
198369
+ this.#stack[this.#sp++] = v;
198370
+ }
198371
+ }
198372
+ static #execOp(op) {
198373
+ const stack = this.#stack;
198374
+ switch (op) {
198375
+ case TOKEN.true:
198376
+ this.#push(1);
198377
+ break;
198378
+ case TOKEN.false:
198379
+ this.#push(0);
198380
+ break;
198381
+ case TOKEN.abs:
198382
+ stack[this.#sp - 1] = Math.abs(stack[this.#sp - 1]);
198383
+ break;
198384
+ case TOKEN.neg:
198385
+ stack[this.#sp - 1] = -stack[this.#sp - 1];
198386
+ break;
198387
+ case TOKEN.ceiling:
198388
+ stack[this.#sp - 1] = Math.ceil(stack[this.#sp - 1]);
198389
+ break;
198390
+ case TOKEN.floor:
198391
+ stack[this.#sp - 1] = Math.floor(stack[this.#sp - 1]);
198392
+ break;
198393
+ case TOKEN.round:
198394
+ stack[this.#sp - 1] = Math.floor(stack[this.#sp - 1] + 0.5);
198395
+ break;
198396
+ case TOKEN.truncate:
198397
+ stack[this.#sp - 1] = Math.trunc(stack[this.#sp - 1]);
198398
+ break;
198399
+ case TOKEN.sqrt:
198400
+ stack[this.#sp - 1] = Math.sqrt(stack[this.#sp - 1]);
198401
+ break;
198402
+ case TOKEN.sin:
198403
+ stack[this.#sp - 1] = Math.sin(
198404
+ stack[this.#sp - 1] % 360 * _DEG_TO_RAD
198405
+ );
198406
+ break;
198407
+ case TOKEN.cos:
198408
+ stack[this.#sp - 1] = Math.cos(
198409
+ stack[this.#sp - 1] % 360 * _DEG_TO_RAD
198410
+ );
198411
+ break;
198412
+ case TOKEN.ln:
198413
+ stack[this.#sp - 1] = Math.log(stack[this.#sp - 1]);
198414
+ break;
198415
+ case TOKEN.log:
198416
+ stack[this.#sp - 1] = Math.log10(stack[this.#sp - 1]);
198417
+ break;
198418
+ case TOKEN.cvi:
198419
+ stack[this.#sp - 1] = Math.trunc(stack[this.#sp - 1]) | 0;
198420
+ break;
198421
+ case TOKEN.cvr:
198422
+ break;
198423
+ // values are already f64
198424
+ case TOKEN.not: {
198425
+ const v = stack[this.#sp - 1];
198426
+ stack[this.#sp - 1] = v === 0 || v === 1 ? 1 - v : ~(v | 0);
198427
+ break;
198428
+ }
198429
+ case TOKEN.add: {
198430
+ const b3 = stack[--this.#sp];
198431
+ stack[this.#sp - 1] += b3;
198432
+ break;
198433
+ }
198434
+ case TOKEN.sub: {
198435
+ const b3 = stack[--this.#sp];
198436
+ stack[this.#sp - 1] -= b3;
198437
+ break;
198438
+ }
198439
+ case TOKEN.mul: {
198440
+ const b3 = stack[--this.#sp];
198441
+ stack[this.#sp - 1] *= b3;
198442
+ break;
198443
+ }
198444
+ case TOKEN.div: {
198445
+ const b3 = stack[--this.#sp];
198446
+ stack[this.#sp - 1] = b3 !== 0 ? stack[this.#sp - 1] / b3 : 0;
198447
+ break;
198448
+ }
198449
+ case TOKEN.idiv: {
198450
+ const b3 = stack[--this.#sp];
198451
+ stack[this.#sp - 1] = b3 !== 0 ? Math.trunc(stack[this.#sp - 1] / b3) : 0;
198452
+ break;
198453
+ }
198454
+ case TOKEN.mod: {
198455
+ const b3 = stack[--this.#sp];
198456
+ stack[this.#sp - 1] = b3 !== 0 ? stack[this.#sp - 1] % b3 : 0;
198457
+ break;
198458
+ }
198459
+ case TOKEN.exp: {
198460
+ const b3 = stack[--this.#sp];
198461
+ stack[this.#sp - 1] **= b3;
198462
+ break;
198463
+ }
198464
+ case TOKEN.atan: {
198465
+ const dx = stack[--this.#sp];
198466
+ const deg = Math.atan2(stack[this.#sp - 1], dx) * _RAD_TO_DEG;
198467
+ stack[this.#sp - 1] = deg < 0 ? deg + 360 : deg;
198468
+ break;
198469
+ }
198470
+ case TOKEN.eq: {
198471
+ const b3 = stack[--this.#sp];
198472
+ stack[this.#sp - 1] = stack[this.#sp - 1] === b3 ? 1 : 0;
198473
+ break;
198474
+ }
198475
+ case TOKEN.ne: {
198476
+ const b3 = stack[--this.#sp];
198477
+ stack[this.#sp - 1] = stack[this.#sp - 1] !== b3 ? 1 : 0;
198478
+ break;
198479
+ }
198480
+ case TOKEN.gt: {
198481
+ const b3 = stack[--this.#sp];
198482
+ stack[this.#sp - 1] = stack[this.#sp - 1] > b3 ? 1 : 0;
198483
+ break;
198484
+ }
198485
+ case TOKEN.ge: {
198486
+ const b3 = stack[--this.#sp];
198487
+ stack[this.#sp - 1] = stack[this.#sp - 1] >= b3 ? 1 : 0;
198488
+ break;
198489
+ }
198490
+ case TOKEN.lt: {
198491
+ const b3 = stack[--this.#sp];
198492
+ stack[this.#sp - 1] = stack[this.#sp - 1] < b3 ? 1 : 0;
198493
+ break;
198494
+ }
198495
+ case TOKEN.le: {
198496
+ const b3 = stack[--this.#sp];
198497
+ stack[this.#sp - 1] = stack[this.#sp - 1] <= b3 ? 1 : 0;
198498
+ break;
198499
+ }
198500
+ case TOKEN.and: {
198501
+ const b3 = stack[--this.#sp] | 0;
198502
+ stack[this.#sp - 1] = (stack[this.#sp - 1] | 0) & b3;
198503
+ break;
198504
+ }
198505
+ case TOKEN.or: {
198506
+ const b3 = stack[--this.#sp] | 0;
198507
+ stack[this.#sp - 1] = stack[this.#sp - 1] | 0 | b3;
198508
+ break;
198509
+ }
198510
+ case TOKEN.xor: {
198511
+ const b3 = stack[--this.#sp] | 0;
198512
+ stack[this.#sp - 1] = (stack[this.#sp - 1] | 0) ^ b3;
198513
+ break;
198514
+ }
198515
+ case TOKEN.bitshift: {
198516
+ const amt = stack[--this.#sp] | 0;
198517
+ const v = stack[this.#sp - 1] | 0;
198518
+ stack[this.#sp - 1] = amt > 0 ? v << amt : v >> -amt;
198519
+ break;
198520
+ }
198521
+ case TOKEN.min: {
198522
+ const b3 = stack[--this.#sp];
198523
+ stack[this.#sp - 1] = Math.min(stack[this.#sp - 1], b3);
198524
+ break;
198525
+ }
198526
+ case TOKEN.max: {
198527
+ const b3 = stack[--this.#sp];
198528
+ stack[this.#sp - 1] = Math.max(stack[this.#sp - 1], b3);
198529
+ break;
198530
+ }
198531
+ case TOKEN.dup:
198532
+ this.#push(stack[this.#sp - 1]);
198533
+ break;
198534
+ case TOKEN.exch: {
198535
+ const a3 = stack[--this.#sp];
198536
+ const b3 = stack[--this.#sp];
198537
+ this.#push(a3);
198538
+ this.#push(b3);
198539
+ break;
198540
+ }
198541
+ case TOKEN.pop:
198542
+ this.#sp--;
198543
+ break;
198544
+ case TOKEN.copy: {
198545
+ const n = Math.trunc(stack[--this.#sp]);
198546
+ const base = this.#sp - n;
198547
+ for (let k = 0; k < n; k++) {
198548
+ this.#push(stack[base + k]);
198549
+ }
198550
+ break;
198551
+ }
198552
+ case TOKEN.index: {
198553
+ const i = Math.trunc(stack[--this.#sp]);
198554
+ this.#push(stack[this.#sp - 1 - i]);
198555
+ break;
198556
+ }
198557
+ case TOKEN.roll: {
198558
+ const j = Math.trunc(stack[--this.#sp]);
198559
+ const n = Math.trunc(stack[--this.#sp]);
198560
+ if (n > 1 && j !== 0) {
198561
+ const mod = (j % n + n) % n;
198562
+ if (mod !== 0) {
198563
+ const base = this.#sp - n;
198564
+ const sub = stack.slice(base, this.#sp);
198565
+ for (let k = 0; k < n; k++) {
198566
+ stack[base + k] = sub[(k - mod + n) % n];
198567
+ }
198568
+ }
198569
+ }
198570
+ break;
198571
+ }
198572
+ }
198573
+ }
198574
+ static #execBlock(instructions) {
198575
+ for (const instr of instructions) {
198576
+ switch (instr.type) {
198577
+ case PS_NODE.number:
198578
+ this.#push(instr.value);
198579
+ break;
198580
+ case PS_NODE.operator:
198581
+ this.#execOp(instr.op);
198582
+ break;
198583
+ case PS_NODE.if:
198584
+ if (this.#stack[--this.#sp] !== 0) {
198585
+ this.#execBlock(instr.then.instructions);
198586
+ }
198587
+ break;
198588
+ case PS_NODE.ifelse:
198589
+ if (this.#stack[--this.#sp] !== 0) {
198590
+ this.#execBlock(instr.then.instructions);
198591
+ } else {
198592
+ this.#execBlock(instr.otherwise.instructions);
198593
+ }
198594
+ break;
198595
+ }
198596
+ }
198597
+ }
198598
+ /**
198599
+ * @param {import("./ast.js").PsProgram} program
198600
+ * @param {number[]} domain – flat [min0,max0, …]
198601
+ * @param {number[]} range – flat [min0,max0, …]
198602
+ * @returns {Function} – `(src, srcOffset, dest, destOffset) => void`
198603
+ */
198604
+ static build(program, domain, range3) {
198605
+ const nIn = domain.length >> 1;
198606
+ const nOut = range3.length >> 1;
198607
+ const { instructions } = program.body;
198608
+ return (src, srcOffset, dest, destOffset) => {
198609
+ this.#sp = 0;
198610
+ for (let i = 0; i < nIn; i++) {
198611
+ this.#push(src[srcOffset + i]);
198612
+ }
198613
+ this.#execBlock(instructions);
198614
+ const base = this.#sp - nOut;
198615
+ for (let i = 0; i < nOut; i++) {
198616
+ const v = base + i >= 0 ? this.#stack[base + i] : 0;
198617
+ dest[destOffset + i] = MathClamp(v, range3[i * 2], range3[i * 2 + 1]);
198618
+ }
198619
+ };
198620
+ }
198621
+ };
198622
+ function buildPostScriptJsFunction(source, domain, range3, forceInterpreter = false) {
198623
+ const program = parsePostScriptFunction(source);
198624
+ const ir = !forceInterpreter && new PsJsCompiler(domain, range3).compile(program);
198625
+ if (ir) {
198626
+ return (src, srcOffset, dest, destOffset) => {
198627
+ PsJsCompiler.execute(ir, src, srcOffset, dest, destOffset);
198628
+ };
198629
+ }
198630
+ return PSStackBasedInterpreter.build(program, domain, range3);
198631
+ }
198632
+ var ShadingType = {
198633
+ FUNCTION_BASED: 1,
198634
+ AXIAL: 2,
198635
+ RADIAL: 3,
198636
+ FREE_FORM_MESH: 4,
198637
+ LATTICE_FORM_MESH: 5,
198638
+ COONS_PATCH_MESH: 6,
198639
+ TENSOR_PATCH_MESH: 7
198640
+ };
198641
+ var BaseShading = class _BaseShading {
198642
+ // A small number to offset the first/last color stops so we can insert ones
198643
+ // to support extend. Number.MIN_VALUE is too small and breaks the extend.
198644
+ static SMALL_NUMBER = 1e-6;
198645
+ constructor() {
198646
+ if ((typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) && this.constructor === _BaseShading) {
198647
+ unreachable2("Cannot initialize BaseShading.");
198648
+ }
198649
+ }
198650
+ getIR() {
198651
+ unreachable2("Abstract method `getIR` called.");
198652
+ }
198653
+ };
198654
+ function meshUpdateBounds(self2) {
198655
+ let minX = self2.coords[0][0], minY = self2.coords[0][1], maxX = minX, maxY = minY;
198656
+ for (let i = 1, ii = self2.coords.length; i < ii; i++) {
198657
+ const x = self2.coords[i][0], y = self2.coords[i][1];
198658
+ minX = minX > x ? x : minX;
198659
+ minY = minY > y ? y : minY;
198660
+ maxX = maxX < x ? x : maxX;
198661
+ maxY = maxY < y ? y : maxY;
198662
+ }
198663
+ self2.bounds = [minX, minY, maxX, maxY];
198664
+ }
198665
+ function meshPackData(self2) {
198666
+ let i, j, ii;
198667
+ const coords = self2.coords;
198668
+ const coordsPacked = new Float32Array(coords.length * 2);
198669
+ for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
198670
+ const xy = coords[i];
198671
+ coordsPacked[j++] = xy[0];
198672
+ coordsPacked[j++] = xy[1];
198673
+ }
198674
+ self2.coords = coordsPacked;
198675
+ const colors2 = self2.colors;
198676
+ const colorsPacked = new Uint8Array(colors2.length * 4);
198677
+ for (i = 0, j = 0, ii = colors2.length; i < ii; i++) {
198678
+ const c4 = colors2[i];
198679
+ colorsPacked[j++] = c4[0];
198680
+ colorsPacked[j++] = c4[1];
198681
+ colorsPacked[j++] = c4[2];
198682
+ j++;
198683
+ }
198684
+ self2.colors = colorsPacked;
198685
+ for (const figure of self2.figures) {
198686
+ figure.coords = new Uint32Array(figure.coords);
198687
+ figure.colors = new Uint32Array(figure.colors);
198688
+ }
198689
+ }
198690
+ function buildMeshVertexData(coords, colors2, figures) {
198691
+ let vertexCount = 0;
198692
+ for (const figure of figures) {
198693
+ if (figure.type === MeshFigureType.TRIANGLES) {
198694
+ vertexCount += figure.coords.length;
198695
+ } else if (figure.type === MeshFigureType.LATTICE) {
198696
+ const vpr = figure.verticesPerRow;
198697
+ vertexCount += (Math.floor(figure.coords.length / vpr) - 1) * (vpr - 1) * 6;
198698
+ }
198699
+ }
198700
+ const posData = new Float32Array(vertexCount * 2);
198701
+ const colData = new Uint8Array(vertexCount * 4);
198702
+ let pOff = 0, cOff = 0;
198703
+ const addVertex = (pi2, ci) => {
198704
+ posData[pOff++] = coords[pi2 * 2];
198705
+ posData[pOff++] = coords[pi2 * 2 + 1];
198706
+ colData[cOff++] = colors2[ci * 4];
198707
+ colData[cOff++] = colors2[ci * 4 + 1];
198708
+ colData[cOff++] = colors2[ci * 4 + 2];
198709
+ cOff++;
198710
+ };
198711
+ for (const figure of figures) {
198712
+ const ps = figure.coords;
198713
+ const cs = figure.colors;
198714
+ if (figure.type === MeshFigureType.TRIANGLES) {
198715
+ for (let i = 0, ii = ps.length; i < ii; i++) {
198716
+ addVertex(ps[i], cs[i]);
198717
+ }
198718
+ } else if (figure.type === MeshFigureType.LATTICE) {
198719
+ const vpr = figure.verticesPerRow;
198720
+ const rows = Math.floor(ps.length / vpr) - 1;
198721
+ const cols = vpr - 1;
198722
+ for (let i = 0; i < rows; i++) {
198723
+ let q2 = i * vpr;
198724
+ for (let j = 0; j < cols; j++, q2++) {
198725
+ addVertex(ps[q2], cs[q2]);
198726
+ addVertex(ps[q2 + 1], cs[q2 + 1]);
198727
+ addVertex(ps[q2 + vpr], cs[q2 + vpr]);
198728
+ addVertex(ps[q2 + vpr + 1], cs[q2 + vpr + 1]);
198729
+ addVertex(ps[q2 + 1], cs[q2 + 1]);
198730
+ addVertex(ps[q2 + vpr], cs[q2 + vpr]);
198731
+ }
198732
+ }
198733
+ }
198734
+ }
198735
+ return { posData, colData, vertexCount };
198736
+ }
198737
+ var MeshStreamReader = class {
198738
+ constructor(stream, context) {
198739
+ this.stream = stream;
198740
+ this.context = context;
198741
+ this.buffer = 0;
198742
+ this.bufferLength = 0;
198743
+ const numComps = context.numComps;
198744
+ this.tmpCompsBuf = new Float32Array(numComps);
198745
+ const csNumComps = context.colorSpace.numComps;
198746
+ this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) : this.tmpCompsBuf;
198747
+ }
198748
+ get hasData() {
198749
+ if (this.stream.end) {
198750
+ return this.stream.pos < this.stream.end;
198751
+ }
198752
+ if (this.bufferLength > 0) {
198753
+ return true;
198754
+ }
198755
+ const nextByte = this.stream.getByte();
198756
+ if (nextByte < 0) {
198757
+ return false;
198758
+ }
198759
+ this.buffer = nextByte;
198760
+ this.bufferLength = 8;
198761
+ return true;
198762
+ }
198763
+ readBits(n) {
198764
+ const { stream } = this;
198765
+ let { buffer, bufferLength } = this;
198766
+ if (n === 32) {
198767
+ if (bufferLength === 0) {
198768
+ return stream.getInt32() >>> 0;
198769
+ }
198770
+ buffer = buffer << 24 | stream.getByte() << 16 | stream.getByte() << 8 | stream.getByte();
198771
+ const nextByte = stream.getByte();
198772
+ this.buffer = nextByte & (1 << bufferLength) - 1;
198773
+ return (buffer << 8 - bufferLength | (nextByte & 255) >> bufferLength) >>> 0;
198774
+ }
198775
+ if (n === 8 && bufferLength === 0) {
198776
+ return stream.getByte();
198777
+ }
198778
+ while (bufferLength < n) {
198779
+ buffer = buffer << 8 | stream.getByte();
198780
+ bufferLength += 8;
198781
+ }
198782
+ bufferLength -= n;
198783
+ this.bufferLength = bufferLength;
198784
+ this.buffer = buffer & (1 << bufferLength) - 1;
198785
+ return buffer >> bufferLength;
198786
+ }
198787
+ align() {
198788
+ this.buffer = 0;
198789
+ this.bufferLength = 0;
198790
+ }
198791
+ readFlag() {
198792
+ return this.readBits(this.context.bitsPerFlag);
198793
+ }
198794
+ readCoordinate() {
198795
+ const { bitsPerCoordinate, decode: decode3 } = this.context;
198796
+ const xi = this.readBits(bitsPerCoordinate);
198797
+ const yi = this.readBits(bitsPerCoordinate);
198798
+ const scale2 = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) : 23283064365386963e-26;
198799
+ return [
198800
+ xi * scale2 * (decode3[1] - decode3[0]) + decode3[0],
198801
+ yi * scale2 * (decode3[3] - decode3[2]) + decode3[2]
198802
+ ];
198803
+ }
198804
+ readComponents() {
198805
+ const { bitsPerComponent, colorFn, colorSpace, decode: decode3, numComps } = this.context;
198806
+ const scale2 = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) : 23283064365386963e-26;
198807
+ const components22 = this.tmpCompsBuf;
198808
+ for (let i = 0, j = 4; i < numComps; i++, j += 2) {
198809
+ const ci = this.readBits(bitsPerComponent);
198810
+ components22[i] = ci * scale2 * (decode3[j + 1] - decode3[j]) + decode3[j];
198811
+ }
198812
+ const color5 = this.tmpCsCompsBuf;
198813
+ colorFn?.(components22, 0, color5, 0);
198814
+ return colorSpace.getRgb(color5, 0);
198815
+ }
198816
+ };
198817
+ var bCache = null;
198818
+ function getB(count) {
198819
+ if (bCache?.has(count)) return bCache.get(count);
198820
+ const values2 = Array.from({ length: count + 1 }, (_, i) => {
198821
+ const t = i / count, t_ = 1 - t;
198822
+ return new Float32Array([
198823
+ t_ ** 3,
198824
+ 3 * t * t_ ** 2,
198825
+ 3 * t ** 2 * t_,
198826
+ t ** 3
198827
+ ]);
198828
+ });
198829
+ (bCache ??= /* @__PURE__ */ new Map()).set(count, values2);
198830
+ return values2;
198831
+ }
198832
+ var MeshShading = class _MeshShading extends BaseShading {
198833
+ static MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;
198834
+ static MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;
198835
+ // Count of triangles per entire mesh bounds.
198836
+ static TRIANGLE_DENSITY = 20;
198837
+ constructor(shadingType, stream, context, rowVertices) {
198838
+ super();
198839
+ this.shadingType = shadingType;
198840
+ this.bbox = this.background = null;
198841
+ this.coords = [];
198842
+ this.colors = [];
198843
+ this.figures = [];
198844
+ const reader = new MeshStreamReader(stream, context);
198845
+ let patchMesh = false;
198846
+ switch (this.shadingType) {
198847
+ case ShadingType.FREE_FORM_MESH:
198848
+ this._decodeType4Shading(reader);
198849
+ break;
198850
+ case ShadingType.LATTICE_FORM_MESH:
198851
+ const verticesPerRow = rowVertices | 0;
198852
+ if (verticesPerRow < 2) {
198853
+ throw new FormatError("Invalid VerticesPerRow");
198854
+ }
198855
+ this._decodeType5Shading(reader, verticesPerRow);
198856
+ break;
198857
+ case ShadingType.COONS_PATCH_MESH:
198858
+ this._decodeType6Shading(reader);
198859
+ patchMesh = true;
198860
+ break;
198861
+ case ShadingType.TENSOR_PATCH_MESH:
198862
+ this._decodeType7Shading(reader);
198863
+ patchMesh = true;
198864
+ break;
198865
+ default:
198866
+ unreachable2("Unsupported mesh type.");
198867
+ break;
198868
+ }
198869
+ if (patchMesh) {
198870
+ this._updateBounds();
198871
+ for (let i = 0, ii = this.figures.length; i < ii; i++) {
198872
+ this._buildFigureFromPatch(i);
198873
+ }
198874
+ }
198875
+ this._updateBounds();
198876
+ this._packData();
198877
+ }
198878
+ _decodeType4Shading(reader) {
198879
+ const coords = this.coords;
198880
+ const colors2 = this.colors;
198881
+ const operators2 = [];
198882
+ const ps = [];
198883
+ let verticesLeft = 0;
198884
+ while (reader.hasData) {
198885
+ const f2 = reader.readFlag();
198886
+ const coord2 = reader.readCoordinate();
198887
+ const color5 = reader.readComponents();
198888
+ if (verticesLeft === 0) {
198889
+ if (!(0 <= f2 && f2 <= 2)) {
198890
+ throw new FormatError("Unknown type4 flag");
198891
+ }
198892
+ switch (f2) {
198893
+ case 0:
198894
+ verticesLeft = 3;
198895
+ break;
198896
+ case 1:
198897
+ ps.push(ps.at(-2), ps.at(-1));
198898
+ verticesLeft = 1;
198899
+ break;
198900
+ case 2:
198901
+ ps.push(ps.at(-3), ps.at(-1));
198902
+ verticesLeft = 1;
198903
+ break;
198904
+ }
198905
+ operators2.push(f2);
198906
+ }
198907
+ ps.push(coords.length);
198908
+ coords.push(coord2);
198909
+ colors2.push(color5);
198910
+ verticesLeft--;
198911
+ reader.align();
198912
+ }
198913
+ this.figures.push({
198914
+ type: MeshFigureType.TRIANGLES,
198915
+ coords: new Int32Array(ps),
198916
+ colors: new Int32Array(ps)
198917
+ });
198918
+ }
198919
+ _decodeType5Shading(reader, verticesPerRow) {
198920
+ const coords = this.coords;
198921
+ const colors2 = this.colors;
198922
+ const ps = [];
198923
+ while (reader.hasData) {
198924
+ const coord2 = reader.readCoordinate();
198925
+ const color5 = reader.readComponents();
198926
+ ps.push(coords.length);
198927
+ coords.push(coord2);
198928
+ colors2.push(color5);
198929
+ }
198930
+ this.figures.push({
198931
+ type: MeshFigureType.LATTICE,
198932
+ coords: new Int32Array(ps),
198933
+ colors: new Int32Array(ps),
198934
+ verticesPerRow
198935
+ });
198936
+ }
198937
+ _decodeType6Shading(reader) {
198938
+ const coords = this.coords;
198939
+ const colors2 = this.colors;
198940
+ const ps = new Int32Array(16);
198941
+ const cs = new Int32Array(4);
198942
+ while (reader.hasData) {
198943
+ const f2 = reader.readFlag();
198944
+ if (!(0 <= f2 && f2 <= 3)) {
198945
+ throw new FormatError("Unknown type6 flag");
198946
+ }
198947
+ const pi2 = coords.length;
198948
+ for (let i = 0, ii = f2 !== 0 ? 8 : 12; i < ii; i++) {
198949
+ coords.push(reader.readCoordinate());
198950
+ }
198951
+ const ci = colors2.length;
198952
+ for (let i = 0, ii = f2 !== 0 ? 2 : 4; i < ii; i++) {
198953
+ colors2.push(reader.readComponents());
198954
+ }
198955
+ let tmp1, tmp2, tmp3, tmp4;
198956
+ switch (f2) {
198957
+ // prettier-ignore
198958
+ case 0:
198959
+ ps[12] = pi2 + 3;
198960
+ ps[13] = pi2 + 4;
198961
+ ps[14] = pi2 + 5;
198962
+ ps[15] = pi2 + 6;
198963
+ ps[8] = pi2 + 2;
198964
+ ps[11] = pi2 + 7;
198965
+ ps[4] = pi2 + 1;
198966
+ ps[7] = pi2 + 8;
198967
+ ps[0] = pi2;
198968
+ ps[1] = pi2 + 11;
198969
+ ps[2] = pi2 + 10;
198970
+ ps[3] = pi2 + 9;
198971
+ cs[2] = ci + 1;
198972
+ cs[3] = ci + 2;
198973
+ cs[0] = ci;
198974
+ cs[1] = ci + 3;
198975
+ break;
198976
+ // prettier-ignore
198977
+ case 1:
198978
+ tmp1 = ps[12];
198979
+ tmp2 = ps[13];
198980
+ tmp3 = ps[14];
198981
+ tmp4 = ps[15];
198982
+ ps[12] = tmp4;
198983
+ ps[13] = pi2 + 0;
198984
+ ps[14] = pi2 + 1;
198985
+ ps[15] = pi2 + 2;
198986
+ ps[8] = tmp3;
198987
+ ps[11] = pi2 + 3;
198988
+ ps[4] = tmp2;
198989
+ ps[7] = pi2 + 4;
198990
+ ps[0] = tmp1;
198991
+ ps[1] = pi2 + 7;
198992
+ ps[2] = pi2 + 6;
198993
+ ps[3] = pi2 + 5;
198994
+ tmp1 = cs[2];
198995
+ tmp2 = cs[3];
198996
+ cs[2] = tmp2;
198997
+ cs[3] = ci;
198998
+ cs[0] = tmp1;
198999
+ cs[1] = ci + 1;
199000
+ break;
199001
+ // prettier-ignore
199002
+ case 2:
199003
+ tmp1 = ps[15];
199004
+ tmp2 = ps[11];
199005
+ ps[12] = ps[3];
199006
+ ps[13] = pi2 + 0;
199007
+ ps[14] = pi2 + 1;
199008
+ ps[15] = pi2 + 2;
199009
+ ps[8] = ps[7];
199010
+ ps[11] = pi2 + 3;
199011
+ ps[4] = tmp2;
199012
+ ps[7] = pi2 + 4;
199013
+ ps[0] = tmp1;
199014
+ ps[1] = pi2 + 7;
199015
+ ps[2] = pi2 + 6;
199016
+ ps[3] = pi2 + 5;
199017
+ tmp1 = cs[3];
199018
+ cs[2] = cs[1];
199019
+ cs[3] = ci;
199020
+ cs[0] = tmp1;
199021
+ cs[1] = ci + 1;
199022
+ break;
199023
+ // prettier-ignore
199024
+ case 3:
199025
+ ps[12] = ps[0];
199026
+ ps[13] = pi2 + 0;
199027
+ ps[14] = pi2 + 1;
199028
+ ps[15] = pi2 + 2;
199029
+ ps[8] = ps[1];
199030
+ ps[11] = pi2 + 3;
199031
+ ps[4] = ps[2];
199032
+ ps[7] = pi2 + 4;
199033
+ ps[0] = ps[3];
199034
+ ps[1] = pi2 + 7;
199035
+ ps[2] = pi2 + 6;
199036
+ ps[3] = pi2 + 5;
199037
+ cs[2] = cs[0];
199038
+ cs[3] = ci;
199039
+ cs[0] = cs[1];
199040
+ cs[1] = ci + 1;
199041
+ break;
199042
+ }
199043
+ ps[5] = coords.length;
199044
+ coords.push([
199045
+ (-4 * coords[ps[0]][0] - coords[ps[15]][0] + 6 * (coords[ps[4]][0] + coords[ps[1]][0]) - 2 * (coords[ps[12]][0] + coords[ps[3]][0]) + 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9,
199046
+ (-4 * coords[ps[0]][1] - coords[ps[15]][1] + 6 * (coords[ps[4]][1] + coords[ps[1]][1]) - 2 * (coords[ps[12]][1] + coords[ps[3]][1]) + 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9
199047
+ ]);
199048
+ ps[6] = coords.length;
199049
+ coords.push([
199050
+ (-4 * coords[ps[3]][0] - coords[ps[12]][0] + 6 * (coords[ps[2]][0] + coords[ps[7]][0]) - 2 * (coords[ps[0]][0] + coords[ps[15]][0]) + 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9,
199051
+ (-4 * coords[ps[3]][1] - coords[ps[12]][1] + 6 * (coords[ps[2]][1] + coords[ps[7]][1]) - 2 * (coords[ps[0]][1] + coords[ps[15]][1]) + 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9
199052
+ ]);
199053
+ ps[9] = coords.length;
199054
+ coords.push([
199055
+ (-4 * coords[ps[12]][0] - coords[ps[3]][0] + 6 * (coords[ps[8]][0] + coords[ps[13]][0]) - 2 * (coords[ps[0]][0] + coords[ps[15]][0]) + 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9,
199056
+ (-4 * coords[ps[12]][1] - coords[ps[3]][1] + 6 * (coords[ps[8]][1] + coords[ps[13]][1]) - 2 * (coords[ps[0]][1] + coords[ps[15]][1]) + 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9
199057
+ ]);
199058
+ ps[10] = coords.length;
199059
+ coords.push([
199060
+ (-4 * coords[ps[15]][0] - coords[ps[0]][0] + 6 * (coords[ps[11]][0] + coords[ps[14]][0]) - 2 * (coords[ps[12]][0] + coords[ps[3]][0]) + 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9,
199061
+ (-4 * coords[ps[15]][1] - coords[ps[0]][1] + 6 * (coords[ps[11]][1] + coords[ps[14]][1]) - 2 * (coords[ps[12]][1] + coords[ps[3]][1]) + 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9
199062
+ ]);
199063
+ this.figures.push({
199064
+ type: MeshFigureType.PATCH,
199065
+ coords: new Int32Array(ps),
199066
+ // making copies of ps and cs
199067
+ colors: new Int32Array(cs)
199068
+ });
199069
+ }
199070
+ }
199071
+ _decodeType7Shading(reader) {
199072
+ const coords = this.coords;
199073
+ const colors2 = this.colors;
199074
+ const ps = new Int32Array(16);
199075
+ const cs = new Int32Array(4);
199076
+ while (reader.hasData) {
199077
+ const f2 = reader.readFlag();
199078
+ if (!(0 <= f2 && f2 <= 3)) {
199079
+ throw new FormatError("Unknown type7 flag");
199080
+ }
199081
+ const pi2 = coords.length;
199082
+ for (let i = 0, ii = f2 !== 0 ? 12 : 16; i < ii; i++) {
199083
+ coords.push(reader.readCoordinate());
199084
+ }
199085
+ const ci = colors2.length;
199086
+ for (let i = 0, ii = f2 !== 0 ? 2 : 4; i < ii; i++) {
199087
+ colors2.push(reader.readComponents());
199088
+ }
199089
+ let tmp1, tmp2, tmp3, tmp4;
199090
+ switch (f2) {
199091
+ // prettier-ignore
199092
+ case 0:
199093
+ ps[12] = pi2 + 3;
199094
+ ps[13] = pi2 + 4;
199095
+ ps[14] = pi2 + 5;
199096
+ ps[15] = pi2 + 6;
199097
+ ps[8] = pi2 + 2;
199098
+ ps[9] = pi2 + 13;
199099
+ ps[10] = pi2 + 14;
199100
+ ps[11] = pi2 + 7;
199101
+ ps[4] = pi2 + 1;
199102
+ ps[5] = pi2 + 12;
199103
+ ps[6] = pi2 + 15;
199104
+ ps[7] = pi2 + 8;
199105
+ ps[0] = pi2;
199106
+ ps[1] = pi2 + 11;
199107
+ ps[2] = pi2 + 10;
199108
+ ps[3] = pi2 + 9;
199109
+ cs[2] = ci + 1;
199110
+ cs[3] = ci + 2;
199111
+ cs[0] = ci;
199112
+ cs[1] = ci + 3;
199113
+ break;
199114
+ // prettier-ignore
199115
+ case 1:
199116
+ tmp1 = ps[12];
199117
+ tmp2 = ps[13];
199118
+ tmp3 = ps[14];
199119
+ tmp4 = ps[15];
199120
+ ps[12] = tmp4;
199121
+ ps[13] = pi2 + 0;
199122
+ ps[14] = pi2 + 1;
199123
+ ps[15] = pi2 + 2;
199124
+ ps[8] = tmp3;
199125
+ ps[9] = pi2 + 9;
199126
+ ps[10] = pi2 + 10;
199127
+ ps[11] = pi2 + 3;
199128
+ ps[4] = tmp2;
199129
+ ps[5] = pi2 + 8;
199130
+ ps[6] = pi2 + 11;
199131
+ ps[7] = pi2 + 4;
199132
+ ps[0] = tmp1;
199133
+ ps[1] = pi2 + 7;
199134
+ ps[2] = pi2 + 6;
199135
+ ps[3] = pi2 + 5;
199136
+ tmp1 = cs[2];
199137
+ tmp2 = cs[3];
199138
+ cs[2] = tmp2;
199139
+ cs[3] = ci;
199140
+ cs[0] = tmp1;
199141
+ cs[1] = ci + 1;
199142
+ break;
199143
+ // prettier-ignore
199144
+ case 2:
199145
+ tmp1 = ps[15];
199146
+ tmp2 = ps[11];
199147
+ ps[12] = ps[3];
199148
+ ps[13] = pi2 + 0;
199149
+ ps[14] = pi2 + 1;
199150
+ ps[15] = pi2 + 2;
199151
+ ps[8] = ps[7];
199152
+ ps[9] = pi2 + 9;
199153
+ ps[10] = pi2 + 10;
199154
+ ps[11] = pi2 + 3;
199155
+ ps[4] = tmp2;
199156
+ ps[5] = pi2 + 8;
199157
+ ps[6] = pi2 + 11;
199158
+ ps[7] = pi2 + 4;
199159
+ ps[0] = tmp1;
199160
+ ps[1] = pi2 + 7;
199161
+ ps[2] = pi2 + 6;
199162
+ ps[3] = pi2 + 5;
199163
+ tmp1 = cs[3];
199164
+ cs[2] = cs[1];
199165
+ cs[3] = ci;
199166
+ cs[0] = tmp1;
199167
+ cs[1] = ci + 1;
199168
+ break;
199169
+ // prettier-ignore
199170
+ case 3:
199171
+ ps[12] = ps[0];
199172
+ ps[13] = pi2 + 0;
199173
+ ps[14] = pi2 + 1;
199174
+ ps[15] = pi2 + 2;
199175
+ ps[8] = ps[1];
199176
+ ps[9] = pi2 + 9;
199177
+ ps[10] = pi2 + 10;
199178
+ ps[11] = pi2 + 3;
199179
+ ps[4] = ps[2];
199180
+ ps[5] = pi2 + 8;
199181
+ ps[6] = pi2 + 11;
199182
+ ps[7] = pi2 + 4;
199183
+ ps[0] = ps[3];
199184
+ ps[1] = pi2 + 7;
199185
+ ps[2] = pi2 + 6;
199186
+ ps[3] = pi2 + 5;
199187
+ cs[2] = cs[0];
199188
+ cs[3] = ci;
199189
+ cs[0] = cs[1];
199190
+ cs[1] = ci + 1;
199191
+ break;
199192
+ }
199193
+ this.figures.push({
199194
+ type: MeshFigureType.PATCH,
199195
+ coords: new Int32Array(ps),
199196
+ // making copies of ps and cs
199197
+ colors: new Int32Array(cs)
199198
+ });
199199
+ }
199200
+ }
199201
+ _buildFigureFromPatch(index2) {
199202
+ const figure = this.figures[index2];
199203
+ assert2(
199204
+ figure.type === MeshFigureType.PATCH,
199205
+ "Unexpected patch mesh figure"
199206
+ );
199207
+ const coords = this.coords, colors2 = this.colors;
199208
+ const pi2 = figure.coords;
199209
+ const ci = figure.colors;
199210
+ const figureMinX = Math.min(
199211
+ coords[pi2[0]][0],
199212
+ coords[pi2[3]][0],
199213
+ coords[pi2[12]][0],
199214
+ coords[pi2[15]][0]
199215
+ );
199216
+ const figureMinY = Math.min(
199217
+ coords[pi2[0]][1],
199218
+ coords[pi2[3]][1],
199219
+ coords[pi2[12]][1],
199220
+ coords[pi2[15]][1]
199221
+ );
199222
+ const figureMaxX = Math.max(
199223
+ coords[pi2[0]][0],
199224
+ coords[pi2[3]][0],
199225
+ coords[pi2[12]][0],
199226
+ coords[pi2[15]][0]
199227
+ );
199228
+ const figureMaxY = Math.max(
199229
+ coords[pi2[0]][1],
199230
+ coords[pi2[3]][1],
199231
+ coords[pi2[12]][1],
199232
+ coords[pi2[15]][1]
199233
+ );
199234
+ let splitXBy = Math.ceil(
199235
+ (figureMaxX - figureMinX) * _MeshShading.TRIANGLE_DENSITY / (this.bounds[2] - this.bounds[0])
199236
+ );
199237
+ splitXBy = MathClamp(
199238
+ splitXBy,
199239
+ _MeshShading.MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
199240
+ _MeshShading.MAX_SPLIT_PATCH_CHUNKS_AMOUNT
199241
+ );
199242
+ let splitYBy = Math.ceil(
199243
+ (figureMaxY - figureMinY) * _MeshShading.TRIANGLE_DENSITY / (this.bounds[3] - this.bounds[1])
199244
+ );
199245
+ splitYBy = MathClamp(
199246
+ splitYBy,
199247
+ _MeshShading.MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
199248
+ _MeshShading.MAX_SPLIT_PATCH_CHUNKS_AMOUNT
199249
+ );
199250
+ const verticesPerRow = splitXBy + 1;
199251
+ const figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);
199252
+ const figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
199253
+ let k = 0;
199254
+ const cl = new Uint8Array(3), cr = new Uint8Array(3);
199255
+ const c0 = colors2[ci[0]], c1 = colors2[ci[1]], c22 = colors2[ci[2]], c32 = colors2[ci[3]];
199256
+ const bRow = getB(splitYBy), bCol = getB(splitXBy);
199257
+ for (let row = 0; row <= splitYBy; row++) {
199258
+ cl[0] = (c0[0] * (splitYBy - row) + c22[0] * row) / splitYBy | 0;
199259
+ cl[1] = (c0[1] * (splitYBy - row) + c22[1] * row) / splitYBy | 0;
199260
+ cl[2] = (c0[2] * (splitYBy - row) + c22[2] * row) / splitYBy | 0;
199261
+ cr[0] = (c1[0] * (splitYBy - row) + c32[0] * row) / splitYBy | 0;
199262
+ cr[1] = (c1[1] * (splitYBy - row) + c32[1] * row) / splitYBy | 0;
199263
+ cr[2] = (c1[2] * (splitYBy - row) + c32[2] * row) / splitYBy | 0;
199264
+ for (let col = 0; col <= splitXBy; col++, k++) {
199265
+ if ((row === 0 || row === splitYBy) && (col === 0 || col === splitXBy)) {
199266
+ continue;
199267
+ }
199268
+ let x = 0, y = 0;
199269
+ let q2 = 0;
199270
+ for (let i = 0; i <= 3; i++) {
199271
+ for (let j = 0; j <= 3; j++, q2++) {
199272
+ const m = bRow[row][i] * bCol[col][j];
199273
+ x += coords[pi2[q2]][0] * m;
199274
+ y += coords[pi2[q2]][1] * m;
199275
+ }
199276
+ }
199277
+ figureCoords[k] = coords.length;
199278
+ coords.push([x, y]);
199279
+ figureColors[k] = colors2.length;
199280
+ const newColor = new Uint8Array(3);
199281
+ newColor[0] = (cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy | 0;
199282
+ newColor[1] = (cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy | 0;
199283
+ newColor[2] = (cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy | 0;
199284
+ colors2.push(newColor);
199285
+ }
199286
+ }
199287
+ figureCoords[0] = pi2[0];
199288
+ figureColors[0] = ci[0];
199289
+ figureCoords[splitXBy] = pi2[3];
199290
+ figureColors[splitXBy] = ci[1];
199291
+ figureCoords[verticesPerRow * splitYBy] = pi2[12];
199292
+ figureColors[verticesPerRow * splitYBy] = ci[2];
199293
+ figureCoords[verticesPerRow * splitYBy + splitXBy] = pi2[15];
199294
+ figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];
199295
+ this.figures[index2] = {
199296
+ type: MeshFigureType.LATTICE,
199297
+ coords: figureCoords,
199298
+ colors: figureColors,
199299
+ verticesPerRow
199300
+ };
199301
+ }
199302
+ _updateBounds() {
199303
+ meshUpdateBounds(this);
199304
+ }
199305
+ _packData() {
199306
+ meshPackData(this);
199307
+ }
199308
+ getIR() {
199309
+ const { posData, colData, vertexCount } = buildMeshVertexData(
199310
+ this.coords,
199311
+ this.colors,
199312
+ this.figures
199313
+ );
199314
+ return [
199315
+ "Mesh",
199316
+ this.shadingType,
199317
+ posData,
199318
+ colData,
199319
+ vertexCount,
199320
+ this.bounds,
199321
+ this.bbox,
199322
+ this.background
199323
+ ];
199324
+ }
199325
+ };
196019
199326
  var PdfError2 = class extends Error {
196020
199327
  constructor(code, message) {
196021
199328
  super(message);
@@ -198921,11 +202228,16 @@ function parseDictionaryStream(dictNode, lexer, bytes) {
198921
202228
  let streamEnd = streamStart;
198922
202229
  if (resolvedLength !== void 0 && resolvedLength >= 0 && streamStart + resolvedLength <= bytes.length) {
198923
202230
  const candidateEnd = streamStart + resolvedLength;
198924
- const tailSlice = bytes.subarray(candidateEnd, Math.min(bytes.length, candidateEnd + 32));
198925
- const tailStr = new TextDecoder("latin1").decode(tailSlice);
198926
- if (tailStr.includes("endstream")) {
202231
+ const tailLexer = new CosByteLexer(bytes, candidateEnd);
202232
+ let endToken;
202233
+ try {
202234
+ endToken = tailLexer.nextToken();
202235
+ } catch (error2) {
202236
+ if (!(error2 instanceof PdfError2) || error2.code !== "E_PARSE") throw error2;
202237
+ }
202238
+ if (endToken?.kind === "keyword" && endToken.value === "endstream") {
198927
202239
  rawStreamBytes = bytes.subarray(streamStart, candidateEnd);
198928
- streamEnd = candidateEnd + tailStr.indexOf("endstream") + "endstream".length;
202240
+ streamEnd = tailLexer.offset;
198929
202241
  }
198930
202242
  }
198931
202243
  if (!rawStreamBytes) {
@@ -207095,6 +210407,25 @@ var __webpack_exports__JpxImage = __webpack_exports__.JpxImage;
207095
210407
  var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel;
207096
210408
  var __webpack_exports__getVerbosityLevel = __webpack_exports__.getVerbosityLevel;
207097
210409
  var __webpack_exports__setVerbosityLevel = __webpack_exports__.setVerbosityLevel;
210410
+ function createCalibratedColorSpace(doc, family, parameters) {
210411
+ const dict = doc.resolveDict(parameters);
210412
+ const array = (key) => {
210413
+ const value3 = dict ? doc.resolveArray(dictGet(dict, key)) : void 0;
210414
+ return value3?.items.map((item) => {
210415
+ const number5 = doc.resolve(item);
210416
+ return number5?.kind === "number" ? number5.value : 0;
210417
+ });
210418
+ };
210419
+ const whitePoint = array("WhitePoint") ?? [0.95047, 1, 1.08883];
210420
+ const blackPoint = array("BlackPoint");
210421
+ if (family === "CalGray") {
210422
+ const gamma2 = dict ? doc.resolve(dictGet(dict, "Gamma")) : void 0;
210423
+ return new CalGrayCS(whitePoint, blackPoint, gamma2?.kind === "number" ? gamma2.value : void 0);
210424
+ }
210425
+ if (family === "CalRGB") return new CalRGBCS(whitePoint, blackPoint, array("Gamma"), array("Matrix"));
210426
+ return new LabCS(whitePoint, blackPoint, array("Range"));
210427
+ }
210428
+ var cmykColorSpace = new DeviceCmykCS();
207098
210429
  function resolveColorSpaceInfo(doc, csNode, resourcesDict) {
207099
210430
  if (!csNode) return { colorSpace: "rgb", colorSpaceLabel: "rgb", components: 3 };
207100
210431
  const resolved = doc.resolve(csNode);
@@ -207135,7 +210466,7 @@ function resolveColorSpaceInfo(doc, csNode, resourcesDict) {
207135
210466
  palette2 = lookupNode.bytes;
207136
210467
  }
207137
210468
  let resolvedBaseComp = baseInfo.components;
207138
- if (palette2 && (baseInfo.isLab || baseInfo.isSeparation || baseInfo.isDeviceN || baseInfo.calRgbGamma !== void 0 || baseInfo.calGrayGamma !== void 0)) {
210469
+ if (palette2 && (baseInfo.isSeparation || baseInfo.isDeviceN || baseInfo.calibrated !== void 0)) {
207139
210470
  const numEntries = Math.max(1, Math.min(hival + 1, Math.floor(palette2.length / Math.max(1, baseInfo.components))));
207140
210471
  const rgbaPal = decodeSamplesToRgba(palette2, numEntries, 1, 8, baseInfo);
207141
210472
  const rgbPal = new Uint8Array(numEntries * 3);
@@ -207165,74 +210496,21 @@ function resolveColorSpaceInfo(doc, csNode, resourcesDict) {
207165
210496
  }
207166
210497
  return { colorSpace: "rgb", colorSpaceLabel: "icc", components: 3 };
207167
210498
  }
207168
- if (kindName === "CalGray") {
207169
- const calDict = doc.resolveDict(resolved.items[1]);
207170
- const gammaNode = calDict ? doc.resolve(dictGet(calDict, "Gamma")) : void 0;
207171
- const gamma2 = gammaNode?.kind === "number" && gammaNode.value > 0 ? gammaNode.value : 1;
207172
- return { colorSpace: "gray", colorSpaceLabel: "cal-gray", components: 1, calGrayGamma: gamma2 };
207173
- }
207174
- if (kindName === "CalRGB") {
207175
- const calDict = doc.resolveDict(resolved.items[1]);
207176
- const gammaArr = calDict ? doc.resolveArray(dictGet(calDict, "Gamma")) : void 0;
207177
- let calRgbGamma = [1, 1, 1];
207178
- if (gammaArr && gammaArr.items.length >= 3) {
207179
- const gNums = gammaArr.items.slice(0, 3).map((it) => {
207180
- const r = doc.resolve(it);
207181
- return r?.kind === "number" && r.value > 0 ? r.value : 1;
207182
- });
207183
- calRgbGamma = [gNums[0], gNums[1], gNums[2]];
207184
- }
207185
- const matArr = calDict ? doc.resolveArray(dictGet(calDict, "Matrix")) : void 0;
207186
- let calRgbMatrix;
207187
- if (matArr && matArr.items.length >= 9) {
207188
- calRgbMatrix = matArr.items.slice(0, 9).map((it) => {
207189
- const r = doc.resolve(it);
207190
- return r?.kind === "number" ? r.value : 0;
207191
- });
207192
- }
210499
+ if (kindName === "CalGray" || kindName === "CalRGB" || kindName === "Lab") {
210500
+ const calibrated = createCalibratedColorSpace(doc, kindName, resolved.items[1]);
207193
210501
  return {
207194
- colorSpace: "rgb",
207195
- colorSpaceLabel: "cal-rgb",
207196
- components: 3,
207197
- calRgbGamma,
207198
- calRgbMatrix
210502
+ colorSpace: kindName === "CalGray" ? "gray" : "rgb",
210503
+ colorSpaceLabel: kindName === "CalGray" ? "cal-gray" : kindName === "CalRGB" ? "cal-rgb" : "lab",
210504
+ components: kindName === "CalGray" ? 1 : 3,
210505
+ calibrated
207199
210506
  };
207200
210507
  }
207201
- if (kindName === "Lab") {
207202
- const labDict = doc.resolveDict(resolved.items[1]);
207203
- const rangeArr = labDict ? doc.resolveArray(dictGet(labDict, "Range")) : void 0;
207204
- let labRange = [-100, 100, -100, 100];
207205
- if (rangeArr && rangeArr.items.length >= 4) {
207206
- const nums = rangeArr.items.slice(0, 4).map((it) => {
207207
- const r = doc.resolve(it);
207208
- return r?.kind === "number" ? r.value : 0;
207209
- });
207210
- labRange = [nums[0], nums[1], nums[2], nums[3]];
207211
- }
207212
- return { colorSpace: "rgb", colorSpaceLabel: "lab", components: 3, isLab: true, labRange };
207213
- }
207214
210508
  if (kindName === "Separation" || kindName === "DeviceN") {
207215
210509
  const isDevN = kindName === "DeviceN";
207216
210510
  const namesArr = isDevN ? doc.resolveArray(resolved.items[1]) : void 0;
207217
210511
  const devNComponents = isDevN && namesArr ? Math.max(1, namesArr.items.length) : 1;
207218
210512
  const altInfo = resolveColorSpaceInfo(doc, resolved.items[2], resourcesDict);
207219
210513
  const altSpace = altInfo.colorSpace === "cmyk" ? "cmyk" : altInfo.colorSpace === "gray" ? "gray" : "rgb";
207220
- const fnResolved = doc.resolve(resolved.items[3]);
207221
- const fnDict = fnResolved?.kind === "stream" ? fnResolved.dict : fnResolved?.kind === "dict" ? fnResolved : void 0;
207222
- const ftNode = fnDict ? doc.resolve(dictGet(fnDict, "FunctionType")) : void 0;
207223
- const tintFunctionType = ftNode?.kind === "number" ? ftNode.value : 2;
207224
- const c0Arr = fnDict ? doc.resolveArray(dictGet(fnDict, "C0")) : void 0;
207225
- const c1Arr = fnDict ? doc.resolveArray(dictGet(fnDict, "C1")) : void 0;
207226
- const nNode = fnDict ? doc.resolve(dictGet(fnDict, "N")) : void 0;
207227
- const c0 = c0Arr ? c0Arr.items.map((it) => {
207228
- const r = doc.resolve(it);
207229
- return r?.kind === "number" ? r.value : 0;
207230
- }) : altSpace === "cmyk" ? [0, 0, 0, 0] : altSpace === "gray" ? [1] : [1, 1, 1];
207231
- const c1 = c1Arr ? c1Arr.items.map((it) => {
207232
- const r = doc.resolve(it);
207233
- return r?.kind === "number" ? r.value : 0;
207234
- }) : altSpace === "cmyk" ? [0, 0, 0, 1] : altSpace === "gray" ? [0] : [0, 0, 0];
207235
- const sepN = nNode?.kind === "number" && nNode.value > 0 ? nNode.value : 1;
207236
210514
  return {
207237
210515
  colorSpace: altSpace,
207238
210516
  colorSpaceLabel: isDevN ? "devn" : "sep",
@@ -207240,12 +210518,9 @@ function resolveColorSpaceInfo(doc, csNode, resourcesDict) {
207240
210518
  isSeparation: !isDevN,
207241
210519
  isDeviceN: isDevN,
207242
210520
  separationAltSpace: altSpace,
207243
- separationC0: c0,
207244
- separationC1: c1,
207245
- separationN: sepN,
210521
+ alternateCalibrated: altInfo.calibrated,
207246
210522
  tintFunctionDoc: doc,
207247
- tintFunctionNode: resolved.items[3],
207248
- tintFunctionType
210523
+ tintFunctionNode: resolved.items[3]
207249
210524
  };
207250
210525
  }
207251
210526
  }
@@ -207395,141 +210670,55 @@ function decodeSamplesToRgba(rawSamples, width2, height, bpc, csInfo, alphaSampl
207395
210670
  const rgba = new Uint8Array(width2 * height * 4);
207396
210671
  const pixelCount = width2 * height;
207397
210672
  if (csInfo.isSeparation || csInfo.isDeviceN) {
207398
- const c0 = csInfo.separationC0 ?? [1, 1, 1];
207399
- const c1 = csInfo.separationC1 ?? [0, 0, 0];
207400
- const expN = csInfo.separationN ?? 1;
207401
210673
  const alt = csInfo.separationAltSpace ?? "rgb";
207402
210674
  const numCh = Math.max(1, csInfo.components);
207403
210675
  const step = bpc === 16 ? 2 : 1;
207404
- const useGenericTintFn = csInfo.tintFunctionDoc !== void 0 && csInfo.tintFunctionNode !== void 0 && (csInfo.tintFunctionType === 0 || csInfo.tintFunctionType === 3 || csInfo.tintFunctionType === 4);
207405
210676
  for (let p2 = 0; p2 < pixelCount; p2++) {
207406
210677
  const chVals = [];
207407
- let wSum = 0;
207408
210678
  for (let ch3 = 0; ch3 < numCh; ch3++) {
207409
210679
  const sRaw = (rawSamples[(p2 * numCh + ch3) * step] ?? 0) / 255;
207410
- const tRemapped = remapUnitSampleWithDecode(sRaw, ch3, decodePairs);
207411
- chVals.push(tRemapped);
207412
- wSum += Math.pow(Math.max(0, Math.min(1, tRemapped)), expN);
207413
- }
207414
- if (useGenericTintFn) {
207415
- const outComps = evalShadingFunctionToComponents(
207416
- csInfo.tintFunctionDoc,
207417
- csInfo.tintFunctionNode,
207418
- chVals
207419
- );
207420
- if (alt === "cmyk") {
207421
- const c4 = outComps[0] ?? 0;
207422
- const m = outComps[1] ?? 0;
207423
- const y = outComps[2] ?? 0;
207424
- const k = outComps[3] ?? 0;
207425
- rgba[p2 * 4] = Math.round(Math.max(0, Math.min(1, (1 - c4) * (1 - k))) * 255);
207426
- rgba[p2 * 4 + 1] = Math.round(Math.max(0, Math.min(1, (1 - m) * (1 - k))) * 255);
207427
- rgba[p2 * 4 + 2] = Math.round(Math.max(0, Math.min(1, (1 - y) * (1 - k))) * 255);
207428
- } else if (alt === "gray") {
207429
- const gByte = Math.round(Math.max(0, Math.min(1, outComps[0] ?? 0)) * 255);
207430
- rgba[p2 * 4] = gByte;
207431
- rgba[p2 * 4 + 1] = gByte;
207432
- rgba[p2 * 4 + 2] = gByte;
207433
- } else {
207434
- rgba[p2 * 4] = Math.round(Math.max(0, Math.min(1, outComps[0] ?? 0)) * 255);
207435
- rgba[p2 * 4 + 1] = Math.round(Math.max(0, Math.min(1, outComps[1] ?? 0)) * 255);
207436
- rgba[p2 * 4 + 2] = Math.round(Math.max(0, Math.min(1, outComps[2] ?? 0)) * 255);
207437
- }
207438
- rgba[p2 * 4 + 3] = 255;
207439
- continue;
210680
+ chVals.push(remapUnitSampleWithDecode(sRaw, ch3, decodePairs));
207440
210681
  }
207441
- const w = Math.max(0, Math.min(1, wSum));
207442
- if (alt === "cmyk") {
207443
- const c4 = (c0[0] ?? 0) + w * ((c1[0] ?? 0) - (c0[0] ?? 0));
207444
- const m = (c0[1] ?? 0) + w * ((c1[1] ?? 0) - (c0[1] ?? 0));
207445
- const y = (c0[2] ?? 0) + w * ((c1[2] ?? 0) - (c0[2] ?? 0));
207446
- const k = (c0[3] ?? 0) + w * ((c1[3] ?? 1) - (c0[3] ?? 0));
207447
- rgba[p2 * 4] = Math.round(Math.max(0, Math.min(1, (1 - c4) * (1 - k))) * 255);
207448
- rgba[p2 * 4 + 1] = Math.round(Math.max(0, Math.min(1, (1 - m) * (1 - k))) * 255);
207449
- rgba[p2 * 4 + 2] = Math.round(Math.max(0, Math.min(1, (1 - y) * (1 - k))) * 255);
210682
+ const outComps = evalShadingFunctionToComponents(
210683
+ csInfo.tintFunctionDoc,
210684
+ csInfo.tintFunctionNode,
210685
+ chVals
210686
+ );
210687
+ if (csInfo.alternateCalibrated) {
210688
+ rgba.set(csInfo.alternateCalibrated.getRgb(outComps, 0), p2 * 4);
210689
+ } else if (alt === "cmyk") {
210690
+ rgba.set(cmykColorSpace.getRgb([outComps[0] ?? 0, outComps[1] ?? 0, outComps[2] ?? 0, outComps[3] ?? 0], 0), p2 * 4);
207450
210691
  } else if (alt === "gray") {
207451
- const gVal = (c0[0] ?? 1) + w * ((c1[0] ?? 0) - (c0[0] ?? 1));
207452
- const gByte = Math.round(Math.max(0, Math.min(1, gVal)) * 255);
210692
+ const gByte = Math.round(Math.max(0, Math.min(1, outComps[0] ?? 0)) * 255);
207453
210693
  rgba[p2 * 4] = gByte;
207454
210694
  rgba[p2 * 4 + 1] = gByte;
207455
210695
  rgba[p2 * 4 + 2] = gByte;
207456
210696
  } else {
207457
- const rVal = (c0[0] ?? 1) + w * ((c1[0] ?? 0) - (c0[0] ?? 1));
207458
- const gVal = (c0[1] ?? 1) + w * ((c1[1] ?? 0) - (c0[1] ?? 1));
207459
- const bVal = (c0[2] ?? 1) + w * ((c1[2] ?? 0) - (c0[2] ?? 1));
207460
- rgba[p2 * 4] = Math.round(Math.max(0, Math.min(1, rVal)) * 255);
207461
- rgba[p2 * 4 + 1] = Math.round(Math.max(0, Math.min(1, gVal)) * 255);
207462
- rgba[p2 * 4 + 2] = Math.round(Math.max(0, Math.min(1, bVal)) * 255);
210697
+ rgba[p2 * 4] = Math.round(Math.max(0, Math.min(1, outComps[0] ?? 0)) * 255);
210698
+ rgba[p2 * 4 + 1] = Math.round(Math.max(0, Math.min(1, outComps[1] ?? 0)) * 255);
210699
+ rgba[p2 * 4 + 2] = Math.round(Math.max(0, Math.min(1, outComps[2] ?? 0)) * 255);
207463
210700
  }
207464
210701
  rgba[p2 * 4 + 3] = 255;
207465
210702
  }
207466
- } else if (csInfo.isLab) {
207467
- const [amin, amax, bmin, bmax] = csInfo.labRange ?? [-100, 100, -100, 100];
207468
- const invF = (t) => t > 6 / 29 ? t * t * t : 3 * (6 / 29) * (6 / 29) * (t - 4 / 29);
207469
- const toSrgb = (u) => {
207470
- const c4 = u <= 31308e-7 ? 12.92 * u : 1.055 * Math.pow(u, 1 / 2.4) - 0.055;
207471
- return Math.round(Math.max(0, Math.min(1, c4)) * 255);
207472
- };
210703
+ } else if (csInfo.calibrated?.name === "Lab") {
210704
+ const { amin, amax, bmin, bmax } = csInfo.calibrated;
210705
+ const step = bpc === 16 ? 2 : 1;
207473
210706
  for (let p2 = 0; p2 < pixelCount; p2++) {
207474
- const s0 = (rawSamples[p2 * 3] ?? 0) / 255;
207475
- const s1 = (rawSamples[p2 * 3 + 1] ?? 128) / 255;
207476
- const s2 = (rawSamples[p2 * 3 + 2] ?? 128) / 255;
207477
- const L = s0 * 100;
207478
- if (L <= 0.01) {
207479
- rgba[p2 * 4] = 0;
207480
- rgba[p2 * 4 + 1] = 0;
207481
- rgba[p2 * 4 + 2] = 0;
207482
- rgba[p2 * 4 + 3] = 255;
207483
- continue;
207484
- }
207485
- const a3 = amin + s1 * (amax - amin);
207486
- const b3 = bmin + s2 * (bmax - bmin);
207487
- const fy = (L + 16) / 116;
207488
- const fx = fy + a3 / 500;
207489
- const fz = fy - b3 / 200;
207490
- const X = 0.95047 * invF(fx);
207491
- const Y = 1 * invF(fy);
207492
- const Z = 1.08883 * invF(fz);
207493
- const linR = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
207494
- const linG = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
207495
- const linB = X * 0.0557 + Y * -0.204 + Z * 1.057;
207496
- rgba[p2 * 4] = toSrgb(linR);
207497
- rgba[p2 * 4 + 1] = toSrgb(linG);
207498
- rgba[p2 * 4 + 2] = toSrgb(linB);
210707
+ const L = (rawSamples[p2 * 3 * step] ?? 0) / 255 * 100;
210708
+ const a3 = amin + (rawSamples[(p2 * 3 + 1) * step] ?? 128) / 255 * (amax - amin);
210709
+ const b3 = bmin + (rawSamples[(p2 * 3 + 2) * step] ?? 128) / 255 * (bmax - bmin);
210710
+ rgba.set(csInfo.calibrated.getRgb([L, a3, b3], 0), p2 * 4);
207499
210711
  rgba[p2 * 4 + 3] = 255;
207500
210712
  }
207501
210713
  } else if (csInfo.colorSpace === "rgb") {
207502
- const hasCalRgb = Boolean(csInfo.calRgbGamma || csInfo.calRgbMatrix);
207503
- const toSrgbByte = (u) => {
207504
- const c4 = u <= 31308e-7 ? 12.92 * u : 1.055 * Math.pow(u, 1 / 2.4) - 0.055;
207505
- return Math.round(Math.max(0, Math.min(1, c4)) * 255);
207506
- };
207507
210714
  const writeRgbPixel = (p2, rByte, gByte, bByte) => {
207508
- let rU = remapUnitSampleWithDecode(rByte / 255, 0, decodePairs);
207509
- let gU = remapUnitSampleWithDecode(gByte / 255, 1, decodePairs);
207510
- let bU = remapUnitSampleWithDecode(bByte / 255, 2, decodePairs);
207511
- if (hasCalRgb) {
207512
- const [gr, gg, gb] = csInfo.calRgbGamma ?? [1, 1, 1];
207513
- const ag = Math.pow(rU, gr);
207514
- const bg = Math.pow(gU, gg);
207515
- const cg = Math.pow(bU, gb);
207516
- if (csInfo.calRgbMatrix && csInfo.calRgbMatrix.length >= 9) {
207517
- const m = csInfo.calRgbMatrix;
207518
- const X = m[0] * ag + m[3] * bg + m[6] * cg;
207519
- const Y = m[1] * ag + m[4] * bg + m[7] * cg;
207520
- const Z = m[2] * ag + m[5] * bg + m[8] * cg;
207521
- const linR = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
207522
- const linG = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
207523
- const linB = X * 0.0557 + Y * -0.204 + Z * 1.057;
207524
- rgba[p2 * 4] = toSrgbByte(linR);
207525
- rgba[p2 * 4 + 1] = toSrgbByte(linG);
207526
- rgba[p2 * 4 + 2] = toSrgbByte(linB);
207527
- rgba[p2 * 4 + 3] = 255;
207528
- return;
207529
- }
207530
- rU = ag;
207531
- gU = bg;
207532
- bU = cg;
210715
+ const rU = remapUnitSampleWithDecode(rByte / 255, 0, decodePairs);
210716
+ const gU = remapUnitSampleWithDecode(gByte / 255, 1, decodePairs);
210717
+ const bU = remapUnitSampleWithDecode(bByte / 255, 2, decodePairs);
210718
+ if (csInfo.calibrated) {
210719
+ rgba.set(csInfo.calibrated.getRgb([rU, gU, bU], 0), p2 * 4);
210720
+ rgba[p2 * 4 + 3] = 255;
210721
+ return;
207533
210722
  }
207534
210723
  rgba[p2 * 4] = Math.round(rU * 255);
207535
210724
  rgba[p2 * 4 + 1] = Math.round(gU * 255);
@@ -207549,10 +210738,11 @@ function decodeSamplesToRgba(rawSamples, width2, height, bpc, csInfo, alphaSampl
207549
210738
  }
207550
210739
  } else if (csInfo.colorSpace === "gray") {
207551
210740
  const writeGrayPixel = (p2, gByte) => {
207552
- let gU = remapUnitSampleWithDecode(gByte / 255, 0, decodePairs);
207553
- if (csInfo.calGrayGamma && csInfo.calGrayGamma !== 1) {
207554
- const lin = Math.pow(gU, csInfo.calGrayGamma);
207555
- gU = lin <= 31308e-7 ? 12.92 * lin : 1.055 * Math.pow(lin, 1 / 2.4) - 0.055;
210741
+ const gU = remapUnitSampleWithDecode(gByte / 255, 0, decodePairs);
210742
+ if (csInfo.calibrated) {
210743
+ rgba.set(csInfo.calibrated.getRgb([gU], 0), p2 * 4);
210744
+ rgba[p2 * 4 + 3] = 255;
210745
+ return;
207556
210746
  }
207557
210747
  const outG = Math.round(Math.max(0, Math.min(1, gU)) * 255);
207558
210748
  rgba[p2 * 4] = outG;
@@ -207608,9 +210798,7 @@ function decodeSamplesToRgba(rawSamples, width2, height, bpc, csInfo, alphaSampl
207608
210798
  const m = remapUnitSampleWithDecode((rawSamples[p2 * stride + chStep] ?? 0) / 255, 1, decodePairs);
207609
210799
  const y = remapUnitSampleWithDecode((rawSamples[p2 * stride + chStep * 2] ?? 0) / 255, 2, decodePairs);
207610
210800
  const k = remapUnitSampleWithDecode((rawSamples[p2 * stride + chStep * 3] ?? 0) / 255, 3, decodePairs);
207611
- rgba[p2 * 4] = Math.round((1 - c4) * (1 - k) * 255);
207612
- rgba[p2 * 4 + 1] = Math.round((1 - m) * (1 - k) * 255);
207613
- rgba[p2 * 4 + 2] = Math.round((1 - y) * (1 - k) * 255);
210801
+ rgba.set(cmykColorSpace.getRgb([c4, m, y, k], 0), p2 * 4);
207614
210802
  rgba[p2 * 4 + 3] = 255;
207615
210803
  }
207616
210804
  } else if (csInfo.colorSpace === "index") {
@@ -207648,9 +210836,7 @@ function decodeSamplesToRgba(rawSamples, width2, height, bpc, csInfo, alphaSampl
207648
210836
  const m = pal[idx * 4 + 1] / 255;
207649
210837
  const yel = pal[idx * 4 + 2] / 255;
207650
210838
  const k = pal[idx * 4 + 3] / 255;
207651
- rgba[p2 * 4] = Math.round((1 - c4) * (1 - k) * 255);
207652
- rgba[p2 * 4 + 1] = Math.round((1 - m) * (1 - k) * 255);
207653
- rgba[p2 * 4 + 2] = Math.round((1 - yel) * (1 - k) * 255);
210839
+ rgba.set(cmykColorSpace.getRgb([c4, m, yel, k], 0), p2 * 4);
207654
210840
  } else {
207655
210841
  rgba[p2 * 4] = pal[idx * baseComp];
207656
210842
  rgba[p2 * 4 + 1] = pal[idx * baseComp + 1];
@@ -207905,6 +211091,7 @@ function decodeInlineImageNodeToRgba(doc, dict, rawData, activeRes, fillColor) {
207905
211091
  });
207906
211092
  return decodeXObjectImageToRgba(context, { kind: "stream", dict, rawBytes: rawData }, activeRes, fillColor);
207907
211093
  }
211094
+ var cmykColorSpace2 = new DeviceCmykCS();
207908
211095
  function multiplyMatrices(m1, m2) {
207909
211096
  return [
207910
211097
  m1[0] * m2[0] + m1[1] * m2[2],
@@ -208121,193 +211308,7 @@ function resolvePageFonts(doc, resourcesDict) {
208121
211308
  }
208122
211309
  return fonts;
208123
211310
  }
208124
- function evaluateType4PostScriptTokens(tokens3, initialStack) {
208125
- const stack = [...initialStack];
208126
- const runRange = (start, end2) => {
208127
- let i = start;
208128
- while (i < end2) {
208129
- const tok = tokens3[i];
208130
- if (tok === "{") {
208131
- let depth = 1;
208132
- let j = i + 1;
208133
- while (j < end2 && depth > 0) {
208134
- if (tokens3[j] === "{") depth++;
208135
- else if (tokens3[j] === "}") depth--;
208136
- j++;
208137
- }
208138
- const blockStart = i + 1;
208139
- const blockEnd = j - 1;
208140
- if (j < end2 && tokens3[j] === "{") {
208141
- let depth2 = 1;
208142
- let k = j + 1;
208143
- while (k < end2 && depth2 > 0) {
208144
- if (tokens3[k] === "{") depth2++;
208145
- else if (tokens3[k] === "}") depth2--;
208146
- k++;
208147
- }
208148
- if (k < end2 && tokens3[k] === "ifelse") {
208149
- const cond = stack.pop() ?? 0;
208150
- if (cond !== 0) runRange(blockStart, blockEnd);
208151
- else runRange(j + 1, k - 1);
208152
- i = k + 1;
208153
- continue;
208154
- }
208155
- }
208156
- if (j < end2 && tokens3[j] === "if") {
208157
- const cond = stack.pop() ?? 0;
208158
- if (cond !== 0) runRange(blockStart, blockEnd);
208159
- i = j + 1;
208160
- continue;
208161
- }
208162
- runRange(blockStart, blockEnd);
208163
- i = j;
208164
- continue;
208165
- }
208166
- if (tok === "}") {
208167
- i++;
208168
- continue;
208169
- }
208170
- const numVal2 = Number(tok);
208171
- if (tok.length > 0 && !Number.isNaN(numVal2)) {
208172
- stack.push(numVal2);
208173
- } else if (tok === "true") {
208174
- stack.push(1);
208175
- } else if (tok === "false") {
208176
- stack.push(0);
208177
- } else if (tok === "add") {
208178
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208179
- stack.push(a3 + b3);
208180
- } else if (tok === "sub") {
208181
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208182
- stack.push(a3 - b3);
208183
- } else if (tok === "mul") {
208184
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208185
- stack.push(a3 * b3);
208186
- } else if (tok === "div") {
208187
- const b3 = stack.pop() ?? 1, a3 = stack.pop() ?? 0;
208188
- stack.push(Math.abs(b3) > 1e-12 ? a3 / b3 : 0);
208189
- } else if (tok === "idiv") {
208190
- const b3 = stack.pop() ?? 1, a3 = stack.pop() ?? 0;
208191
- stack.push(Math.abs(b3) > 1e-12 ? Math.trunc(a3 / b3) : 0);
208192
- } else if (tok === "mod") {
208193
- const b3 = stack.pop() ?? 1, a3 = stack.pop() ?? 0;
208194
- stack.push(Math.abs(b3) > 1e-12 ? a3 % b3 : 0);
208195
- } else if (tok === "neg") {
208196
- stack.push(-(stack.pop() ?? 0));
208197
- } else if (tok === "abs") {
208198
- stack.push(Math.abs(stack.pop() ?? 0));
208199
- } else if (tok === "ceiling") {
208200
- stack.push(Math.ceil(stack.pop() ?? 0));
208201
- } else if (tok === "floor") {
208202
- stack.push(Math.floor(stack.pop() ?? 0));
208203
- } else if (tok === "round") {
208204
- stack.push(Math.round(stack.pop() ?? 0));
208205
- } else if (tok === "truncate" || tok === "cvi") {
208206
- stack.push(Math.trunc(stack.pop() ?? 0));
208207
- } else if (tok === "sqrt") {
208208
- stack.push(Math.sqrt(Math.max(0, stack.pop() ?? 0)));
208209
- } else if (tok === "sin") {
208210
- stack.push(Math.sin((stack.pop() ?? 0) * Math.PI / 180));
208211
- } else if (tok === "cos") {
208212
- stack.push(Math.cos((stack.pop() ?? 0) * Math.PI / 180));
208213
- } else if (tok === "atan") {
208214
- const dx = stack.pop() ?? 1, dy = stack.pop() ?? 0;
208215
- let deg = Math.atan2(dy, dx) * 180 / Math.PI;
208216
- if (deg < 0) deg += 360;
208217
- stack.push(deg);
208218
- } else if (tok === "exp") {
208219
- const exp = stack.pop() ?? 1, base = stack.pop() ?? 0;
208220
- stack.push(Math.pow(base, exp));
208221
- } else if (tok === "ln") {
208222
- stack.push(Math.log(Math.max(1e-12, stack.pop() ?? 1)));
208223
- } else if (tok === "log") {
208224
- stack.push(Math.log10(Math.max(1e-12, stack.pop() ?? 1)));
208225
- } else if (tok === "dup") {
208226
- if (stack.length > 0) stack.push(stack[stack.length - 1]);
208227
- } else if (tok === "exch") {
208228
- if (stack.length >= 2) {
208229
- const b3 = stack.pop(), a3 = stack.pop();
208230
- stack.push(b3, a3);
208231
- }
208232
- } else if (tok === "pop") {
208233
- stack.pop();
208234
- } else if (tok === "copy") {
208235
- const n = Math.max(0, Math.trunc(stack.pop() ?? 0));
208236
- const slice = stack.slice(Math.max(0, stack.length - n));
208237
- stack.push(...slice);
208238
- } else if (tok === "index") {
208239
- const n = Math.max(0, Math.trunc(stack.pop() ?? 0));
208240
- const idx = stack.length - 1 - n;
208241
- if (idx >= 0 && idx < stack.length) stack.push(stack[idx]);
208242
- } else if (tok === "roll") {
208243
- const jShift = Math.trunc(stack.pop() ?? 0);
208244
- const n = Math.max(0, Math.trunc(stack.pop() ?? 0));
208245
- if (n > 0 && stack.length >= n) {
208246
- const sub = stack.splice(stack.length - n, n);
208247
- const modShift = (jShift % n + n) % n;
208248
- const rolled = [...sub.slice(n - modShift), ...sub.slice(0, n - modShift)];
208249
- stack.push(...rolled);
208250
- }
208251
- } else if (tok === "eq") {
208252
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208253
- stack.push(Math.abs(a3 - b3) < 1e-9 ? 1 : 0);
208254
- } else if (tok === "ne") {
208255
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208256
- stack.push(Math.abs(a3 - b3) >= 1e-9 ? 1 : 0);
208257
- } else if (tok === "gt") {
208258
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208259
- stack.push(a3 > b3 ? 1 : 0);
208260
- } else if (tok === "ge") {
208261
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208262
- stack.push(a3 >= b3 ? 1 : 0);
208263
- } else if (tok === "lt") {
208264
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208265
- stack.push(a3 < b3 ? 1 : 0);
208266
- } else if (tok === "le") {
208267
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208268
- stack.push(a3 <= b3 ? 1 : 0);
208269
- } else if (tok === "and") {
208270
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208271
- stack.push(a3 !== 0 && b3 !== 0 ? 1 : 0);
208272
- } else if (tok === "or") {
208273
- const b3 = stack.pop() ?? 0, a3 = stack.pop() ?? 0;
208274
- stack.push(a3 !== 0 || b3 !== 0 ? 1 : 0);
208275
- } else if (tok === "not") {
208276
- const a3 = stack.pop() ?? 0;
208277
- stack.push(a3 === 0 ? 1 : 0);
208278
- }
208279
- i++;
208280
- }
208281
- };
208282
- runRange(0, tokens3.length);
208283
- return stack;
208284
- }
208285
- function tokenizePostScriptCode(bytes) {
208286
- const tokens3 = [];
208287
- let cur = "";
208288
- for (let i = 0; i < bytes.length; i++) {
208289
- const ch3 = String.fromCharCode(bytes[i]);
208290
- if (ch3 === "{" || ch3 === "}") {
208291
- if (cur.length > 0) {
208292
- tokens3.push(cur);
208293
- cur = "";
208294
- }
208295
- tokens3.push(ch3);
208296
- } else if (ch3 === " " || ch3 === " " || ch3 === "\n" || ch3 === "\r") {
208297
- if (cur.length > 0) {
208298
- tokens3.push(cur);
208299
- cur = "";
208300
- }
208301
- } else {
208302
- cur += ch3;
208303
- }
208304
- }
208305
- if (cur.length > 0) tokens3.push(cur);
208306
- if (tokens3[0] === "{" && tokens3[tokens3.length - 1] === "}") {
208307
- return tokens3.slice(1, -1);
208308
- }
208309
- return tokens3;
208310
- }
211311
+ var postScriptFunctions = /* @__PURE__ */ new WeakMap();
208311
211312
  function evalShadingFunctionToComponents(doc, fnNode, inputs) {
208312
211313
  const inArr = typeof inputs === "number" ? [inputs] : inputs;
208313
211314
  const t = inArr[0] ?? 0;
@@ -208354,35 +211355,50 @@ function evalShadingFunctionToComponents(doc, fnNode, inputs) {
208354
211355
  const decode3 = getNums("Decode", range3);
208355
211356
  const nOut = Math.max(1, Math.floor((decode3.length || range3.length || 6) / 2));
208356
211357
  const mIn = Math.max(1, size.length);
208357
- let flatGridIndex = 0;
211358
+ const streamBytes = doc.decodeStream(resolved);
211359
+ let vertices = [{ index: 0, weight: 1 }];
208358
211360
  let stride = 1;
208359
211361
  for (let i = 0; i < mIn; i++) {
208360
211362
  const d02 = dom[i * 2] ?? 0;
208361
211363
  const d12 = dom[i * 2 + 1] ?? 1;
208362
- const sMax = Math.max(1, (size[i] ?? 2) - 1);
211364
+ const sMax = Math.max(0, (size[i] ?? 2) - 1);
208363
211365
  const e0 = encode[i * 2] ?? 0;
208364
211366
  const e1 = encode[i * 2 + 1] ?? sMax;
208365
211367
  const x = Math.max(d02, Math.min(d12, inArr[i] ?? 0));
208366
- const u = Math.abs(d12 - d02) > 1e-8 ? (x - d02) / (d12 - d02) : 0;
208367
- const idx = Math.round(Math.max(0, Math.min(sMax, e0 + u * (e1 - e0))));
208368
- flatGridIndex += idx * stride;
211368
+ const u = d12 === d02 ? 0 : (x - d02) / (d12 - d02);
211369
+ const e = Math.max(0, Math.min(sMax, e0 + u * (e1 - e0)));
211370
+ const low = Math.floor(e), fraction = e - low;
211371
+ const next = [];
211372
+ for (const vertex of vertices) {
211373
+ const index2 = vertex.index + low * stride;
211374
+ if (index2 * nOut * bps < streamBytes.length * 8) next.push({ index: index2, weight: vertex.weight * (1 - fraction) });
211375
+ if (fraction && (index2 + stride) * nOut * bps < streamBytes.length * 8) {
211376
+ next.push({ index: index2 + stride, weight: vertex.weight * fraction });
211377
+ }
211378
+ }
211379
+ vertices = next;
208369
211380
  stride *= size[i] ?? 2;
208370
211381
  }
208371
- const streamBytes = doc.decodeStream(resolved);
211382
+ const maxSample = 2 ** bps - 1;
211383
+ const readSample = (index2) => {
211384
+ let bitOffset = index2 * bps, remaining = bps, value3 = 0;
211385
+ while (remaining > 0) {
211386
+ const bitInByte = bitOffset % 8;
211387
+ const take = Math.min(remaining, 8 - bitInByte);
211388
+ const byte = streamBytes[Math.floor(bitOffset / 8)] ?? 0;
211389
+ value3 = value3 * 2 ** take + (byte >> 8 - bitInByte - take & (1 << take) - 1);
211390
+ bitOffset += take;
211391
+ remaining -= take;
211392
+ }
211393
+ return value3 / maxSample;
211394
+ };
208372
211395
  const out2 = [];
208373
- const maxSample = bps === 16 ? 65535 : 255;
208374
211396
  for (let j = 0; j < nOut; j++) {
208375
- const sampleIdx = flatGridIndex * nOut + j;
208376
- let rawVal = 0;
208377
- if (bps === 16) {
208378
- rawVal = (streamBytes[sampleIdx * 2] ?? 0) << 8 | (streamBytes[sampleIdx * 2 + 1] ?? 0);
208379
- } else {
208380
- rawVal = streamBytes[sampleIdx] ?? 0;
208381
- }
208382
- const frac = rawVal / maxSample;
211397
+ let value3 = 0;
211398
+ for (const vertex of vertices) value3 += readSample(vertex.index * nOut + j) * vertex.weight;
208383
211399
  const dec0 = decode3[j * 2] ?? 0;
208384
211400
  const dec1 = decode3[j * 2 + 1] ?? 1;
208385
- out2.push(dec0 + frac * (dec1 - dec0));
211401
+ out2.push(dec0 + value3 * (dec1 - dec0));
208386
211402
  }
208387
211403
  return clampRange(out2);
208388
211404
  }
@@ -208392,34 +211408,40 @@ function evalShadingFunctionToComponents(doc, fnNode, inputs) {
208392
211408
  const d12 = dom[i * 2 + 1] ?? 1;
208393
211409
  return Math.max(d02, Math.min(d12, v));
208394
211410
  });
208395
- const tokens3 = tokenizePostScriptCode(doc.decodeStream(resolved));
208396
- const stackOut = evaluateType4PostScriptTokens(tokens3, clampedInputs);
208397
- return clampRange(stackOut);
211411
+ const source = bytesToString3(doc.decodeStream(resolved));
211412
+ let cached = postScriptFunctions.get(resolved);
211413
+ if (!cached || cached.source !== source || cached.domain.length !== dom.length || cached.domain.some((value3, index2) => value3 !== dom[index2]) || cached.range.length !== range3.length || cached.range.some((value3, index2) => value3 !== range3[index2])) {
211414
+ cached = { source, domain: dom, range: range3, evaluate: buildPostScriptJsFunction(source, dom, range3) };
211415
+ postScriptFunctions.set(resolved, cached);
211416
+ }
211417
+ const output2 = [];
211418
+ cached.evaluate(clampedInputs, 0, output2, 0);
211419
+ return output2;
208398
211420
  }
208399
211421
  if (ft === 3) {
208400
211422
  const fnsArr = doc.resolveArray(dictGet(fnDict, "Functions"));
208401
211423
  const bounds2 = getNums("Bounds", []);
208402
211424
  const encode = getNums("Encode", []);
208403
211425
  if (fnsArr && fnsArr.items.length > 0) {
211426
+ const input = Math.max(dom[0] ?? 0, Math.min(dom[1] ?? 1, t));
208404
211427
  let segIdx = 0;
208405
- while (segIdx < bounds2.length && t >= bounds2[segIdx]) segIdx++;
211428
+ while (segIdx < bounds2.length && input >= bounds2[segIdx]) segIdx++;
208406
211429
  segIdx = Math.min(fnsArr.items.length - 1, segIdx);
208407
211430
  const b0 = segIdx === 0 ? dom[0] ?? 0 : bounds2[segIdx - 1];
208408
211431
  const b1 = segIdx < bounds2.length ? bounds2[segIdx] : dom[1] ?? 1;
208409
211432
  const e0 = encode[segIdx * 2] ?? 0;
208410
211433
  const e1 = encode[segIdx * 2 + 1] ?? 1;
208411
- const localT = Math.abs(b1 - b0) > 1e-8 ? e0 + (t - b0) / (b1 - b0) * (e1 - e0) : e0;
208412
- return evalShadingFunctionToComponents(doc, fnsArr.items[segIdx], Math.max(0, Math.min(1, localT)));
211434
+ const localT = b1 !== b0 ? e0 + (input - b0) / (b1 - b0) * (e1 - e0) : e0;
211435
+ return clampRange(evalShadingFunctionToComponents(doc, fnsArr.items[segIdx], localT));
208413
211436
  }
208414
211437
  }
208415
- const c0 = getNums("C0", [0, 0, 0]);
208416
- const c1 = getNums("C1", [1, 1, 1]);
211438
+ const c0 = getNums("C0", [0]);
211439
+ const c1 = getNums("C1", [1]);
208417
211440
  const nNode = doc.resolve(dictGet(fnDict, "N"));
208418
- const expN = nNode?.kind === "number" && nNode.value > 0 ? nNode.value : 1;
211441
+ const expN = nNode?.kind === "number" ? nNode.value : 1;
208419
211442
  const d0 = dom[0] ?? 0;
208420
211443
  const d1 = dom[1] ?? 1;
208421
- const normT = Math.abs(d1 - d0) > 1e-8 ? (t - d0) / (d1 - d0) : t;
208422
- const w = Math.pow(Math.max(0, Math.min(1, normT)), expN);
211444
+ const w = Math.pow(Math.max(d0, Math.min(d1, t)), expN);
208423
211445
  const len = Math.max(c0.length, c1.length);
208424
211446
  const out = [];
208425
211447
  for (let i = 0; i < len; i++) {
@@ -208435,30 +211457,14 @@ function shadingComponentsToRgb(csName, comps) {
208435
211457
  return [v, v, v];
208436
211458
  }
208437
211459
  if (csName === "DeviceCMYK" || csName === "CMYK" || comps.length >= 4) {
208438
- const cc = comps[0] ?? 0, cm = comps[1] ?? 0, cy = comps[2] ?? 0, ck = comps[3] ?? 0;
208439
- return [(1 - cc) * (1 - ck), (1 - cm) * (1 - kClamp(ck)), (1 - cy) * (1 - kClamp(ck))];
211460
+ const rgb22 = cmykColorSpace2.getRgb([comps[0] ?? 0, comps[1] ?? 0, comps[2] ?? 0, comps[3] ?? 0], 0);
211461
+ return [rgb22[0] / 255, rgb22[1] / 255, rgb22[2] / 255];
208440
211462
  }
208441
211463
  return [comps[0] ?? 0, comps[1] ?? 0, comps[2] ?? 0];
208442
211464
  }
208443
211465
  function kClamp(v) {
208444
211466
  return Math.max(0, Math.min(1, v));
208445
211467
  }
208446
- function xyzToSrgb(X, Y, Z, Xw = 0.95047, Yw = 1, Zw = 1.08883) {
208447
- const scaleX = Xw > 1e-6 ? 0.95047 / Xw : 1;
208448
- const scaleY = Yw > 1e-6 ? 1 / Yw : 1;
208449
- const scaleZ = Zw > 1e-6 ? 1.08883 / Zw : 1;
208450
- const x = X * scaleX;
208451
- const y = Y * scaleY;
208452
- const z = Z * scaleZ;
208453
- const rl = 3.2404542 * x - 1.5371385 * y - 0.4985314 * z;
208454
- const gl = -0.969266 * x + 1.8760108 * y + 0.041556 * z;
208455
- const bl = 0.0556434 * x - 0.2040259 * y + 1.0572252 * z;
208456
- const toGamma = (u) => {
208457
- const c4 = Math.max(0, Math.min(1, u));
208458
- return c4 <= 31308e-7 ? 12.92 * c4 : 1.055 * Math.pow(c4, 1 / 2.4) - 0.055;
208459
- };
208460
- return [toGamma(rl), toGamma(gl), toGamma(bl)];
208461
- }
208462
211468
  function getColorSpaceComponentCount(doc, csNode, activeResources, depth = 0) {
208463
211469
  if (!csNode || depth > 4) return 3;
208464
211470
  const resolved = doc ? doc.resolve(csNode) : csNode;
@@ -208515,63 +211521,10 @@ function convertColorSpaceComponentsToRgb(doc, csNode, csNameFallback, comps, ac
208515
211521
  if (resolved.kind === "array" && resolved.items.length > 0 && doc) {
208516
211522
  const familyNode = doc.resolve(resolved.items[0]);
208517
211523
  const family = familyNode?.kind === "name" ? familyNode.decoded : "";
208518
- if (family === "CalGray") {
208519
- const paramDict = resolved.items[1] ? doc.resolveDict(resolved.items[1]) : void 0;
208520
- const gNode = paramDict ? doc.resolve(dictGet(paramDict, "Gamma")) : void 0;
208521
- const gamma2 = gNode?.kind === "number" && gNode.value > 0 ? gNode.value : 1;
208522
- const a3 = Math.pow(kClamp(comps[0] ?? 0), gamma2);
208523
- return [a3, a3, a3];
208524
- }
208525
- if (family === "CalRGB") {
208526
- const paramDict = resolved.items[1] ? doc.resolveDict(resolved.items[1]) : void 0;
208527
- const gammaArr = paramDict ? doc.resolveArray(dictGet(paramDict, "Gamma")) : void 0;
208528
- const getArrNum = (arr, idx, fb) => {
208529
- const r = arr && arr.items[idx] ? doc.resolve(arr.items[idx]) : void 0;
208530
- return r?.kind === "number" ? r.value : fb;
208531
- };
208532
- const gr = getArrNum(gammaArr, 0, 1);
208533
- const gg = getArrNum(gammaArr, 1, 1);
208534
- const gb = getArrNum(gammaArr, 2, 1);
208535
- const ag = Math.pow(kClamp(comps[0] ?? 0), gr > 0 ? gr : 1);
208536
- const bg = Math.pow(kClamp(comps[1] ?? 0), gg > 0 ? gg : 1);
208537
- const cg = Math.pow(kClamp(comps[2] ?? 0), gb > 0 ? gb : 1);
208538
- const matArr = paramDict ? doc.resolveArray(dictGet(paramDict, "Matrix")) : void 0;
208539
- if (matArr && matArr.items.length >= 9) {
208540
- const m = (i) => getArrNum(matArr, i, 0);
208541
- const X = m(0) * ag + m(3) * bg + m(6) * cg;
208542
- const Y = m(1) * ag + m(4) * bg + m(7) * cg;
208543
- const Z = m(2) * ag + m(5) * bg + m(8) * cg;
208544
- const wpArr = paramDict ? doc.resolveArray(dictGet(paramDict, "WhitePoint")) : void 0;
208545
- const Xw = getArrNum(wpArr, 0, 0.95047);
208546
- const Yw = getArrNum(wpArr, 1, 1);
208547
- const Zw = getArrNum(wpArr, 2, 1.08883);
208548
- return xyzToSrgb(X, Y, Z, Xw, Yw, Zw);
208549
- }
208550
- return [ag, bg, cg];
208551
- }
208552
- if (family === "Lab") {
208553
- const paramDict = resolved.items[1] ? doc.resolveDict(resolved.items[1]) : void 0;
208554
- const wpArr = paramDict ? doc.resolveArray(dictGet(paramDict, "WhitePoint")) : void 0;
208555
- const rangeArr = paramDict ? doc.resolveArray(dictGet(paramDict, "Range")) : void 0;
208556
- const getNum = (arr, idx, fb) => {
208557
- const r = arr && arr.items[idx] ? doc.resolve(arr.items[idx]) : void 0;
208558
- return r?.kind === "number" ? r.value : fb;
208559
- };
208560
- const Xw = getNum(wpArr, 0, 0.95047);
208561
- const Yw = getNum(wpArr, 1, 1);
208562
- const Zw = getNum(wpArr, 2, 1.08883);
208563
- const amin = getNum(rangeArr, 0, -100);
208564
- const amax = getNum(rangeArr, 1, 100);
208565
- const bmin = getNum(rangeArr, 2, -100);
208566
- const bmax = getNum(rangeArr, 3, 100);
208567
- const Lstar = Math.max(0, Math.min(100, comps[0] ?? 0));
208568
- const astar = Math.max(amin, Math.min(amax, comps[1] ?? 0));
208569
- const bstar = Math.max(bmin, Math.min(bmax, comps[2] ?? 0));
208570
- const M = (Lstar + 16) / 116;
208571
- const L = M + astar / 500;
208572
- const N = M - bstar / 200;
208573
- const gFn = (x) => x >= 6 / 29 ? x * x * x : 108 / 841 * (x - 4 / 29);
208574
- return xyzToSrgb(Xw * gFn(L), Yw * gFn(M), Zw * gFn(N), Xw, Yw, Zw);
211524
+ if (family === "CalGray" || family === "CalRGB" || family === "Lab") {
211525
+ const colorSpace = createCalibratedColorSpace(doc, family, resolved.items[1]);
211526
+ const rgb22 = colorSpace.getRgb(comps, 0);
211527
+ return [rgb22[0] / 255, rgb22[1] / 255, rgb22[2] / 255];
208575
211528
  }
208576
211529
  if (family === "ICCBased" && resolved.items[1]) {
208577
211530
  const iccNode = doc.resolve(resolved.items[1]);
@@ -208652,143 +211605,28 @@ function renderMeshShadingToImage(doc, shDict, shStream, shType, effectiveCtm, t
208652
211605
  const r = doc.resolve(it);
208653
211606
  return r?.kind === "number" ? r.value : 0;
208654
211607
  });
208655
- const xmin = decodeNums[0], xmax = decodeNums[1], ymin = decodeNums[2], ymax = decodeNums[3];
208656
- const numColorParams = Math.max(1, Math.floor((decodeNums.length - 4) / 2));
208657
211608
  const fnNode = dictGet(shDict, "Function");
208658
211609
  const csNode = doc.resolve(dictGet(shDict, "ColorSpace"));
208659
211610
  const csName = csNode?.kind === "name" ? csNode.decoded : "DeviceRGB";
208660
- let bitPos = 0;
208661
- const totalBits = bytes.length * 8;
208662
- const readBits = (n) => {
208663
- let val = 0;
208664
- for (let i = 0; i < n; i++) {
208665
- if (bitPos >= totalBits) return val;
208666
- const byteIdx = bitPos >> 3;
208667
- const bitIdx = 7 - (bitPos & 7);
208668
- val = val * 2 + (bytes[byteIdx] >> bitIdx & 1);
208669
- bitPos++;
208670
- }
208671
- return val;
208672
- };
208673
- const coordMax = Math.pow(2, bpcCoord) - 1 || 1;
208674
- const compMax = Math.pow(2, bpcComp) - 1 || 1;
208675
- const readCoord = () => {
208676
- const rx = readBits(bpcCoord) / coordMax;
208677
- const ry = readBits(bpcCoord) / coordMax;
208678
- return [xmin + rx * (xmax - xmin), ymin + ry * (ymax - ymin)];
208679
- };
208680
- const readColorRgb = () => {
208681
- const params = [];
208682
- for (let c4 = 0; c4 < numColorParams; c4++) {
208683
- const rc = readBits(bpcComp) / compMax;
208684
- const cMin = decodeNums[4 + c4 * 2] ?? 0;
208685
- const cMax = decodeNums[4 + c4 * 2 + 1] ?? 1;
208686
- params.push(cMin + rc * (cMax - cMin));
208687
- }
208688
- const comps = fnNode ? evalShadingFunctionToComponents(doc, fnNode, params) : params;
208689
- return convertColorSpaceComponentsToRgb(doc, csNode, csName, comps);
208690
- };
208691
- const triangles = [];
208692
- if (shType === 4) {
208693
- const minBitsPerVert = bpcFlag + 2 * bpcCoord + numColorParams * bpcComp;
208694
- let triVerts;
208695
- while (bitPos + minBitsPerVert <= totalBits) {
208696
- const flag = readBits(bpcFlag) & 3;
208697
- const [x, y] = readCoord();
208698
- const rgb22 = readColorRgb();
208699
- const vNew = { x, y, rgb: rgb22 };
208700
- if (flag === 0 || !triVerts) {
208701
- if (bitPos + 2 * minBitsPerVert > totalBits) break;
208702
- readBits(bpcFlag);
208703
- const [x1, y1] = readCoord();
208704
- const rgb1 = readColorRgb();
208705
- readBits(bpcFlag);
208706
- const [x2, y2] = readCoord();
208707
- const rgb222 = readColorRgb();
208708
- triVerts = [vNew, { x: x1, y: y1, rgb: rgb1 }, { x: x2, y: y2, rgb: rgb222 }];
208709
- triangles.push(triVerts);
208710
- } else if (flag === 1) {
208711
- triVerts = [triVerts[1], triVerts[2], vNew];
208712
- triangles.push(triVerts);
208713
- } else if (flag === 2) {
208714
- triVerts = [triVerts[0], triVerts[2], vNew];
208715
- triangles.push(triVerts);
208716
- }
208717
- }
208718
- } else if (shType === 5) {
208719
- const minBitsPerVert = 2 * bpcCoord + numColorParams * bpcComp;
208720
- const verts = [];
208721
- while (bitPos + minBitsPerVert <= totalBits) {
208722
- const [x, y] = readCoord();
208723
- const rgb22 = readColorRgb();
208724
- verts.push({ x, y, rgb: rgb22 });
208725
- }
208726
- const numRows = Math.floor(verts.length / vPerRow);
208727
- for (let r = 0; r + 1 < numRows; r++) {
208728
- for (let c4 = 0; c4 + 1 < vPerRow; c4++) {
208729
- const v00 = verts[r * vPerRow + c4];
208730
- const v01 = verts[r * vPerRow + c4 + 1];
208731
- const v11 = verts[(r + 1) * vPerRow + c4 + 1];
208732
- const v10 = verts[(r + 1) * vPerRow + c4];
208733
- triangles.push([v00, v01, v11], [v00, v11, v10]);
208734
- }
208735
- }
208736
- } else if (shType === 6 || shType === 7) {
208737
- const numCtrl = shType === 6 ? 12 : 16;
208738
- const minBitsPatch = bpcFlag + (numCtrl - 4) * 2 * bpcCoord + 2 * numColorParams * bpcComp;
208739
- let prevPts;
208740
- let prevColors;
208741
- while (bitPos + minBitsPatch <= totalBits) {
208742
- const flag = readBits(bpcFlag) & 3;
208743
- let pts = [];
208744
- let cols = [];
208745
- if (flag === 0 || !prevPts || !prevColors) {
208746
- for (let i = 0; i < numCtrl; i++) pts.push(readCoord());
208747
- for (let i = 0; i < 4; i++) cols.push(readColorRgb());
208748
- } else {
208749
- const extraCtrl = numCtrl - 4;
208750
- const readExtra = [];
208751
- for (let i = 0; i < extraCtrl; i++) readExtra.push(readCoord());
208752
- const c22 = readColorRgb();
208753
- const c32 = readColorRgb();
208754
- pts = [prevPts[3], prevPts[4], prevPts[5], prevPts[6], ...readExtra];
208755
- cols = [prevColors[1], prevColors[2], c22, c32];
208756
- }
208757
- prevPts = pts;
208758
- prevColors = cols;
208759
- const p00 = pts[0];
208760
- const p03 = pts[3];
208761
- const p33 = pts[6];
208762
- const p30 = pts[9];
208763
- const c00 = cols[0], c03 = cols[1], c33 = cols[2], c30 = cols[3];
208764
- const steps = 4;
208765
- const grid = [];
208766
- for (let iu = 0; iu <= steps; iu++) {
208767
- const u = iu / steps;
208768
- const row = [];
208769
- for (let iv = 0; iv <= steps; iv++) {
208770
- const v = iv / steps;
208771
- const x = (1 - u) * (1 - v) * p00[0] + (1 - u) * v * p03[0] + u * v * p33[0] + u * (1 - v) * p30[0];
208772
- const y = (1 - u) * (1 - v) * p00[1] + (1 - u) * v * p03[1] + u * v * p33[1] + u * (1 - v) * p30[1];
208773
- const r = (1 - u) * (1 - v) * c00[0] + (1 - u) * v * c03[0] + u * v * c33[0] + u * (1 - v) * c30[0];
208774
- const g = (1 - u) * (1 - v) * c00[1] + (1 - u) * v * c03[1] + u * v * c33[1] + u * (1 - v) * c30[1];
208775
- const b3 = (1 - u) * (1 - v) * c00[2] + (1 - u) * v * c03[2] + u * v * c33[2] + u * (1 - v) * c30[2];
208776
- row.push({ x, y, rgb: [r, g, b3] });
208777
- }
208778
- grid.push(row);
208779
- }
208780
- for (let iu = 0; iu < steps; iu++) {
208781
- for (let iv = 0; iv < steps; iv++) {
208782
- const g00 = grid[iu][iv];
208783
- const g01 = grid[iu][iv + 1];
208784
- const g11 = grid[iu + 1][iv + 1];
208785
- const g10 = grid[iu + 1][iv];
208786
- triangles.push([g00, g01, g11], [g00, g11, g10]);
208787
- }
208788
- }
208789
- }
208790
- }
208791
- if (triangles.length === 0) return void 0;
211611
+ const numComps = fnNode ? 1 : getColorSpaceComponentCount(doc, csNode);
211612
+ const mesh = new MeshShading(shType, new Stream(bytes), {
211613
+ bitsPerCoordinate: bpcCoord,
211614
+ bitsPerComponent: bpcComp,
211615
+ bitsPerFlag: bpcFlag,
211616
+ decode: decodeNums,
211617
+ numComps,
211618
+ colorFn: null,
211619
+ colorSpace: {
211620
+ numComps,
211621
+ getRgb(components22) {
211622
+ const params = Array.from(components22);
211623
+ const values2 = fnNode ? evalShadingFunctionToComponents(doc, fnNode, params) : params;
211624
+ return new Uint8Array(convertColorSpaceComponentsToRgb(doc, csNode, csName, values2).map((value3) => Math.round(Math.max(0, Math.min(1, value3)) * 255)));
211625
+ }
211626
+ }
211627
+ }, vPerRow);
211628
+ const [, , positions, colors2, vertexCount] = mesh.getIR();
211629
+ if (vertexCount === 0) return void 0;
208792
211630
  const [bx0, by0, bx1, by1] = targetBox;
208793
211631
  const boxW = Math.max(1, bx1 - bx0);
208794
211632
  const boxH = Math.max(1, by1 - by0);
@@ -208800,10 +211638,10 @@ function renderMeshShadingToImage(doc, shDict, shStream, shType, effectiveCtm, t
208800
211638
  const [px, py] = transformPoint(effectiveCtm, vx, vy);
208801
211639
  return [(px - bx0) / boxW * imgW, (by1 - py) / boxH * imgH];
208802
211640
  };
208803
- for (const [v0, v1, v2] of triangles) {
208804
- const [x0, y0] = toImgCoords(v0.x, v0.y);
208805
- const [x1, y1] = toImgCoords(v1.x, v1.y);
208806
- const [x2, y2] = toImgCoords(v2.x, v2.y);
211641
+ for (let vertex = 0; vertex < vertexCount; vertex += 3) {
211642
+ const [x0, y0] = toImgCoords(positions[vertex * 2], positions[vertex * 2 + 1]);
211643
+ const [x1, y1] = toImgCoords(positions[vertex * 2 + 2], positions[vertex * 2 + 3]);
211644
+ const [x2, y2] = toImgCoords(positions[vertex * 2 + 4], positions[vertex * 2 + 5]);
208807
211645
  const denom = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2);
208808
211646
  if (Math.abs(denom) < 1e-6) continue;
208809
211647
  const minX = Math.max(0, Math.floor(Math.min(x0, x1, x2)));
@@ -208818,13 +211656,12 @@ function renderMeshShadingToImage(doc, shDict, shStream, shType, effectiveCtm, t
208818
211656
  const w1 = ((y2 - y0) * (px - x2) + (x0 - x2) * (py - y2)) / denom;
208819
211657
  const w2 = 1 - w0 - w1;
208820
211658
  if (w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4) {
208821
- const r = w0 * v0.rgb[0] + w1 * v1.rgb[0] + w2 * v2.rgb[0];
208822
- const g = w0 * v0.rgb[1] + w1 * v1.rgb[1] + w2 * v2.rgb[1];
208823
- const b3 = w0 * v0.rgb[2] + w1 * v1.rgb[2] + w2 * v2.rgb[2];
208824
211659
  const pIdx = (iy * imgW + ix) * 4;
208825
- rgba[pIdx] = Math.round(Math.max(0, Math.min(1, r)) * 255);
208826
- rgba[pIdx + 1] = Math.round(Math.max(0, Math.min(1, g)) * 255);
208827
- rgba[pIdx + 2] = Math.round(Math.max(0, Math.min(1, b3)) * 255);
211660
+ for (let channel = 0; channel < 3; channel++) {
211661
+ rgba[pIdx + channel] = Math.round(
211662
+ w0 * colors2[vertex * 4 + channel] + w1 * colors2[vertex * 4 + 4 + channel] + w2 * colors2[vertex * 4 + 8 + channel]
211663
+ );
211664
+ }
208828
211665
  rgba[pIdx + 3] = a8;
208829
211666
  }
208830
211667
  }
@@ -208911,6 +211748,8 @@ function renderShadingDictToImage(doc, shDict, shadingCtm, targetBox, fillAlpha,
208911
211748
  const [a3, b3, c4, d2, e, f2] = effectiveCtm;
208912
211749
  const det = a3 * d2 - b3 * c4;
208913
211750
  if (Math.abs(det) <= 1e-8) return void 0;
211751
+ const [sa, sb, sc, sd, se, sf] = shadingCtm;
211752
+ const shadingDet = sa * sd - sb * sc;
208914
211753
  const t0Dom = shDomain[0] ?? 0;
208915
211754
  const t1Dom = shDomain[1] ?? 1;
208916
211755
  for (let iy = 0; iy < imgH; iy++) {
@@ -208921,8 +211760,10 @@ function renderShadingDictToImage(doc, shDict, shadingCtm, targetBox, fillAlpha,
208921
211760
  const dxPdf = xPdf - e;
208922
211761
  const xs = (d2 * dxPdf - c4 * dyPdf) / det;
208923
211762
  const ys = (-b3 * dxPdf + a3 * dyPdf) / det;
208924
- if (shBBox && (xs < shBBox[0] || xs > shBBox[2] || ys < shBBox[1] || ys > shBBox[3])) {
208925
- continue;
211763
+ if (shBBox) {
211764
+ const bboxX = (sd * (xPdf - se) - sc * (yPdf - sf)) / shadingDet;
211765
+ const bboxY = (-sb * (xPdf - se) + sa * (yPdf - sf)) / shadingDet;
211766
+ if (bboxX < shBBox[0] || bboxX > shBBox[2] || bboxY < shBBox[1] || bboxY > shBBox[3]) continue;
208926
211767
  }
208927
211768
  let comps;
208928
211769
  if (shType === 1) {
@@ -209222,7 +212063,8 @@ function evaluateContentStreamToDisplayList(params) {
209222
212063
  const shDict = shNode?.kind === "dict" ? shNode : shNode?.kind === "stream" ? shNode.dict : void 0;
209223
212064
  const shStream = shNode?.kind === "stream" ? shNode : void 0;
209224
212065
  if (shDict) {
209225
- const targetBox = st.clipRect ?? [0, 0, params.width, params.height];
212066
+ const [originX, originY] = params.origin ?? [0, 0];
212067
+ const targetBox = st.clipRect ?? [originX, originY, originX + params.width, originY + params.height];
209226
212068
  const img = renderShadingDictToImage(
209227
212069
  params.cosDoc,
209228
212070
  shDict,
@@ -209261,12 +212103,10 @@ function evaluateContentStreamToDisplayList(params) {
209261
212103
  } else if (operator === "RG" || operator === "SC" || operator === "SCN") {
209262
212104
  st.strokeColor = resolveScColorOperands(operator === "RG" ? "DeviceRGB" : st.strokeColorSpaceName, ops, activeResources);
209263
212105
  } else if (operator === "k") {
209264
- const c4 = num(0), m = num(1), y = num(2), k = num(3);
209265
- st.fillColor = { r: (1 - c4) * (1 - k), g: (1 - m) * (1 - k), b: (1 - y) * (1 - k) };
212106
+ st.fillColor = resolveScColorOperands("DeviceCMYK", ops, activeResources);
209266
212107
  st.fillPatternName = void 0;
209267
212108
  } else if (operator === "K") {
209268
- const c4 = num(0), m = num(1), y = num(2), k = num(3);
209269
- st.strokeColor = { r: (1 - c4) * (1 - k), g: (1 - m) * (1 - k), b: (1 - y) * (1 - k) };
212109
+ st.strokeColor = resolveScColorOperands("DeviceCMYK", ops, activeResources);
209270
212110
  } else if (operator === "gs" && params.cosDoc && activeResources && ops[0]?.kind === "name") {
209271
212111
  const extDict = params.cosDoc.resolveDict(dictGet(activeResources, "ExtGState"));
209272
212112
  const gsDict = extDict ? params.cosDoc.resolveDict(dictGet(extDict, ops[0].decoded)) : void 0;
@@ -209475,7 +212315,7 @@ function evaluateContentStreamToDisplayList(params) {
209475
212315
  stateStack.pop();
209476
212316
  capturedOperations = parentOperations;
209477
212317
  }
209478
- if (compositeGroup) emit({ kind: "group", value: { operations: children8, alpha: st.fillAlpha, blendMode: st.blendMode, clipRect: st.clipRect } });
212318
+ if (compositeGroup) emit({ kind: "group", value: { operations: children8, alpha: st.fillAlpha, isolated, bboxClip: nextClipPaths?.[0], blendMode: st.blendMode, clipRect: st.clipRect } });
209479
212319
  };
209480
212320
  const walkNodes = (nodes, mcid, actualText, activeResources = params.resourcesDict, activeFonts = fonts, depth = 0) => {
209481
212321
  for (const node3 of nodes) {
@@ -210059,6 +212899,7 @@ function evaluateContentStreamToDisplayList(params) {
210059
212899
  pageIndex: params.pageIndex,
210060
212900
  width: params.width,
210061
212901
  height: params.height,
212902
+ ...params.origin ? { origin: params.origin } : {},
210062
212903
  rotation: params.rotation ?? 0,
210063
212904
  glyphs,
210064
212905
  paths,
@@ -211529,7 +214370,7 @@ var PdfPage = class {
211529
214370
  return [n0.value, n1.value, n2.value, n3.value];
211530
214371
  }
211531
214372
  }
211532
- return [0, 0, 612, 792];
214373
+ return key === "MediaBox" ? [0, 0, 612, 792] : this.resolveBox("MediaBox");
211533
214374
  }
211534
214375
  getMediaBox() {
211535
214376
  return this.resolveBox("MediaBox");
@@ -212202,16 +215043,19 @@ var PdfPage = class {
212202
215043
  });
212203
215044
  }
212204
215045
  }
212205
- return evaluateContentStreamToDisplayList({
215046
+ const mediaBox = this.getMediaBox(), cropBox = this.getCropBox();
215047
+ const originX = Math.min(mediaBox[0], mediaBox[2]), originY = Math.min(mediaBox[1], mediaBox[3]);
215048
+ return { ...evaluateContentStreamToDisplayList({
212206
215049
  pageIndex: this.index,
212207
215050
  width: width2,
212208
215051
  height,
215052
+ origin: [originX, originY],
212209
215053
  rotation: this.getRotation(),
212210
215054
  nodes: baseNodes,
212211
215055
  cosDoc: this.cosDoc,
212212
215056
  resourcesDict: evalResourcesDict,
212213
215057
  annotations: extractPageAnnotations(this.cosDoc, this.pageDict)
212214
- });
215058
+ }), cropBox: [cropBox[0] - originX, cropBox[1] - originY, cropBox[2] - originX, cropBox[3] - originY] };
212215
215059
  }
212216
215060
  extractPage(options) {
212217
215061
  const dl = this.evaluateDisplayList();
@@ -212229,10 +215073,10 @@ var PdfPage = class {
212229
215073
  return extractTablesFromDisplayList(this.evaluateDisplayList());
212230
215074
  }
212231
215075
  renderToBitmap(options) {
212232
- return renderDisplayListToBitmap(this.evaluateDisplayList(), options);
215076
+ return renderDisplayListToBitmap(this.evaluateDisplayList({ hideAnnotations: options?.hideAnnotations }), options);
212233
215077
  }
212234
215078
  renderToPng(options) {
212235
- return renderDisplayListToPng(this.evaluateDisplayList(), options);
215079
+ return renderDisplayListToPng(this.evaluateDisplayList({ hideAnnotations: options?.hideAnnotations }), options);
212236
215080
  }
212237
215081
  };
212238
215082
  function createStandardFontHandle(standardName) {
@@ -213282,7 +216126,7 @@ function prepareStroke(path2, scale2) {
213282
216126
  }
213283
216127
  return { matrix: matrix2, width: width2, dashArray, dashPhase };
213284
216128
  }
213285
- function strokeContours(path2, pageHeight, scale2) {
216129
+ function strokeContours(path2, pageHeight, scale2, originX = 0, originY = 0) {
213286
216130
  const stroke = prepareStroke(path2, scale2);
213287
216131
  if (!stroke) return [];
213288
216132
  const inverse2 = inverseStrokeMatrix(stroke.matrix);
@@ -213294,8 +216138,8 @@ function strokeContours(path2, pageHeight, scale2) {
213294
216138
  (inverse2[1] * x + inverse2[3] * y + inverse2[5]) * strokeScale
213295
216139
  ];
213296
216140
  const toScreen = ([x, y]) => [
213297
- (a3 * x / strokeScale + c4 * y / strokeScale + e) * scale2,
213298
- (pageHeight - b3 * x / strokeScale - d2 * y / strokeScale - f2) * scale2
216141
+ (a3 * x / strokeScale + c4 * y / strokeScale + e - originX) * scale2,
216142
+ (pageHeight + originY - b3 * x / strokeScale - d2 * y / strokeScale - f2) * scale2
213299
216143
  ];
213300
216144
  const contours = strokeOutlines(
213301
216145
  segmentsToScreenPaths(path2.segments, pageHeight, scale2, project),
@@ -213453,18 +216297,34 @@ function renderSoftMask(mask, displayList, scale2) {
213453
216297
  }
213454
216298
  return bitmap;
213455
216299
  }
213456
- function hasBlendModes(operations) {
213457
- return operations.some((operation) => !!operation.value.blendMode && operation.value.blendMode !== "Normal" && operation.value.blendMode !== "Compatible" || operation.kind === "group" && hasBlendModes(operation.value.operations));
216300
+ function getDisplayListCropBox(list) {
216301
+ const full = [0, 0, list.width, list.height];
216302
+ const box = list.cropBox;
216303
+ if (!box || !box.every(Number.isFinite)) return full;
216304
+ const x0 = Math.max(0, Math.min(box[0], box[2]));
216305
+ const y0 = Math.max(0, Math.min(box[1], box[3]));
216306
+ const x1 = Math.min(list.width, Math.max(box[0], box[2]));
216307
+ const y1 = Math.min(list.height, Math.max(box[1], box[3]));
216308
+ return x1 > x0 && y1 > y0 ? [x0, y0, x1, y1] : full;
216309
+ }
216310
+ function hasCompositingEffects(operations, includeSoftMasks = false) {
216311
+ return operations.some((operation) => includeSoftMasks && !!operation.value.softMask || !!operation.value.blendMode && operation.value.blendMode !== "Normal" && operation.value.blendMode !== "Compatible" || operation.kind === "group" && hasCompositingEffects(operation.value.operations, includeSoftMasks));
216312
+ }
216313
+ function needsGroupBackdrop(group) {
216314
+ return group.isolated === false && !!group.softMask && hasCompositingEffects(group.operations, true);
213458
216315
  }
213459
216316
  function renderDisplayListToBitmap(displayList, options = {}) {
213460
216317
  const baseScale = options.scale ?? (options.dpi ? options.dpi / 72 : 1.5);
213461
216318
  const scaleX = options.dpiX !== void 0 ? options.dpiX / 72 : baseScale;
213462
216319
  const scaleY = options.dpiY !== void 0 ? options.dpiY / 72 : baseScale;
213463
216320
  const scale2 = scaleX;
216321
+ const [originX, originY] = displayList.origin ?? [0, 0];
216322
+ const pageTop = originY + displayList.height;
216323
+ const toScreen = (x, y) => [(x - originX) * scale2, (pageTop - y) * scale2];
213464
216324
  const width2 = Math.max(1, Math.round(displayList.width * scale2));
213465
216325
  const height = Math.max(1, Math.round(displayList.height * scale2));
213466
216326
  const rgba = new Uint8Array(width2 * height * 4);
213467
- const deferBackground = !options.transparent && hasBlendModes(paintOperations(displayList));
216327
+ const deferBackground = !options.transparent && hasCompositingEffects(paintOperations(displayList));
213468
216328
  const transparent = options.transparent || deferBackground;
213469
216329
  const bg = options.background ?? { r: 1, g: 1, b: 1 };
213470
216330
  const bgR = transparent ? 0 : Math.round(bg.r * 255);
@@ -213489,14 +216349,27 @@ function renderDisplayListToBitmap(displayList, options = {}) {
213489
216349
  let operation = original.kind === "glyph" ? { kind: "path", value: glyphPaint(original.value) } : original;
213490
216350
  if (operation.kind === "group") {
213491
216351
  const group = operation.value;
213492
- const bitmap = renderDisplayListToBitmap({ ...displayList, rotation: 0, operations: group.operations }, { ...options, scale: scale2, dpiX: void 0, dpiY: void 0, cropRect: void 0, transparent: true });
216352
+ let operations = group.operations;
216353
+ if (needsGroupBackdrop(group)) {
216354
+ operations = [{ kind: "image", value: {
216355
+ name: "GroupBackdrop",
216356
+ width: width2,
216357
+ height,
216358
+ decodedRgba: rgba.slice(),
216359
+ matrix: [width2 / scale2, 0, 0, height / scale2, originX, pageTop - height / scale2],
216360
+ colorSpace: "DeviceRGB",
216361
+ bitsPerComponent: 8,
216362
+ ...group.bboxClip ? { clipPaths: [group.bboxClip] } : {}
216363
+ } }, ...operations];
216364
+ }
216365
+ const bitmap = renderDisplayListToBitmap({ ...displayList, rotation: 0, operations }, { ...options, scale: scale2, dpiX: void 0, dpiY: void 0, cropRect: void 0, useCropBox: false, transparent: true });
213493
216366
  for (let i = 3; i < bitmap.data.length; i += 4) bitmap.data[i] = Math.round(bitmap.data[i] * group.alpha);
213494
216367
  operation = { kind: "image", value: {
213495
216368
  name: "TransparencyGroup",
213496
216369
  width: bitmap.width,
213497
216370
  height: bitmap.height,
213498
216371
  decodedRgba: bitmap.data,
213499
- matrix: [bitmap.width / scale2, 0, 0, bitmap.height / scale2, 0, displayList.height - bitmap.height / scale2],
216372
+ matrix: [bitmap.width / scale2, 0, 0, bitmap.height / scale2, originX, pageTop - bitmap.height / scale2],
213500
216373
  colorSpace: "DeviceRGB",
213501
216374
  bitsPerComponent: 8,
213502
216375
  blendMode: group.blendMode,
@@ -213510,7 +216383,7 @@ function renderDisplayListToBitmap(displayList, options = {}) {
213510
216383
  for (const clip2 of clips) {
213511
216384
  const { segments, fillRule } = "segments" in clip2 ? clip2 : { segments: clip2, fillRule: "nonzero" };
213512
216385
  const layer = new Uint8Array(width2 * height * 4);
213513
- fillEdgesScanline4x4(layer, width2, height, pathsToEdges(segmentsToScreenPaths(segments, displayList.height, scale2), true), { r: 1, g: 1, b: 1 }, 1, fillRule);
216386
+ fillEdgesScanline4x4(layer, width2, height, pathsToEdges(segmentsToScreenPaths(segments, displayList.height, scale2, toScreen), true), { r: 1, g: 1, b: 1 }, 1, fillRule);
213514
216387
  for (let i = 3; i < layer.length; i += 4) clipMask[i] = Math.round(clipMask[i] * layer[i] / 255);
213515
216388
  }
213516
216389
  cachedClips = clips;
@@ -213557,15 +216430,15 @@ function renderDisplayListToBitmap(displayList, options = {}) {
213557
216430
  if (operation.kind === "path") {
213558
216431
  const path2 = operation.value;
213559
216432
  if (path2.fillColor) {
213560
- const edges2 = pathsToEdges(segmentsToScreenPaths(path2.segments, displayList.height, scale2), true);
213561
- const clipScreen = path2.clipRect ? [path2.clipRect[0] * scale2, (displayList.height - path2.clipRect[3]) * scale2, path2.clipRect[2] * scale2, (displayList.height - path2.clipRect[1]) * scale2] : void 0;
216433
+ const edges2 = pathsToEdges(segmentsToScreenPaths(path2.segments, displayList.height, scale2, toScreen), true);
216434
+ const clipScreen = path2.clipRect ? [(path2.clipRect[0] - originX) * scale2, (pageTop - path2.clipRect[3]) * scale2, (path2.clipRect[2] - originX) * scale2, (pageTop - path2.clipRect[1]) * scale2] : void 0;
213562
216435
  fillEdgesScanline4x4(rgba, width2, height, edges2, path2.fillColor, path2.fillAlpha ?? 1, path2.fillRule ?? "nonzero", clipScreen, original.kind === "glyph" ? aaTxt : aaVec, path2.blendMode, clipMask);
213563
216436
  }
213564
216437
  if (path2.strokeColor) {
213565
216438
  const rawSw = path2.strokeWidth * scale2 * (path2.strokeMatrix ? Math.hypot(path2.strokeMatrix[0], path2.strokeMatrix[1]) : 1);
213566
216439
  const strokeAlpha = options.thinLineMode === "shape" && rawSw < 1 ? (path2.strokeAlpha ?? 1) * Math.max(0.25, rawSw) : path2.strokeAlpha ?? 1;
213567
- const edges2 = pathsToEdges(strokeContours(path2, displayList.height, scale2).map((points) => ({ points, closed: true })));
213568
- const clipScreen = path2.clipRect ? [path2.clipRect[0] * scale2, (displayList.height - path2.clipRect[3]) * scale2, path2.clipRect[2] * scale2, (displayList.height - path2.clipRect[1]) * scale2] : void 0;
216440
+ const edges2 = pathsToEdges(strokeContours(path2, displayList.height, scale2, originX, originY).map((points) => ({ points, closed: true })));
216441
+ const clipScreen = path2.clipRect ? [(path2.clipRect[0] - originX) * scale2, (pageTop - path2.clipRect[3]) * scale2, (path2.clipRect[2] - originX) * scale2, (pageTop - path2.clipRect[1]) * scale2] : void 0;
213569
216442
  fillEdgesScanline4x4(
213570
216443
  rgba,
213571
216444
  width2,
@@ -213588,12 +216461,12 @@ function renderDisplayListToBitmap(displayList, options = {}) {
213588
216461
  if (Math.abs(det) <= 1e-8) continue;
213589
216462
  const cornersPdfX = [e, a3 + e, a3 + c4 + e, c4 + e];
213590
216463
  const cornersPdfY = [f2, b3 + f2, b3 + d2 + f2, d2 + f2];
213591
- const cornersPx = cornersPdfX.map((cx) => cx * scale2);
213592
- const cornersPy = cornersPdfY.map((cy) => (displayList.height - cy) * scale2);
213593
- const clipMinPx = img.clipRect ? Math.floor(img.clipRect[0] * scale2) : 0;
213594
- const clipMaxPx = img.clipRect ? Math.ceil(img.clipRect[2] * scale2) - 1 : width2 - 1;
213595
- const clipMinPy = img.clipRect ? Math.floor((displayList.height - img.clipRect[3]) * scale2) : 0;
213596
- const clipMaxPy = img.clipRect ? Math.ceil((displayList.height - img.clipRect[1]) * scale2) - 1 : height - 1;
216464
+ const cornersPx = cornersPdfX.map((cx) => (cx - originX) * scale2);
216465
+ const cornersPy = cornersPdfY.map((cy) => (pageTop - cy) * scale2);
216466
+ const clipMinPx = img.clipRect ? Math.floor((img.clipRect[0] - originX) * scale2) : 0;
216467
+ const clipMaxPx = img.clipRect ? Math.ceil((img.clipRect[2] - originX) * scale2) - 1 : width2 - 1;
216468
+ const clipMinPy = img.clipRect ? Math.floor((pageTop - img.clipRect[3]) * scale2) : 0;
216469
+ const clipMaxPy = img.clipRect ? Math.ceil((pageTop - img.clipRect[1]) * scale2) - 1 : height - 1;
213597
216470
  const minPx = Math.max(0, clipMinPx, Math.floor(Math.min(...cornersPx)));
213598
216471
  const maxPx = Math.min(width2 - 1, clipMaxPx, Math.ceil(Math.max(...cornersPx)) - 1);
213599
216472
  const minPy = Math.max(0, clipMinPy, Math.floor(Math.min(...cornersPy)));
@@ -213610,11 +216483,11 @@ function renderDisplayListToBitmap(displayList, options = {}) {
213610
216483
  const smooth = Math.fround((s1 + s2 + Math.hypot(s1 - s2, 2 * cross)) / 2) <= 1;
213611
216484
  const sample2 = new Float64Array(4);
213612
216485
  for (let py = minPy; py <= maxPy; py++) {
213613
- const yPdf = displayList.height - (py + 0.5) / scale2;
216486
+ const yPdf = pageTop - (py + 0.5) / scale2;
213614
216487
  if (img.clipRect && (yPdf < img.clipRect[1] || yPdf > img.clipRect[3])) continue;
213615
216488
  const dyPdf = yPdf - f2;
213616
216489
  for (let px = minPx; px <= maxPx; px++) {
213617
- const xPdf = (px + 0.5) / scale2;
216490
+ const xPdf = originX + (px + 0.5) / scale2;
213618
216491
  if (img.clipRect && (xPdf < img.clipRect[0] || xPdf > img.clipRect[2])) continue;
213619
216492
  const dxPdf = xPdf - e;
213620
216493
  const u = (d2 * dxPdf - c4 * dyPdf) / det;
@@ -213675,6 +216548,15 @@ function renderDisplayListToBitmap(displayList, options = {}) {
213675
216548
  }
213676
216549
  result2 = { width: targetW, height: targetH, data: resampled };
213677
216550
  }
216551
+ if (options.useCropBox) {
216552
+ const box = getDisplayListCropBox(displayList);
216553
+ result2 = cropRgbaBitmap(result2, {
216554
+ x: box[0] * scaleX,
216555
+ y: (displayList.height - box[3]) * scaleY,
216556
+ width: (box[2] - box[0]) * scaleX,
216557
+ height: (box[3] - box[1]) * scaleY
216558
+ });
216559
+ }
213678
216560
  result2 = rotateRgbaBitmapQuarterTurns(result2, displayList.rotation ?? 0);
213679
216561
  if (options.cropRect) {
213680
216562
  result2 = cropRgbaBitmap(result2, options.cropRect);
@@ -213703,23 +216585,6 @@ function collectLeavesForRaster(cosDoc, node3, out = [], visited = /* @__PURE__
213703
216585
  }
213704
216586
  return out;
213705
216587
  }
213706
- function extractBoxArray(cosDoc, dict, key) {
213707
- let cur = dict;
213708
- const visited = /* @__PURE__ */ new Set();
213709
- while (cur && !visited.has(cur)) {
213710
- visited.add(cur);
213711
- const arr = cosDoc.resolveArray(dictGet(cur, key));
213712
- if (arr && arr.items.length >= 4) {
213713
- const nums = arr.items.slice(0, 4).map((item) => {
213714
- const r = cosDoc.resolve(item);
213715
- return r?.kind === "number" ? r.value : 0;
213716
- });
213717
- return [nums[0], nums[1], nums[2], nums[3]];
213718
- }
213719
- cur = cosDoc.resolveDict(dictGet(cur, "Parent"));
213720
- }
213721
- return void 0;
213722
- }
213723
216588
  function renderPdfPageToBitmap(pdfBytes, pageIndex = 0, options) {
213724
216589
  const cos = pdfBytes instanceof Uint8Array ? parseCosDocument(pdfBytes) : pdfBytes;
213725
216590
  const catalog = cos.resolveDict(cos.rootRef);
@@ -213728,35 +216593,7 @@ function renderPdfPageToBitmap(pdfBytes, pageIndex = 0, options) {
213728
216593
  if (!leaf) throw new Error(`Page index ${pageIndex} out of bounds`);
213729
216594
  const resolvedIndex = leaves.indexOf(leaf);
213730
216595
  const page = new PdfPage(cos, leaf.ref, leaf.dict, resolvedIndex);
213731
- const { cropRect, ...restOptions } = options ?? {};
213732
- let bitmap = renderDisplayListToBitmap(
213733
- // CropBox is in unrotated page coordinates. Apply page rotation after it.
213734
- { ...page.evaluateDisplayList({ hideAnnotations: options?.hideAnnotations }), rotation: 0 },
213735
- restOptions
213736
- );
213737
- if (options?.useCropBox) {
213738
- const cropBox = extractBoxArray(cos, leaf.dict, "CropBox");
213739
- if (cropBox) {
213740
- const mediaBox = extractBoxArray(cos, leaf.dict, "MediaBox") ?? [0, 0, page.getSize().width, page.getSize().height];
213741
- const baseScale = options.scale ?? (options.dpi ? options.dpi / 72 : 1.5);
213742
- const scaleX = options.dpiX !== void 0 ? options.dpiX / 72 : baseScale;
213743
- const scaleY = options.dpiY !== void 0 ? options.dpiY / 72 : baseScale;
213744
- const mediaH = mediaBox[3] - mediaBox[1];
213745
- const bx = Math.round((cropBox[0] - mediaBox[0]) * scaleX);
213746
- const by = Math.round((mediaH - (cropBox[3] - mediaBox[1])) * scaleY);
213747
- const bw = Math.max(1, Math.round(Math.abs(cropBox[2] - cropBox[0]) * scaleX));
213748
- const bh = Math.max(1, Math.round(Math.abs(cropBox[3] - cropBox[1]) * scaleY));
213749
- bitmap = cropRgbaBitmap(bitmap, { x: bx, y: by, width: bw, height: bh });
213750
- }
213751
- }
213752
- const rotation = page.getRotation();
213753
- if (rotation === 90 || rotation === 180 || rotation === 270) {
213754
- bitmap = rotateRgbaBitmapQuarterTurns(bitmap, rotation);
213755
- }
213756
- if (cropRect) {
213757
- bitmap = cropRgbaBitmap(bitmap, cropRect);
213758
- }
213759
- return bitmap;
216596
+ return page.renderToBitmap(options);
213760
216597
  }
213761
216598
  function renderPdfPageToPng(pdfBytes, pageIndex = 0, options) {
213762
216599
  const bmp = renderPdfPageToBitmap(pdfBytes, pageIndex, options);