@taptap/maker 0.0.37-beta.1 → 0.0.37-beta.11

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.
@@ -0,0 +1,2594 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __commonJS = (cb, mod) => function __require2() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+
34
+ // node_modules/pngjs/lib/chunkstream.js
35
+ var require_chunkstream = __commonJS({
36
+ "node_modules/pngjs/lib/chunkstream.js"(exports, module) {
37
+ "use strict";
38
+ var util = __require("util");
39
+ var Stream = __require("stream");
40
+ var ChunkStream = module.exports = function() {
41
+ Stream.call(this);
42
+ this._buffers = [];
43
+ this._buffered = 0;
44
+ this._reads = [];
45
+ this._paused = false;
46
+ this._encoding = "utf8";
47
+ this.writable = true;
48
+ };
49
+ util.inherits(ChunkStream, Stream);
50
+ ChunkStream.prototype.read = function(length, callback) {
51
+ this._reads.push({
52
+ length: Math.abs(length),
53
+ // if length < 0 then at most this length
54
+ allowLess: length < 0,
55
+ func: callback
56
+ });
57
+ process.nextTick(
58
+ function() {
59
+ this._process();
60
+ if (this._paused && this._reads && this._reads.length > 0) {
61
+ this._paused = false;
62
+ this.emit("drain");
63
+ }
64
+ }.bind(this)
65
+ );
66
+ };
67
+ ChunkStream.prototype.write = function(data, encoding) {
68
+ if (!this.writable) {
69
+ this.emit("error", new Error("Stream not writable"));
70
+ return false;
71
+ }
72
+ let dataBuffer;
73
+ if (Buffer.isBuffer(data)) {
74
+ dataBuffer = data;
75
+ } else {
76
+ dataBuffer = Buffer.from(data, encoding || this._encoding);
77
+ }
78
+ this._buffers.push(dataBuffer);
79
+ this._buffered += dataBuffer.length;
80
+ this._process();
81
+ if (this._reads && this._reads.length === 0) {
82
+ this._paused = true;
83
+ }
84
+ return this.writable && !this._paused;
85
+ };
86
+ ChunkStream.prototype.end = function(data, encoding) {
87
+ if (data) {
88
+ this.write(data, encoding);
89
+ }
90
+ this.writable = false;
91
+ if (!this._buffers) {
92
+ return;
93
+ }
94
+ if (this._buffers.length === 0) {
95
+ this._end();
96
+ } else {
97
+ this._buffers.push(null);
98
+ this._process();
99
+ }
100
+ };
101
+ ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
102
+ ChunkStream.prototype._end = function() {
103
+ if (this._reads.length > 0) {
104
+ this.emit("error", new Error("Unexpected end of input"));
105
+ }
106
+ this.destroy();
107
+ };
108
+ ChunkStream.prototype.destroy = function() {
109
+ if (!this._buffers) {
110
+ return;
111
+ }
112
+ this.writable = false;
113
+ this._reads = null;
114
+ this._buffers = null;
115
+ this.emit("close");
116
+ };
117
+ ChunkStream.prototype._processReadAllowingLess = function(read) {
118
+ this._reads.shift();
119
+ let smallerBuf = this._buffers[0];
120
+ if (smallerBuf.length > read.length) {
121
+ this._buffered -= read.length;
122
+ this._buffers[0] = smallerBuf.slice(read.length);
123
+ read.func.call(this, smallerBuf.slice(0, read.length));
124
+ } else {
125
+ this._buffered -= smallerBuf.length;
126
+ this._buffers.shift();
127
+ read.func.call(this, smallerBuf);
128
+ }
129
+ };
130
+ ChunkStream.prototype._processRead = function(read) {
131
+ this._reads.shift();
132
+ let pos = 0;
133
+ let count = 0;
134
+ let data = Buffer.alloc(read.length);
135
+ while (pos < read.length) {
136
+ let buf = this._buffers[count++];
137
+ let len = Math.min(buf.length, read.length - pos);
138
+ buf.copy(data, pos, 0, len);
139
+ pos += len;
140
+ if (len !== buf.length) {
141
+ this._buffers[--count] = buf.slice(len);
142
+ }
143
+ }
144
+ if (count > 0) {
145
+ this._buffers.splice(0, count);
146
+ }
147
+ this._buffered -= read.length;
148
+ read.func.call(this, data);
149
+ };
150
+ ChunkStream.prototype._process = function() {
151
+ try {
152
+ while (this._buffered > 0 && this._reads && this._reads.length > 0) {
153
+ let read = this._reads[0];
154
+ if (read.allowLess) {
155
+ this._processReadAllowingLess(read);
156
+ } else if (this._buffered >= read.length) {
157
+ this._processRead(read);
158
+ } else {
159
+ break;
160
+ }
161
+ }
162
+ if (this._buffers && !this.writable) {
163
+ this._end();
164
+ }
165
+ } catch (ex) {
166
+ this.emit("error", ex);
167
+ }
168
+ };
169
+ }
170
+ });
171
+
172
+ // node_modules/pngjs/lib/interlace.js
173
+ var require_interlace = __commonJS({
174
+ "node_modules/pngjs/lib/interlace.js"(exports) {
175
+ "use strict";
176
+ var imagePasses = [
177
+ {
178
+ // pass 1 - 1px
179
+ x: [0],
180
+ y: [0]
181
+ },
182
+ {
183
+ // pass 2 - 1px
184
+ x: [4],
185
+ y: [0]
186
+ },
187
+ {
188
+ // pass 3 - 2px
189
+ x: [0, 4],
190
+ y: [4]
191
+ },
192
+ {
193
+ // pass 4 - 4px
194
+ x: [2, 6],
195
+ y: [0, 4]
196
+ },
197
+ {
198
+ // pass 5 - 8px
199
+ x: [0, 2, 4, 6],
200
+ y: [2, 6]
201
+ },
202
+ {
203
+ // pass 6 - 16px
204
+ x: [1, 3, 5, 7],
205
+ y: [0, 2, 4, 6]
206
+ },
207
+ {
208
+ // pass 7 - 32px
209
+ x: [0, 1, 2, 3, 4, 5, 6, 7],
210
+ y: [1, 3, 5, 7]
211
+ }
212
+ ];
213
+ exports.getImagePasses = function(width, height) {
214
+ let images = [];
215
+ let xLeftOver = width % 8;
216
+ let yLeftOver = height % 8;
217
+ let xRepeats = (width - xLeftOver) / 8;
218
+ let yRepeats = (height - yLeftOver) / 8;
219
+ for (let i = 0; i < imagePasses.length; i++) {
220
+ let pass = imagePasses[i];
221
+ let passWidth = xRepeats * pass.x.length;
222
+ let passHeight = yRepeats * pass.y.length;
223
+ for (let j = 0; j < pass.x.length; j++) {
224
+ if (pass.x[j] < xLeftOver) {
225
+ passWidth++;
226
+ } else {
227
+ break;
228
+ }
229
+ }
230
+ for (let j = 0; j < pass.y.length; j++) {
231
+ if (pass.y[j] < yLeftOver) {
232
+ passHeight++;
233
+ } else {
234
+ break;
235
+ }
236
+ }
237
+ if (passWidth > 0 && passHeight > 0) {
238
+ images.push({ width: passWidth, height: passHeight, index: i });
239
+ }
240
+ }
241
+ return images;
242
+ };
243
+ exports.getInterlaceIterator = function(width) {
244
+ return function(x, y, pass) {
245
+ let outerXLeftOver = x % imagePasses[pass].x.length;
246
+ let outerX = (x - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver];
247
+ let outerYLeftOver = y % imagePasses[pass].y.length;
248
+ let outerY = (y - outerYLeftOver) / imagePasses[pass].y.length * 8 + imagePasses[pass].y[outerYLeftOver];
249
+ return outerX * 4 + outerY * width * 4;
250
+ };
251
+ };
252
+ }
253
+ });
254
+
255
+ // node_modules/pngjs/lib/paeth-predictor.js
256
+ var require_paeth_predictor = __commonJS({
257
+ "node_modules/pngjs/lib/paeth-predictor.js"(exports, module) {
258
+ "use strict";
259
+ module.exports = function paethPredictor(left, above, upLeft) {
260
+ let paeth = left + above - upLeft;
261
+ let pLeft = Math.abs(paeth - left);
262
+ let pAbove = Math.abs(paeth - above);
263
+ let pUpLeft = Math.abs(paeth - upLeft);
264
+ if (pLeft <= pAbove && pLeft <= pUpLeft) {
265
+ return left;
266
+ }
267
+ if (pAbove <= pUpLeft) {
268
+ return above;
269
+ }
270
+ return upLeft;
271
+ };
272
+ }
273
+ });
274
+
275
+ // node_modules/pngjs/lib/filter-parse.js
276
+ var require_filter_parse = __commonJS({
277
+ "node_modules/pngjs/lib/filter-parse.js"(exports, module) {
278
+ "use strict";
279
+ var interlaceUtils = require_interlace();
280
+ var paethPredictor = require_paeth_predictor();
281
+ function getByteWidth(width, bpp, depth) {
282
+ let byteWidth = width * bpp;
283
+ if (depth !== 8) {
284
+ byteWidth = Math.ceil(byteWidth / (8 / depth));
285
+ }
286
+ return byteWidth;
287
+ }
288
+ var Filter = module.exports = function(bitmapInfo, dependencies) {
289
+ let width = bitmapInfo.width;
290
+ let height = bitmapInfo.height;
291
+ let interlace = bitmapInfo.interlace;
292
+ let bpp = bitmapInfo.bpp;
293
+ let depth = bitmapInfo.depth;
294
+ this.read = dependencies.read;
295
+ this.write = dependencies.write;
296
+ this.complete = dependencies.complete;
297
+ this._imageIndex = 0;
298
+ this._images = [];
299
+ if (interlace) {
300
+ let passes = interlaceUtils.getImagePasses(width, height);
301
+ for (let i = 0; i < passes.length; i++) {
302
+ this._images.push({
303
+ byteWidth: getByteWidth(passes[i].width, bpp, depth),
304
+ height: passes[i].height,
305
+ lineIndex: 0
306
+ });
307
+ }
308
+ } else {
309
+ this._images.push({
310
+ byteWidth: getByteWidth(width, bpp, depth),
311
+ height,
312
+ lineIndex: 0
313
+ });
314
+ }
315
+ if (depth === 8) {
316
+ this._xComparison = bpp;
317
+ } else if (depth === 16) {
318
+ this._xComparison = bpp * 2;
319
+ } else {
320
+ this._xComparison = 1;
321
+ }
322
+ };
323
+ Filter.prototype.start = function() {
324
+ this.read(
325
+ this._images[this._imageIndex].byteWidth + 1,
326
+ this._reverseFilterLine.bind(this)
327
+ );
328
+ };
329
+ Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
330
+ let xComparison = this._xComparison;
331
+ let xBiggerThan = xComparison - 1;
332
+ for (let x = 0; x < byteWidth; x++) {
333
+ let rawByte = rawData[1 + x];
334
+ let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
335
+ unfilteredLine[x] = rawByte + f1Left;
336
+ }
337
+ };
338
+ Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
339
+ let lastLine = this._lastLine;
340
+ for (let x = 0; x < byteWidth; x++) {
341
+ let rawByte = rawData[1 + x];
342
+ let f2Up = lastLine ? lastLine[x] : 0;
343
+ unfilteredLine[x] = rawByte + f2Up;
344
+ }
345
+ };
346
+ Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
347
+ let xComparison = this._xComparison;
348
+ let xBiggerThan = xComparison - 1;
349
+ let lastLine = this._lastLine;
350
+ for (let x = 0; x < byteWidth; x++) {
351
+ let rawByte = rawData[1 + x];
352
+ let f3Up = lastLine ? lastLine[x] : 0;
353
+ let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
354
+ let f3Add = Math.floor((f3Left + f3Up) / 2);
355
+ unfilteredLine[x] = rawByte + f3Add;
356
+ }
357
+ };
358
+ Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
359
+ let xComparison = this._xComparison;
360
+ let xBiggerThan = xComparison - 1;
361
+ let lastLine = this._lastLine;
362
+ for (let x = 0; x < byteWidth; x++) {
363
+ let rawByte = rawData[1 + x];
364
+ let f4Up = lastLine ? lastLine[x] : 0;
365
+ let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
366
+ let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
367
+ let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
368
+ unfilteredLine[x] = rawByte + f4Add;
369
+ }
370
+ };
371
+ Filter.prototype._reverseFilterLine = function(rawData) {
372
+ let filter = rawData[0];
373
+ let unfilteredLine;
374
+ let currentImage = this._images[this._imageIndex];
375
+ let byteWidth = currentImage.byteWidth;
376
+ if (filter === 0) {
377
+ unfilteredLine = rawData.slice(1, byteWidth + 1);
378
+ } else {
379
+ unfilteredLine = Buffer.alloc(byteWidth);
380
+ switch (filter) {
381
+ case 1:
382
+ this._unFilterType1(rawData, unfilteredLine, byteWidth);
383
+ break;
384
+ case 2:
385
+ this._unFilterType2(rawData, unfilteredLine, byteWidth);
386
+ break;
387
+ case 3:
388
+ this._unFilterType3(rawData, unfilteredLine, byteWidth);
389
+ break;
390
+ case 4:
391
+ this._unFilterType4(rawData, unfilteredLine, byteWidth);
392
+ break;
393
+ default:
394
+ throw new Error("Unrecognised filter type - " + filter);
395
+ }
396
+ }
397
+ this.write(unfilteredLine);
398
+ currentImage.lineIndex++;
399
+ if (currentImage.lineIndex >= currentImage.height) {
400
+ this._lastLine = null;
401
+ this._imageIndex++;
402
+ currentImage = this._images[this._imageIndex];
403
+ } else {
404
+ this._lastLine = unfilteredLine;
405
+ }
406
+ if (currentImage) {
407
+ this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
408
+ } else {
409
+ this._lastLine = null;
410
+ this.complete();
411
+ }
412
+ };
413
+ }
414
+ });
415
+
416
+ // node_modules/pngjs/lib/filter-parse-async.js
417
+ var require_filter_parse_async = __commonJS({
418
+ "node_modules/pngjs/lib/filter-parse-async.js"(exports, module) {
419
+ "use strict";
420
+ var util = __require("util");
421
+ var ChunkStream = require_chunkstream();
422
+ var Filter = require_filter_parse();
423
+ var FilterAsync = module.exports = function(bitmapInfo) {
424
+ ChunkStream.call(this);
425
+ let buffers = [];
426
+ let that = this;
427
+ this._filter = new Filter(bitmapInfo, {
428
+ read: this.read.bind(this),
429
+ write: function(buffer) {
430
+ buffers.push(buffer);
431
+ },
432
+ complete: function() {
433
+ that.emit("complete", Buffer.concat(buffers));
434
+ }
435
+ });
436
+ this._filter.start();
437
+ };
438
+ util.inherits(FilterAsync, ChunkStream);
439
+ }
440
+ });
441
+
442
+ // node_modules/pngjs/lib/constants.js
443
+ var require_constants = __commonJS({
444
+ "node_modules/pngjs/lib/constants.js"(exports, module) {
445
+ "use strict";
446
+ module.exports = {
447
+ PNG_SIGNATURE: [137, 80, 78, 71, 13, 10, 26, 10],
448
+ TYPE_IHDR: 1229472850,
449
+ TYPE_IEND: 1229278788,
450
+ TYPE_IDAT: 1229209940,
451
+ TYPE_PLTE: 1347179589,
452
+ TYPE_tRNS: 1951551059,
453
+ // eslint-disable-line camelcase
454
+ TYPE_gAMA: 1732332865,
455
+ // eslint-disable-line camelcase
456
+ // color-type bits
457
+ COLORTYPE_GRAYSCALE: 0,
458
+ COLORTYPE_PALETTE: 1,
459
+ COLORTYPE_COLOR: 2,
460
+ COLORTYPE_ALPHA: 4,
461
+ // e.g. grayscale and alpha
462
+ // color-type combinations
463
+ COLORTYPE_PALETTE_COLOR: 3,
464
+ COLORTYPE_COLOR_ALPHA: 6,
465
+ COLORTYPE_TO_BPP_MAP: {
466
+ 0: 1,
467
+ 2: 3,
468
+ 3: 1,
469
+ 4: 2,
470
+ 6: 4
471
+ },
472
+ GAMMA_DIVISION: 1e5
473
+ };
474
+ }
475
+ });
476
+
477
+ // node_modules/pngjs/lib/crc.js
478
+ var require_crc = __commonJS({
479
+ "node_modules/pngjs/lib/crc.js"(exports, module) {
480
+ "use strict";
481
+ var crcTable = [];
482
+ (function() {
483
+ for (let i = 0; i < 256; i++) {
484
+ let currentCrc = i;
485
+ for (let j = 0; j < 8; j++) {
486
+ if (currentCrc & 1) {
487
+ currentCrc = 3988292384 ^ currentCrc >>> 1;
488
+ } else {
489
+ currentCrc = currentCrc >>> 1;
490
+ }
491
+ }
492
+ crcTable[i] = currentCrc;
493
+ }
494
+ })();
495
+ var CrcCalculator = module.exports = function() {
496
+ this._crc = -1;
497
+ };
498
+ CrcCalculator.prototype.write = function(data) {
499
+ for (let i = 0; i < data.length; i++) {
500
+ this._crc = crcTable[(this._crc ^ data[i]) & 255] ^ this._crc >>> 8;
501
+ }
502
+ return true;
503
+ };
504
+ CrcCalculator.prototype.crc32 = function() {
505
+ return this._crc ^ -1;
506
+ };
507
+ CrcCalculator.crc32 = function(buf) {
508
+ let crc = -1;
509
+ for (let i = 0; i < buf.length; i++) {
510
+ crc = crcTable[(crc ^ buf[i]) & 255] ^ crc >>> 8;
511
+ }
512
+ return crc ^ -1;
513
+ };
514
+ }
515
+ });
516
+
517
+ // node_modules/pngjs/lib/parser.js
518
+ var require_parser = __commonJS({
519
+ "node_modules/pngjs/lib/parser.js"(exports, module) {
520
+ "use strict";
521
+ var constants = require_constants();
522
+ var CrcCalculator = require_crc();
523
+ var Parser = module.exports = function(options, dependencies) {
524
+ this._options = options;
525
+ options.checkCRC = options.checkCRC !== false;
526
+ this._hasIHDR = false;
527
+ this._hasIEND = false;
528
+ this._emittedHeadersFinished = false;
529
+ this._palette = [];
530
+ this._colorType = 0;
531
+ this._chunks = {};
532
+ this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
533
+ this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
534
+ this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
535
+ this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
536
+ this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
537
+ this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
538
+ this.read = dependencies.read;
539
+ this.error = dependencies.error;
540
+ this.metadata = dependencies.metadata;
541
+ this.gamma = dependencies.gamma;
542
+ this.transColor = dependencies.transColor;
543
+ this.palette = dependencies.palette;
544
+ this.parsed = dependencies.parsed;
545
+ this.inflateData = dependencies.inflateData;
546
+ this.finished = dependencies.finished;
547
+ this.simpleTransparency = dependencies.simpleTransparency;
548
+ this.headersFinished = dependencies.headersFinished || function() {
549
+ };
550
+ };
551
+ Parser.prototype.start = function() {
552
+ this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));
553
+ };
554
+ Parser.prototype._parseSignature = function(data) {
555
+ let signature = constants.PNG_SIGNATURE;
556
+ for (let i = 0; i < signature.length; i++) {
557
+ if (data[i] !== signature[i]) {
558
+ this.error(new Error("Invalid file signature"));
559
+ return;
560
+ }
561
+ }
562
+ this.read(8, this._parseChunkBegin.bind(this));
563
+ };
564
+ Parser.prototype._parseChunkBegin = function(data) {
565
+ let length = data.readUInt32BE(0);
566
+ let type = data.readUInt32BE(4);
567
+ let name = "";
568
+ for (let i = 4; i < 8; i++) {
569
+ name += String.fromCharCode(data[i]);
570
+ }
571
+ let ancillary = Boolean(data[4] & 32);
572
+ if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
573
+ this.error(new Error("Expected IHDR on beggining"));
574
+ return;
575
+ }
576
+ this._crc = new CrcCalculator();
577
+ this._crc.write(Buffer.from(name));
578
+ if (this._chunks[type]) {
579
+ return this._chunks[type](length);
580
+ }
581
+ if (!ancillary) {
582
+ this.error(new Error("Unsupported critical chunk type " + name));
583
+ return;
584
+ }
585
+ this.read(length + 4, this._skipChunk.bind(this));
586
+ };
587
+ Parser.prototype._skipChunk = function() {
588
+ this.read(8, this._parseChunkBegin.bind(this));
589
+ };
590
+ Parser.prototype._handleChunkEnd = function() {
591
+ this.read(4, this._parseChunkEnd.bind(this));
592
+ };
593
+ Parser.prototype._parseChunkEnd = function(data) {
594
+ let fileCrc = data.readInt32BE(0);
595
+ let calcCrc = this._crc.crc32();
596
+ if (this._options.checkCRC && calcCrc !== fileCrc) {
597
+ this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc));
598
+ return;
599
+ }
600
+ if (!this._hasIEND) {
601
+ this.read(8, this._parseChunkBegin.bind(this));
602
+ }
603
+ };
604
+ Parser.prototype._handleIHDR = function(length) {
605
+ this.read(length, this._parseIHDR.bind(this));
606
+ };
607
+ Parser.prototype._parseIHDR = function(data) {
608
+ this._crc.write(data);
609
+ let width = data.readUInt32BE(0);
610
+ let height = data.readUInt32BE(4);
611
+ let depth = data[8];
612
+ let colorType = data[9];
613
+ let compr = data[10];
614
+ let filter = data[11];
615
+ let interlace = data[12];
616
+ if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
617
+ this.error(new Error("Unsupported bit depth " + depth));
618
+ return;
619
+ }
620
+ if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
621
+ this.error(new Error("Unsupported color type"));
622
+ return;
623
+ }
624
+ if (compr !== 0) {
625
+ this.error(new Error("Unsupported compression method"));
626
+ return;
627
+ }
628
+ if (filter !== 0) {
629
+ this.error(new Error("Unsupported filter method"));
630
+ return;
631
+ }
632
+ if (interlace !== 0 && interlace !== 1) {
633
+ this.error(new Error("Unsupported interlace method"));
634
+ return;
635
+ }
636
+ this._colorType = colorType;
637
+ let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
638
+ this._hasIHDR = true;
639
+ this.metadata({
640
+ width,
641
+ height,
642
+ depth,
643
+ interlace: Boolean(interlace),
644
+ palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
645
+ color: Boolean(colorType & constants.COLORTYPE_COLOR),
646
+ alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
647
+ bpp,
648
+ colorType
649
+ });
650
+ this._handleChunkEnd();
651
+ };
652
+ Parser.prototype._handlePLTE = function(length) {
653
+ this.read(length, this._parsePLTE.bind(this));
654
+ };
655
+ Parser.prototype._parsePLTE = function(data) {
656
+ this._crc.write(data);
657
+ let entries = Math.floor(data.length / 3);
658
+ for (let i = 0; i < entries; i++) {
659
+ this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 255]);
660
+ }
661
+ this.palette(this._palette);
662
+ this._handleChunkEnd();
663
+ };
664
+ Parser.prototype._handleTRNS = function(length) {
665
+ this.simpleTransparency();
666
+ this.read(length, this._parseTRNS.bind(this));
667
+ };
668
+ Parser.prototype._parseTRNS = function(data) {
669
+ this._crc.write(data);
670
+ if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
671
+ if (this._palette.length === 0) {
672
+ this.error(new Error("Transparency chunk must be after palette"));
673
+ return;
674
+ }
675
+ if (data.length > this._palette.length) {
676
+ this.error(new Error("More transparent colors than palette size"));
677
+ return;
678
+ }
679
+ for (let i = 0; i < data.length; i++) {
680
+ this._palette[i][3] = data[i];
681
+ }
682
+ this.palette(this._palette);
683
+ }
684
+ if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
685
+ this.transColor([data.readUInt16BE(0)]);
686
+ }
687
+ if (this._colorType === constants.COLORTYPE_COLOR) {
688
+ this.transColor([
689
+ data.readUInt16BE(0),
690
+ data.readUInt16BE(2),
691
+ data.readUInt16BE(4)
692
+ ]);
693
+ }
694
+ this._handleChunkEnd();
695
+ };
696
+ Parser.prototype._handleGAMA = function(length) {
697
+ this.read(length, this._parseGAMA.bind(this));
698
+ };
699
+ Parser.prototype._parseGAMA = function(data) {
700
+ this._crc.write(data);
701
+ this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
702
+ this._handleChunkEnd();
703
+ };
704
+ Parser.prototype._handleIDAT = function(length) {
705
+ if (!this._emittedHeadersFinished) {
706
+ this._emittedHeadersFinished = true;
707
+ this.headersFinished();
708
+ }
709
+ this.read(-length, this._parseIDAT.bind(this, length));
710
+ };
711
+ Parser.prototype._parseIDAT = function(length, data) {
712
+ this._crc.write(data);
713
+ if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
714
+ throw new Error("Expected palette not found");
715
+ }
716
+ this.inflateData(data);
717
+ let leftOverLength = length - data.length;
718
+ if (leftOverLength > 0) {
719
+ this._handleIDAT(leftOverLength);
720
+ } else {
721
+ this._handleChunkEnd();
722
+ }
723
+ };
724
+ Parser.prototype._handleIEND = function(length) {
725
+ this.read(length, this._parseIEND.bind(this));
726
+ };
727
+ Parser.prototype._parseIEND = function(data) {
728
+ this._crc.write(data);
729
+ this._hasIEND = true;
730
+ this._handleChunkEnd();
731
+ if (this.finished) {
732
+ this.finished();
733
+ }
734
+ };
735
+ }
736
+ });
737
+
738
+ // node_modules/pngjs/lib/bitmapper.js
739
+ var require_bitmapper = __commonJS({
740
+ "node_modules/pngjs/lib/bitmapper.js"(exports) {
741
+ "use strict";
742
+ var interlaceUtils = require_interlace();
743
+ var pixelBppMapper = [
744
+ // 0 - dummy entry
745
+ function() {
746
+ },
747
+ // 1 - L
748
+ // 0: 0, 1: 0, 2: 0, 3: 0xff
749
+ function(pxData, data, pxPos, rawPos) {
750
+ if (rawPos === data.length) {
751
+ throw new Error("Ran out of data");
752
+ }
753
+ let pixel = data[rawPos];
754
+ pxData[pxPos] = pixel;
755
+ pxData[pxPos + 1] = pixel;
756
+ pxData[pxPos + 2] = pixel;
757
+ pxData[pxPos + 3] = 255;
758
+ },
759
+ // 2 - LA
760
+ // 0: 0, 1: 0, 2: 0, 3: 1
761
+ function(pxData, data, pxPos, rawPos) {
762
+ if (rawPos + 1 >= data.length) {
763
+ throw new Error("Ran out of data");
764
+ }
765
+ let pixel = data[rawPos];
766
+ pxData[pxPos] = pixel;
767
+ pxData[pxPos + 1] = pixel;
768
+ pxData[pxPos + 2] = pixel;
769
+ pxData[pxPos + 3] = data[rawPos + 1];
770
+ },
771
+ // 3 - RGB
772
+ // 0: 0, 1: 1, 2: 2, 3: 0xff
773
+ function(pxData, data, pxPos, rawPos) {
774
+ if (rawPos + 2 >= data.length) {
775
+ throw new Error("Ran out of data");
776
+ }
777
+ pxData[pxPos] = data[rawPos];
778
+ pxData[pxPos + 1] = data[rawPos + 1];
779
+ pxData[pxPos + 2] = data[rawPos + 2];
780
+ pxData[pxPos + 3] = 255;
781
+ },
782
+ // 4 - RGBA
783
+ // 0: 0, 1: 1, 2: 2, 3: 3
784
+ function(pxData, data, pxPos, rawPos) {
785
+ if (rawPos + 3 >= data.length) {
786
+ throw new Error("Ran out of data");
787
+ }
788
+ pxData[pxPos] = data[rawPos];
789
+ pxData[pxPos + 1] = data[rawPos + 1];
790
+ pxData[pxPos + 2] = data[rawPos + 2];
791
+ pxData[pxPos + 3] = data[rawPos + 3];
792
+ }
793
+ ];
794
+ var pixelBppCustomMapper = [
795
+ // 0 - dummy entry
796
+ function() {
797
+ },
798
+ // 1 - L
799
+ // 0: 0, 1: 0, 2: 0, 3: 0xff
800
+ function(pxData, pixelData, pxPos, maxBit) {
801
+ let pixel = pixelData[0];
802
+ pxData[pxPos] = pixel;
803
+ pxData[pxPos + 1] = pixel;
804
+ pxData[pxPos + 2] = pixel;
805
+ pxData[pxPos + 3] = maxBit;
806
+ },
807
+ // 2 - LA
808
+ // 0: 0, 1: 0, 2: 0, 3: 1
809
+ function(pxData, pixelData, pxPos) {
810
+ let pixel = pixelData[0];
811
+ pxData[pxPos] = pixel;
812
+ pxData[pxPos + 1] = pixel;
813
+ pxData[pxPos + 2] = pixel;
814
+ pxData[pxPos + 3] = pixelData[1];
815
+ },
816
+ // 3 - RGB
817
+ // 0: 0, 1: 1, 2: 2, 3: 0xff
818
+ function(pxData, pixelData, pxPos, maxBit) {
819
+ pxData[pxPos] = pixelData[0];
820
+ pxData[pxPos + 1] = pixelData[1];
821
+ pxData[pxPos + 2] = pixelData[2];
822
+ pxData[pxPos + 3] = maxBit;
823
+ },
824
+ // 4 - RGBA
825
+ // 0: 0, 1: 1, 2: 2, 3: 3
826
+ function(pxData, pixelData, pxPos) {
827
+ pxData[pxPos] = pixelData[0];
828
+ pxData[pxPos + 1] = pixelData[1];
829
+ pxData[pxPos + 2] = pixelData[2];
830
+ pxData[pxPos + 3] = pixelData[3];
831
+ }
832
+ ];
833
+ function bitRetriever(data, depth) {
834
+ let leftOver = [];
835
+ let i = 0;
836
+ function split() {
837
+ if (i === data.length) {
838
+ throw new Error("Ran out of data");
839
+ }
840
+ let byte = data[i];
841
+ i++;
842
+ let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
843
+ switch (depth) {
844
+ default:
845
+ throw new Error("unrecognised depth");
846
+ case 16:
847
+ byte2 = data[i];
848
+ i++;
849
+ leftOver.push((byte << 8) + byte2);
850
+ break;
851
+ case 4:
852
+ byte2 = byte & 15;
853
+ byte1 = byte >> 4;
854
+ leftOver.push(byte1, byte2);
855
+ break;
856
+ case 2:
857
+ byte4 = byte & 3;
858
+ byte3 = byte >> 2 & 3;
859
+ byte2 = byte >> 4 & 3;
860
+ byte1 = byte >> 6 & 3;
861
+ leftOver.push(byte1, byte2, byte3, byte4);
862
+ break;
863
+ case 1:
864
+ byte8 = byte & 1;
865
+ byte7 = byte >> 1 & 1;
866
+ byte6 = byte >> 2 & 1;
867
+ byte5 = byte >> 3 & 1;
868
+ byte4 = byte >> 4 & 1;
869
+ byte3 = byte >> 5 & 1;
870
+ byte2 = byte >> 6 & 1;
871
+ byte1 = byte >> 7 & 1;
872
+ leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
873
+ break;
874
+ }
875
+ }
876
+ return {
877
+ get: function(count) {
878
+ while (leftOver.length < count) {
879
+ split();
880
+ }
881
+ let returner = leftOver.slice(0, count);
882
+ leftOver = leftOver.slice(count);
883
+ return returner;
884
+ },
885
+ resetAfterLine: function() {
886
+ leftOver.length = 0;
887
+ },
888
+ end: function() {
889
+ if (i !== data.length) {
890
+ throw new Error("extra data found");
891
+ }
892
+ }
893
+ };
894
+ }
895
+ function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) {
896
+ let imageWidth = image.width;
897
+ let imageHeight = image.height;
898
+ let imagePass = image.index;
899
+ for (let y = 0; y < imageHeight; y++) {
900
+ for (let x = 0; x < imageWidth; x++) {
901
+ let pxPos = getPxPos(x, y, imagePass);
902
+ pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
903
+ rawPos += bpp;
904
+ }
905
+ }
906
+ return rawPos;
907
+ }
908
+ function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) {
909
+ let imageWidth = image.width;
910
+ let imageHeight = image.height;
911
+ let imagePass = image.index;
912
+ for (let y = 0; y < imageHeight; y++) {
913
+ for (let x = 0; x < imageWidth; x++) {
914
+ let pixelData = bits.get(bpp);
915
+ let pxPos = getPxPos(x, y, imagePass);
916
+ pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
917
+ }
918
+ bits.resetAfterLine();
919
+ }
920
+ }
921
+ exports.dataToBitMap = function(data, bitmapInfo) {
922
+ let width = bitmapInfo.width;
923
+ let height = bitmapInfo.height;
924
+ let depth = bitmapInfo.depth;
925
+ let bpp = bitmapInfo.bpp;
926
+ let interlace = bitmapInfo.interlace;
927
+ let bits;
928
+ if (depth !== 8) {
929
+ bits = bitRetriever(data, depth);
930
+ }
931
+ let pxData;
932
+ if (depth <= 8) {
933
+ pxData = Buffer.alloc(width * height * 4);
934
+ } else {
935
+ pxData = new Uint16Array(width * height * 4);
936
+ }
937
+ let maxBit = Math.pow(2, depth) - 1;
938
+ let rawPos = 0;
939
+ let images;
940
+ let getPxPos;
941
+ if (interlace) {
942
+ images = interlaceUtils.getImagePasses(width, height);
943
+ getPxPos = interlaceUtils.getInterlaceIterator(width, height);
944
+ } else {
945
+ let nonInterlacedPxPos = 0;
946
+ getPxPos = function() {
947
+ let returner = nonInterlacedPxPos;
948
+ nonInterlacedPxPos += 4;
949
+ return returner;
950
+ };
951
+ images = [{ width, height }];
952
+ }
953
+ for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {
954
+ if (depth === 8) {
955
+ rawPos = mapImage8Bit(
956
+ images[imageIndex],
957
+ pxData,
958
+ getPxPos,
959
+ bpp,
960
+ data,
961
+ rawPos
962
+ );
963
+ } else {
964
+ mapImageCustomBit(
965
+ images[imageIndex],
966
+ pxData,
967
+ getPxPos,
968
+ bpp,
969
+ bits,
970
+ maxBit
971
+ );
972
+ }
973
+ }
974
+ if (depth === 8) {
975
+ if (rawPos !== data.length) {
976
+ throw new Error("extra data found");
977
+ }
978
+ } else {
979
+ bits.end();
980
+ }
981
+ return pxData;
982
+ };
983
+ }
984
+ });
985
+
986
+ // node_modules/pngjs/lib/format-normaliser.js
987
+ var require_format_normaliser = __commonJS({
988
+ "node_modules/pngjs/lib/format-normaliser.js"(exports, module) {
989
+ "use strict";
990
+ function dePalette(indata, outdata, width, height, palette) {
991
+ let pxPos = 0;
992
+ for (let y = 0; y < height; y++) {
993
+ for (let x = 0; x < width; x++) {
994
+ let color = palette[indata[pxPos]];
995
+ if (!color) {
996
+ throw new Error("index " + indata[pxPos] + " not in palette");
997
+ }
998
+ for (let i = 0; i < 4; i++) {
999
+ outdata[pxPos + i] = color[i];
1000
+ }
1001
+ pxPos += 4;
1002
+ }
1003
+ }
1004
+ }
1005
+ function replaceTransparentColor(indata, outdata, width, height, transColor) {
1006
+ let pxPos = 0;
1007
+ for (let y = 0; y < height; y++) {
1008
+ for (let x = 0; x < width; x++) {
1009
+ let makeTrans = false;
1010
+ if (transColor.length === 1) {
1011
+ if (transColor[0] === indata[pxPos]) {
1012
+ makeTrans = true;
1013
+ }
1014
+ } else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
1015
+ makeTrans = true;
1016
+ }
1017
+ if (makeTrans) {
1018
+ for (let i = 0; i < 4; i++) {
1019
+ outdata[pxPos + i] = 0;
1020
+ }
1021
+ }
1022
+ pxPos += 4;
1023
+ }
1024
+ }
1025
+ }
1026
+ function scaleDepth(indata, outdata, width, height, depth) {
1027
+ let maxOutSample = 255;
1028
+ let maxInSample = Math.pow(2, depth) - 1;
1029
+ let pxPos = 0;
1030
+ for (let y = 0; y < height; y++) {
1031
+ for (let x = 0; x < width; x++) {
1032
+ for (let i = 0; i < 4; i++) {
1033
+ outdata[pxPos + i] = Math.floor(
1034
+ indata[pxPos + i] * maxOutSample / maxInSample + 0.5
1035
+ );
1036
+ }
1037
+ pxPos += 4;
1038
+ }
1039
+ }
1040
+ }
1041
+ module.exports = function(indata, imageData, skipRescale = false) {
1042
+ let depth = imageData.depth;
1043
+ let width = imageData.width;
1044
+ let height = imageData.height;
1045
+ let colorType = imageData.colorType;
1046
+ let transColor = imageData.transColor;
1047
+ let palette = imageData.palette;
1048
+ let outdata = indata;
1049
+ if (colorType === 3) {
1050
+ dePalette(indata, outdata, width, height, palette);
1051
+ } else {
1052
+ if (transColor) {
1053
+ replaceTransparentColor(indata, outdata, width, height, transColor);
1054
+ }
1055
+ if (depth !== 8 && !skipRescale) {
1056
+ if (depth === 16) {
1057
+ outdata = Buffer.alloc(width * height * 4);
1058
+ }
1059
+ scaleDepth(indata, outdata, width, height, depth);
1060
+ }
1061
+ }
1062
+ return outdata;
1063
+ };
1064
+ }
1065
+ });
1066
+
1067
+ // node_modules/pngjs/lib/parser-async.js
1068
+ var require_parser_async = __commonJS({
1069
+ "node_modules/pngjs/lib/parser-async.js"(exports, module) {
1070
+ "use strict";
1071
+ var util = __require("util");
1072
+ var zlib = __require("zlib");
1073
+ var ChunkStream = require_chunkstream();
1074
+ var FilterAsync = require_filter_parse_async();
1075
+ var Parser = require_parser();
1076
+ var bitmapper = require_bitmapper();
1077
+ var formatNormaliser = require_format_normaliser();
1078
+ var ParserAsync = module.exports = function(options) {
1079
+ ChunkStream.call(this);
1080
+ this._parser = new Parser(options, {
1081
+ read: this.read.bind(this),
1082
+ error: this._handleError.bind(this),
1083
+ metadata: this._handleMetaData.bind(this),
1084
+ gamma: this.emit.bind(this, "gamma"),
1085
+ palette: this._handlePalette.bind(this),
1086
+ transColor: this._handleTransColor.bind(this),
1087
+ finished: this._finished.bind(this),
1088
+ inflateData: this._inflateData.bind(this),
1089
+ simpleTransparency: this._simpleTransparency.bind(this),
1090
+ headersFinished: this._headersFinished.bind(this)
1091
+ });
1092
+ this._options = options;
1093
+ this.writable = true;
1094
+ this._parser.start();
1095
+ };
1096
+ util.inherits(ParserAsync, ChunkStream);
1097
+ ParserAsync.prototype._handleError = function(err) {
1098
+ this.emit("error", err);
1099
+ this.writable = false;
1100
+ this.destroy();
1101
+ if (this._inflate && this._inflate.destroy) {
1102
+ this._inflate.destroy();
1103
+ }
1104
+ if (this._filter) {
1105
+ this._filter.destroy();
1106
+ this._filter.on("error", function() {
1107
+ });
1108
+ }
1109
+ this.errord = true;
1110
+ };
1111
+ ParserAsync.prototype._inflateData = function(data) {
1112
+ if (!this._inflate) {
1113
+ if (this._bitmapInfo.interlace) {
1114
+ this._inflate = zlib.createInflate();
1115
+ this._inflate.on("error", this.emit.bind(this, "error"));
1116
+ this._filter.on("complete", this._complete.bind(this));
1117
+ this._inflate.pipe(this._filter);
1118
+ } else {
1119
+ let rowSize = (this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7 >> 3) + 1;
1120
+ let imageSize = rowSize * this._bitmapInfo.height;
1121
+ let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
1122
+ this._inflate = zlib.createInflate({ chunkSize });
1123
+ let leftToInflate = imageSize;
1124
+ let emitError = this.emit.bind(this, "error");
1125
+ this._inflate.on("error", function(err) {
1126
+ if (!leftToInflate) {
1127
+ return;
1128
+ }
1129
+ emitError(err);
1130
+ });
1131
+ this._filter.on("complete", this._complete.bind(this));
1132
+ let filterWrite = this._filter.write.bind(this._filter);
1133
+ this._inflate.on("data", function(chunk) {
1134
+ if (!leftToInflate) {
1135
+ return;
1136
+ }
1137
+ if (chunk.length > leftToInflate) {
1138
+ chunk = chunk.slice(0, leftToInflate);
1139
+ }
1140
+ leftToInflate -= chunk.length;
1141
+ filterWrite(chunk);
1142
+ });
1143
+ this._inflate.on("end", this._filter.end.bind(this._filter));
1144
+ }
1145
+ }
1146
+ this._inflate.write(data);
1147
+ };
1148
+ ParserAsync.prototype._handleMetaData = function(metaData) {
1149
+ this._metaData = metaData;
1150
+ this._bitmapInfo = Object.create(metaData);
1151
+ this._filter = new FilterAsync(this._bitmapInfo);
1152
+ };
1153
+ ParserAsync.prototype._handleTransColor = function(transColor) {
1154
+ this._bitmapInfo.transColor = transColor;
1155
+ };
1156
+ ParserAsync.prototype._handlePalette = function(palette) {
1157
+ this._bitmapInfo.palette = palette;
1158
+ };
1159
+ ParserAsync.prototype._simpleTransparency = function() {
1160
+ this._metaData.alpha = true;
1161
+ };
1162
+ ParserAsync.prototype._headersFinished = function() {
1163
+ this.emit("metadata", this._metaData);
1164
+ };
1165
+ ParserAsync.prototype._finished = function() {
1166
+ if (this.errord) {
1167
+ return;
1168
+ }
1169
+ if (!this._inflate) {
1170
+ this.emit("error", "No Inflate block");
1171
+ } else {
1172
+ this._inflate.end();
1173
+ }
1174
+ };
1175
+ ParserAsync.prototype._complete = function(filteredData) {
1176
+ if (this.errord) {
1177
+ return;
1178
+ }
1179
+ let normalisedBitmapData;
1180
+ try {
1181
+ let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
1182
+ normalisedBitmapData = formatNormaliser(
1183
+ bitmapData,
1184
+ this._bitmapInfo,
1185
+ this._options.skipRescale
1186
+ );
1187
+ bitmapData = null;
1188
+ } catch (ex) {
1189
+ this._handleError(ex);
1190
+ return;
1191
+ }
1192
+ this.emit("parsed", normalisedBitmapData);
1193
+ };
1194
+ }
1195
+ });
1196
+
1197
+ // node_modules/pngjs/lib/bitpacker.js
1198
+ var require_bitpacker = __commonJS({
1199
+ "node_modules/pngjs/lib/bitpacker.js"(exports, module) {
1200
+ "use strict";
1201
+ var constants = require_constants();
1202
+ module.exports = function(dataIn, width, height, options) {
1203
+ let outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(
1204
+ options.colorType
1205
+ ) !== -1;
1206
+ if (options.colorType === options.inputColorType) {
1207
+ let bigEndian = (function() {
1208
+ let buffer = new ArrayBuffer(2);
1209
+ new DataView(buffer).setInt16(
1210
+ 0,
1211
+ 256,
1212
+ true
1213
+ /* littleEndian */
1214
+ );
1215
+ return new Int16Array(buffer)[0] !== 256;
1216
+ })();
1217
+ if (options.bitDepth === 8 || options.bitDepth === 16 && bigEndian) {
1218
+ return dataIn;
1219
+ }
1220
+ }
1221
+ let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
1222
+ let maxValue = 255;
1223
+ let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
1224
+ if (inBpp === 4 && !options.inputHasAlpha) {
1225
+ inBpp = 3;
1226
+ }
1227
+ let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
1228
+ if (options.bitDepth === 16) {
1229
+ maxValue = 65535;
1230
+ outBpp *= 2;
1231
+ }
1232
+ let outData = Buffer.alloc(width * height * outBpp);
1233
+ let inIndex = 0;
1234
+ let outIndex = 0;
1235
+ let bgColor = options.bgColor || {};
1236
+ if (bgColor.red === void 0) {
1237
+ bgColor.red = maxValue;
1238
+ }
1239
+ if (bgColor.green === void 0) {
1240
+ bgColor.green = maxValue;
1241
+ }
1242
+ if (bgColor.blue === void 0) {
1243
+ bgColor.blue = maxValue;
1244
+ }
1245
+ function getRGBA() {
1246
+ let red;
1247
+ let green;
1248
+ let blue;
1249
+ let alpha = maxValue;
1250
+ switch (options.inputColorType) {
1251
+ case constants.COLORTYPE_COLOR_ALPHA:
1252
+ alpha = data[inIndex + 3];
1253
+ red = data[inIndex];
1254
+ green = data[inIndex + 1];
1255
+ blue = data[inIndex + 2];
1256
+ break;
1257
+ case constants.COLORTYPE_COLOR:
1258
+ red = data[inIndex];
1259
+ green = data[inIndex + 1];
1260
+ blue = data[inIndex + 2];
1261
+ break;
1262
+ case constants.COLORTYPE_ALPHA:
1263
+ alpha = data[inIndex + 1];
1264
+ red = data[inIndex];
1265
+ green = red;
1266
+ blue = red;
1267
+ break;
1268
+ case constants.COLORTYPE_GRAYSCALE:
1269
+ red = data[inIndex];
1270
+ green = red;
1271
+ blue = red;
1272
+ break;
1273
+ default:
1274
+ throw new Error(
1275
+ "input color type:" + options.inputColorType + " is not supported at present"
1276
+ );
1277
+ }
1278
+ if (options.inputHasAlpha) {
1279
+ if (!outHasAlpha) {
1280
+ alpha /= maxValue;
1281
+ red = Math.min(
1282
+ Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0),
1283
+ maxValue
1284
+ );
1285
+ green = Math.min(
1286
+ Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0),
1287
+ maxValue
1288
+ );
1289
+ blue = Math.min(
1290
+ Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0),
1291
+ maxValue
1292
+ );
1293
+ }
1294
+ }
1295
+ return { red, green, blue, alpha };
1296
+ }
1297
+ for (let y = 0; y < height; y++) {
1298
+ for (let x = 0; x < width; x++) {
1299
+ let rgba = getRGBA(data, inIndex);
1300
+ switch (options.colorType) {
1301
+ case constants.COLORTYPE_COLOR_ALPHA:
1302
+ case constants.COLORTYPE_COLOR:
1303
+ if (options.bitDepth === 8) {
1304
+ outData[outIndex] = rgba.red;
1305
+ outData[outIndex + 1] = rgba.green;
1306
+ outData[outIndex + 2] = rgba.blue;
1307
+ if (outHasAlpha) {
1308
+ outData[outIndex + 3] = rgba.alpha;
1309
+ }
1310
+ } else {
1311
+ outData.writeUInt16BE(rgba.red, outIndex);
1312
+ outData.writeUInt16BE(rgba.green, outIndex + 2);
1313
+ outData.writeUInt16BE(rgba.blue, outIndex + 4);
1314
+ if (outHasAlpha) {
1315
+ outData.writeUInt16BE(rgba.alpha, outIndex + 6);
1316
+ }
1317
+ }
1318
+ break;
1319
+ case constants.COLORTYPE_ALPHA:
1320
+ case constants.COLORTYPE_GRAYSCALE: {
1321
+ let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
1322
+ if (options.bitDepth === 8) {
1323
+ outData[outIndex] = grayscale;
1324
+ if (outHasAlpha) {
1325
+ outData[outIndex + 1] = rgba.alpha;
1326
+ }
1327
+ } else {
1328
+ outData.writeUInt16BE(grayscale, outIndex);
1329
+ if (outHasAlpha) {
1330
+ outData.writeUInt16BE(rgba.alpha, outIndex + 2);
1331
+ }
1332
+ }
1333
+ break;
1334
+ }
1335
+ default:
1336
+ throw new Error("unrecognised color Type " + options.colorType);
1337
+ }
1338
+ inIndex += inBpp;
1339
+ outIndex += outBpp;
1340
+ }
1341
+ }
1342
+ return outData;
1343
+ };
1344
+ }
1345
+ });
1346
+
1347
+ // node_modules/pngjs/lib/filter-pack.js
1348
+ var require_filter_pack = __commonJS({
1349
+ "node_modules/pngjs/lib/filter-pack.js"(exports, module) {
1350
+ "use strict";
1351
+ var paethPredictor = require_paeth_predictor();
1352
+ function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
1353
+ for (let x = 0; x < byteWidth; x++) {
1354
+ rawData[rawPos + x] = pxData[pxPos + x];
1355
+ }
1356
+ }
1357
+ function filterSumNone(pxData, pxPos, byteWidth) {
1358
+ let sum = 0;
1359
+ let length = pxPos + byteWidth;
1360
+ for (let i = pxPos; i < length; i++) {
1361
+ sum += Math.abs(pxData[i]);
1362
+ }
1363
+ return sum;
1364
+ }
1365
+ function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
1366
+ for (let x = 0; x < byteWidth; x++) {
1367
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
1368
+ let val = pxData[pxPos + x] - left;
1369
+ rawData[rawPos + x] = val;
1370
+ }
1371
+ }
1372
+ function filterSumSub(pxData, pxPos, byteWidth, bpp) {
1373
+ let sum = 0;
1374
+ for (let x = 0; x < byteWidth; x++) {
1375
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
1376
+ let val = pxData[pxPos + x] - left;
1377
+ sum += Math.abs(val);
1378
+ }
1379
+ return sum;
1380
+ }
1381
+ function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
1382
+ for (let x = 0; x < byteWidth; x++) {
1383
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
1384
+ let val = pxData[pxPos + x] - up;
1385
+ rawData[rawPos + x] = val;
1386
+ }
1387
+ }
1388
+ function filterSumUp(pxData, pxPos, byteWidth) {
1389
+ let sum = 0;
1390
+ let length = pxPos + byteWidth;
1391
+ for (let x = pxPos; x < length; x++) {
1392
+ let up = pxPos > 0 ? pxData[x - byteWidth] : 0;
1393
+ let val = pxData[x] - up;
1394
+ sum += Math.abs(val);
1395
+ }
1396
+ return sum;
1397
+ }
1398
+ function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
1399
+ for (let x = 0; x < byteWidth; x++) {
1400
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
1401
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
1402
+ let val = pxData[pxPos + x] - (left + up >> 1);
1403
+ rawData[rawPos + x] = val;
1404
+ }
1405
+ }
1406
+ function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
1407
+ let sum = 0;
1408
+ for (let x = 0; x < byteWidth; x++) {
1409
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
1410
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
1411
+ let val = pxData[pxPos + x] - (left + up >> 1);
1412
+ sum += Math.abs(val);
1413
+ }
1414
+ return sum;
1415
+ }
1416
+ function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
1417
+ for (let x = 0; x < byteWidth; x++) {
1418
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
1419
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
1420
+ let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
1421
+ let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
1422
+ rawData[rawPos + x] = val;
1423
+ }
1424
+ }
1425
+ function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
1426
+ let sum = 0;
1427
+ for (let x = 0; x < byteWidth; x++) {
1428
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
1429
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
1430
+ let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
1431
+ let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
1432
+ sum += Math.abs(val);
1433
+ }
1434
+ return sum;
1435
+ }
1436
+ var filters = {
1437
+ 0: filterNone,
1438
+ 1: filterSub,
1439
+ 2: filterUp,
1440
+ 3: filterAvg,
1441
+ 4: filterPaeth
1442
+ };
1443
+ var filterSums = {
1444
+ 0: filterSumNone,
1445
+ 1: filterSumSub,
1446
+ 2: filterSumUp,
1447
+ 3: filterSumAvg,
1448
+ 4: filterSumPaeth
1449
+ };
1450
+ module.exports = function(pxData, width, height, options, bpp) {
1451
+ let filterTypes;
1452
+ if (!("filterType" in options) || options.filterType === -1) {
1453
+ filterTypes = [0, 1, 2, 3, 4];
1454
+ } else if (typeof options.filterType === "number") {
1455
+ filterTypes = [options.filterType];
1456
+ } else {
1457
+ throw new Error("unrecognised filter types");
1458
+ }
1459
+ if (options.bitDepth === 16) {
1460
+ bpp *= 2;
1461
+ }
1462
+ let byteWidth = width * bpp;
1463
+ let rawPos = 0;
1464
+ let pxPos = 0;
1465
+ let rawData = Buffer.alloc((byteWidth + 1) * height);
1466
+ let sel = filterTypes[0];
1467
+ for (let y = 0; y < height; y++) {
1468
+ if (filterTypes.length > 1) {
1469
+ let min = Infinity;
1470
+ for (let i = 0; i < filterTypes.length; i++) {
1471
+ let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
1472
+ if (sum < min) {
1473
+ sel = filterTypes[i];
1474
+ min = sum;
1475
+ }
1476
+ }
1477
+ }
1478
+ rawData[rawPos] = sel;
1479
+ rawPos++;
1480
+ filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
1481
+ rawPos += byteWidth;
1482
+ pxPos += byteWidth;
1483
+ }
1484
+ return rawData;
1485
+ };
1486
+ }
1487
+ });
1488
+
1489
+ // node_modules/pngjs/lib/packer.js
1490
+ var require_packer = __commonJS({
1491
+ "node_modules/pngjs/lib/packer.js"(exports, module) {
1492
+ "use strict";
1493
+ var constants = require_constants();
1494
+ var CrcStream = require_crc();
1495
+ var bitPacker = require_bitpacker();
1496
+ var filter = require_filter_pack();
1497
+ var zlib = __require("zlib");
1498
+ var Packer = module.exports = function(options) {
1499
+ this._options = options;
1500
+ options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
1501
+ options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
1502
+ options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
1503
+ options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
1504
+ options.deflateFactory = options.deflateFactory || zlib.createDeflate;
1505
+ options.bitDepth = options.bitDepth || 8;
1506
+ options.colorType = typeof options.colorType === "number" ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
1507
+ options.inputColorType = typeof options.inputColorType === "number" ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
1508
+ if ([
1509
+ constants.COLORTYPE_GRAYSCALE,
1510
+ constants.COLORTYPE_COLOR,
1511
+ constants.COLORTYPE_COLOR_ALPHA,
1512
+ constants.COLORTYPE_ALPHA
1513
+ ].indexOf(options.colorType) === -1) {
1514
+ throw new Error(
1515
+ "option color type:" + options.colorType + " is not supported at present"
1516
+ );
1517
+ }
1518
+ if ([
1519
+ constants.COLORTYPE_GRAYSCALE,
1520
+ constants.COLORTYPE_COLOR,
1521
+ constants.COLORTYPE_COLOR_ALPHA,
1522
+ constants.COLORTYPE_ALPHA
1523
+ ].indexOf(options.inputColorType) === -1) {
1524
+ throw new Error(
1525
+ "option input color type:" + options.inputColorType + " is not supported at present"
1526
+ );
1527
+ }
1528
+ if (options.bitDepth !== 8 && options.bitDepth !== 16) {
1529
+ throw new Error(
1530
+ "option bit depth:" + options.bitDepth + " is not supported at present"
1531
+ );
1532
+ }
1533
+ };
1534
+ Packer.prototype.getDeflateOptions = function() {
1535
+ return {
1536
+ chunkSize: this._options.deflateChunkSize,
1537
+ level: this._options.deflateLevel,
1538
+ strategy: this._options.deflateStrategy
1539
+ };
1540
+ };
1541
+ Packer.prototype.createDeflate = function() {
1542
+ return this._options.deflateFactory(this.getDeflateOptions());
1543
+ };
1544
+ Packer.prototype.filterData = function(data, width, height) {
1545
+ let packedData = bitPacker(data, width, height, this._options);
1546
+ let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
1547
+ let filteredData = filter(packedData, width, height, this._options, bpp);
1548
+ return filteredData;
1549
+ };
1550
+ Packer.prototype._packChunk = function(type, data) {
1551
+ let len = data ? data.length : 0;
1552
+ let buf = Buffer.alloc(len + 12);
1553
+ buf.writeUInt32BE(len, 0);
1554
+ buf.writeUInt32BE(type, 4);
1555
+ if (data) {
1556
+ data.copy(buf, 8);
1557
+ }
1558
+ buf.writeInt32BE(
1559
+ CrcStream.crc32(buf.slice(4, buf.length - 4)),
1560
+ buf.length - 4
1561
+ );
1562
+ return buf;
1563
+ };
1564
+ Packer.prototype.packGAMA = function(gamma) {
1565
+ let buf = Buffer.alloc(4);
1566
+ buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
1567
+ return this._packChunk(constants.TYPE_gAMA, buf);
1568
+ };
1569
+ Packer.prototype.packIHDR = function(width, height) {
1570
+ let buf = Buffer.alloc(13);
1571
+ buf.writeUInt32BE(width, 0);
1572
+ buf.writeUInt32BE(height, 4);
1573
+ buf[8] = this._options.bitDepth;
1574
+ buf[9] = this._options.colorType;
1575
+ buf[10] = 0;
1576
+ buf[11] = 0;
1577
+ buf[12] = 0;
1578
+ return this._packChunk(constants.TYPE_IHDR, buf);
1579
+ };
1580
+ Packer.prototype.packIDAT = function(data) {
1581
+ return this._packChunk(constants.TYPE_IDAT, data);
1582
+ };
1583
+ Packer.prototype.packIEND = function() {
1584
+ return this._packChunk(constants.TYPE_IEND, null);
1585
+ };
1586
+ }
1587
+ });
1588
+
1589
+ // node_modules/pngjs/lib/packer-async.js
1590
+ var require_packer_async = __commonJS({
1591
+ "node_modules/pngjs/lib/packer-async.js"(exports, module) {
1592
+ "use strict";
1593
+ var util = __require("util");
1594
+ var Stream = __require("stream");
1595
+ var constants = require_constants();
1596
+ var Packer = require_packer();
1597
+ var PackerAsync = module.exports = function(opt) {
1598
+ Stream.call(this);
1599
+ let options = opt || {};
1600
+ this._packer = new Packer(options);
1601
+ this._deflate = this._packer.createDeflate();
1602
+ this.readable = true;
1603
+ };
1604
+ util.inherits(PackerAsync, Stream);
1605
+ PackerAsync.prototype.pack = function(data, width, height, gamma) {
1606
+ this.emit("data", Buffer.from(constants.PNG_SIGNATURE));
1607
+ this.emit("data", this._packer.packIHDR(width, height));
1608
+ if (gamma) {
1609
+ this.emit("data", this._packer.packGAMA(gamma));
1610
+ }
1611
+ let filteredData = this._packer.filterData(data, width, height);
1612
+ this._deflate.on("error", this.emit.bind(this, "error"));
1613
+ this._deflate.on(
1614
+ "data",
1615
+ function(compressedData) {
1616
+ this.emit("data", this._packer.packIDAT(compressedData));
1617
+ }.bind(this)
1618
+ );
1619
+ this._deflate.on(
1620
+ "end",
1621
+ function() {
1622
+ this.emit("data", this._packer.packIEND());
1623
+ this.emit("end");
1624
+ }.bind(this)
1625
+ );
1626
+ this._deflate.end(filteredData);
1627
+ };
1628
+ }
1629
+ });
1630
+
1631
+ // node_modules/pngjs/lib/sync-inflate.js
1632
+ var require_sync_inflate = __commonJS({
1633
+ "node_modules/pngjs/lib/sync-inflate.js"(exports, module) {
1634
+ "use strict";
1635
+ var assert2 = __require("assert").ok;
1636
+ var zlib = __require("zlib");
1637
+ var util = __require("util");
1638
+ var kMaxLength = __require("buffer").kMaxLength;
1639
+ function Inflate(opts) {
1640
+ if (!(this instanceof Inflate)) {
1641
+ return new Inflate(opts);
1642
+ }
1643
+ if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
1644
+ opts.chunkSize = zlib.Z_MIN_CHUNK;
1645
+ }
1646
+ zlib.Inflate.call(this, opts);
1647
+ this._offset = this._offset === void 0 ? this._outOffset : this._offset;
1648
+ this._buffer = this._buffer || this._outBuffer;
1649
+ if (opts && opts.maxLength != null) {
1650
+ this._maxLength = opts.maxLength;
1651
+ }
1652
+ }
1653
+ function createInflate(opts) {
1654
+ return new Inflate(opts);
1655
+ }
1656
+ function _close(engine, callback) {
1657
+ if (callback) {
1658
+ process.nextTick(callback);
1659
+ }
1660
+ if (!engine._handle) {
1661
+ return;
1662
+ }
1663
+ engine._handle.close();
1664
+ engine._handle = null;
1665
+ }
1666
+ Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
1667
+ if (typeof asyncCb === "function") {
1668
+ return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
1669
+ }
1670
+ let self = this;
1671
+ let availInBefore = chunk && chunk.length;
1672
+ let availOutBefore = this._chunkSize - this._offset;
1673
+ let leftToInflate = this._maxLength;
1674
+ let inOff = 0;
1675
+ let buffers = [];
1676
+ let nread = 0;
1677
+ let error;
1678
+ this.on("error", function(err) {
1679
+ error = err;
1680
+ });
1681
+ function handleChunk(availInAfter, availOutAfter) {
1682
+ if (self._hadError) {
1683
+ return;
1684
+ }
1685
+ let have = availOutBefore - availOutAfter;
1686
+ assert2(have >= 0, "have should not go down");
1687
+ if (have > 0) {
1688
+ let out = self._buffer.slice(self._offset, self._offset + have);
1689
+ self._offset += have;
1690
+ if (out.length > leftToInflate) {
1691
+ out = out.slice(0, leftToInflate);
1692
+ }
1693
+ buffers.push(out);
1694
+ nread += out.length;
1695
+ leftToInflate -= out.length;
1696
+ if (leftToInflate === 0) {
1697
+ return false;
1698
+ }
1699
+ }
1700
+ if (availOutAfter === 0 || self._offset >= self._chunkSize) {
1701
+ availOutBefore = self._chunkSize;
1702
+ self._offset = 0;
1703
+ self._buffer = Buffer.allocUnsafe(self._chunkSize);
1704
+ }
1705
+ if (availOutAfter === 0) {
1706
+ inOff += availInBefore - availInAfter;
1707
+ availInBefore = availInAfter;
1708
+ return true;
1709
+ }
1710
+ return false;
1711
+ }
1712
+ assert2(this._handle, "zlib binding closed");
1713
+ let res;
1714
+ do {
1715
+ res = this._handle.writeSync(
1716
+ flushFlag,
1717
+ chunk,
1718
+ // in
1719
+ inOff,
1720
+ // in_off
1721
+ availInBefore,
1722
+ // in_len
1723
+ this._buffer,
1724
+ // out
1725
+ this._offset,
1726
+ //out_off
1727
+ availOutBefore
1728
+ );
1729
+ res = res || this._writeState;
1730
+ } while (!this._hadError && handleChunk(res[0], res[1]));
1731
+ if (this._hadError) {
1732
+ throw error;
1733
+ }
1734
+ if (nread >= kMaxLength) {
1735
+ _close(this);
1736
+ throw new RangeError(
1737
+ "Cannot create final Buffer. It would be larger than 0x" + kMaxLength.toString(16) + " bytes"
1738
+ );
1739
+ }
1740
+ let buf = Buffer.concat(buffers, nread);
1741
+ _close(this);
1742
+ return buf;
1743
+ };
1744
+ util.inherits(Inflate, zlib.Inflate);
1745
+ function zlibBufferSync(engine, buffer) {
1746
+ if (typeof buffer === "string") {
1747
+ buffer = Buffer.from(buffer);
1748
+ }
1749
+ if (!(buffer instanceof Buffer)) {
1750
+ throw new TypeError("Not a string or buffer");
1751
+ }
1752
+ let flushFlag = engine._finishFlushFlag;
1753
+ if (flushFlag == null) {
1754
+ flushFlag = zlib.Z_FINISH;
1755
+ }
1756
+ return engine._processChunk(buffer, flushFlag);
1757
+ }
1758
+ function inflateSync(buffer, opts) {
1759
+ return zlibBufferSync(new Inflate(opts), buffer);
1760
+ }
1761
+ module.exports = exports = inflateSync;
1762
+ exports.Inflate = Inflate;
1763
+ exports.createInflate = createInflate;
1764
+ exports.inflateSync = inflateSync;
1765
+ }
1766
+ });
1767
+
1768
+ // node_modules/pngjs/lib/sync-reader.js
1769
+ var require_sync_reader = __commonJS({
1770
+ "node_modules/pngjs/lib/sync-reader.js"(exports, module) {
1771
+ "use strict";
1772
+ var SyncReader = module.exports = function(buffer) {
1773
+ this._buffer = buffer;
1774
+ this._reads = [];
1775
+ };
1776
+ SyncReader.prototype.read = function(length, callback) {
1777
+ this._reads.push({
1778
+ length: Math.abs(length),
1779
+ // if length < 0 then at most this length
1780
+ allowLess: length < 0,
1781
+ func: callback
1782
+ });
1783
+ };
1784
+ SyncReader.prototype.process = function() {
1785
+ while (this._reads.length > 0 && this._buffer.length) {
1786
+ let read = this._reads[0];
1787
+ if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
1788
+ this._reads.shift();
1789
+ let buf = this._buffer;
1790
+ this._buffer = buf.slice(read.length);
1791
+ read.func.call(this, buf.slice(0, read.length));
1792
+ } else {
1793
+ break;
1794
+ }
1795
+ }
1796
+ if (this._reads.length > 0) {
1797
+ throw new Error("There are some read requests waitng on finished stream");
1798
+ }
1799
+ if (this._buffer.length > 0) {
1800
+ throw new Error("unrecognised content at end of stream");
1801
+ }
1802
+ };
1803
+ }
1804
+ });
1805
+
1806
+ // node_modules/pngjs/lib/filter-parse-sync.js
1807
+ var require_filter_parse_sync = __commonJS({
1808
+ "node_modules/pngjs/lib/filter-parse-sync.js"(exports) {
1809
+ "use strict";
1810
+ var SyncReader = require_sync_reader();
1811
+ var Filter = require_filter_parse();
1812
+ exports.process = function(inBuffer, bitmapInfo) {
1813
+ let outBuffers = [];
1814
+ let reader = new SyncReader(inBuffer);
1815
+ let filter = new Filter(bitmapInfo, {
1816
+ read: reader.read.bind(reader),
1817
+ write: function(bufferPart) {
1818
+ outBuffers.push(bufferPart);
1819
+ },
1820
+ complete: function() {
1821
+ }
1822
+ });
1823
+ filter.start();
1824
+ reader.process();
1825
+ return Buffer.concat(outBuffers);
1826
+ };
1827
+ }
1828
+ });
1829
+
1830
+ // node_modules/pngjs/lib/parser-sync.js
1831
+ var require_parser_sync = __commonJS({
1832
+ "node_modules/pngjs/lib/parser-sync.js"(exports, module) {
1833
+ "use strict";
1834
+ var hasSyncZlib = true;
1835
+ var zlib = __require("zlib");
1836
+ var inflateSync = require_sync_inflate();
1837
+ if (!zlib.deflateSync) {
1838
+ hasSyncZlib = false;
1839
+ }
1840
+ var SyncReader = require_sync_reader();
1841
+ var FilterSync = require_filter_parse_sync();
1842
+ var Parser = require_parser();
1843
+ var bitmapper = require_bitmapper();
1844
+ var formatNormaliser = require_format_normaliser();
1845
+ module.exports = function(buffer, options) {
1846
+ if (!hasSyncZlib) {
1847
+ throw new Error(
1848
+ "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
1849
+ );
1850
+ }
1851
+ let err;
1852
+ function handleError(_err_) {
1853
+ err = _err_;
1854
+ }
1855
+ let metaData;
1856
+ function handleMetaData(_metaData_) {
1857
+ metaData = _metaData_;
1858
+ }
1859
+ function handleTransColor(transColor) {
1860
+ metaData.transColor = transColor;
1861
+ }
1862
+ function handlePalette(palette) {
1863
+ metaData.palette = palette;
1864
+ }
1865
+ function handleSimpleTransparency() {
1866
+ metaData.alpha = true;
1867
+ }
1868
+ let gamma;
1869
+ function handleGamma(_gamma_) {
1870
+ gamma = _gamma_;
1871
+ }
1872
+ let inflateDataList = [];
1873
+ function handleInflateData(inflatedData2) {
1874
+ inflateDataList.push(inflatedData2);
1875
+ }
1876
+ let reader = new SyncReader(buffer);
1877
+ let parser = new Parser(options, {
1878
+ read: reader.read.bind(reader),
1879
+ error: handleError,
1880
+ metadata: handleMetaData,
1881
+ gamma: handleGamma,
1882
+ palette: handlePalette,
1883
+ transColor: handleTransColor,
1884
+ inflateData: handleInflateData,
1885
+ simpleTransparency: handleSimpleTransparency
1886
+ });
1887
+ parser.start();
1888
+ reader.process();
1889
+ if (err) {
1890
+ throw err;
1891
+ }
1892
+ let inflateData = Buffer.concat(inflateDataList);
1893
+ inflateDataList.length = 0;
1894
+ let inflatedData;
1895
+ if (metaData.interlace) {
1896
+ inflatedData = zlib.inflateSync(inflateData);
1897
+ } else {
1898
+ let rowSize = (metaData.width * metaData.bpp * metaData.depth + 7 >> 3) + 1;
1899
+ let imageSize = rowSize * metaData.height;
1900
+ inflatedData = inflateSync(inflateData, {
1901
+ chunkSize: imageSize,
1902
+ maxLength: imageSize
1903
+ });
1904
+ }
1905
+ inflateData = null;
1906
+ if (!inflatedData || !inflatedData.length) {
1907
+ throw new Error("bad png - invalid inflate data response");
1908
+ }
1909
+ let unfilteredData = FilterSync.process(inflatedData, metaData);
1910
+ inflateData = null;
1911
+ let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
1912
+ unfilteredData = null;
1913
+ let normalisedBitmapData = formatNormaliser(
1914
+ bitmapData,
1915
+ metaData,
1916
+ options.skipRescale
1917
+ );
1918
+ metaData.data = normalisedBitmapData;
1919
+ metaData.gamma = gamma || 0;
1920
+ return metaData;
1921
+ };
1922
+ }
1923
+ });
1924
+
1925
+ // node_modules/pngjs/lib/packer-sync.js
1926
+ var require_packer_sync = __commonJS({
1927
+ "node_modules/pngjs/lib/packer-sync.js"(exports, module) {
1928
+ "use strict";
1929
+ var hasSyncZlib = true;
1930
+ var zlib = __require("zlib");
1931
+ if (!zlib.deflateSync) {
1932
+ hasSyncZlib = false;
1933
+ }
1934
+ var constants = require_constants();
1935
+ var Packer = require_packer();
1936
+ module.exports = function(metaData, opt) {
1937
+ if (!hasSyncZlib) {
1938
+ throw new Error(
1939
+ "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
1940
+ );
1941
+ }
1942
+ let options = opt || {};
1943
+ let packer = new Packer(options);
1944
+ let chunks = [];
1945
+ chunks.push(Buffer.from(constants.PNG_SIGNATURE));
1946
+ chunks.push(packer.packIHDR(metaData.width, metaData.height));
1947
+ if (metaData.gamma) {
1948
+ chunks.push(packer.packGAMA(metaData.gamma));
1949
+ }
1950
+ let filteredData = packer.filterData(
1951
+ metaData.data,
1952
+ metaData.width,
1953
+ metaData.height
1954
+ );
1955
+ let compressedData = zlib.deflateSync(
1956
+ filteredData,
1957
+ packer.getDeflateOptions()
1958
+ );
1959
+ filteredData = null;
1960
+ if (!compressedData || !compressedData.length) {
1961
+ throw new Error("bad png - invalid compressed data response");
1962
+ }
1963
+ chunks.push(packer.packIDAT(compressedData));
1964
+ chunks.push(packer.packIEND());
1965
+ return Buffer.concat(chunks);
1966
+ };
1967
+ }
1968
+ });
1969
+
1970
+ // node_modules/pngjs/lib/png-sync.js
1971
+ var require_png_sync = __commonJS({
1972
+ "node_modules/pngjs/lib/png-sync.js"(exports) {
1973
+ "use strict";
1974
+ var parse = require_parser_sync();
1975
+ var pack = require_packer_sync();
1976
+ exports.read = function(buffer, options) {
1977
+ return parse(buffer, options || {});
1978
+ };
1979
+ exports.write = function(png, options) {
1980
+ return pack(png, options);
1981
+ };
1982
+ }
1983
+ });
1984
+
1985
+ // node_modules/pngjs/lib/png.js
1986
+ var require_png = __commonJS({
1987
+ "node_modules/pngjs/lib/png.js"(exports) {
1988
+ "use strict";
1989
+ var util = __require("util");
1990
+ var Stream = __require("stream");
1991
+ var Parser = require_parser_async();
1992
+ var Packer = require_packer_async();
1993
+ var PNGSync = require_png_sync();
1994
+ var PNG2 = exports.PNG = function(options) {
1995
+ Stream.call(this);
1996
+ options = options || {};
1997
+ this.width = options.width | 0;
1998
+ this.height = options.height | 0;
1999
+ this.data = this.width > 0 && this.height > 0 ? Buffer.alloc(4 * this.width * this.height) : null;
2000
+ if (options.fill && this.data) {
2001
+ this.data.fill(0);
2002
+ }
2003
+ this.gamma = 0;
2004
+ this.readable = this.writable = true;
2005
+ this._parser = new Parser(options);
2006
+ this._parser.on("error", this.emit.bind(this, "error"));
2007
+ this._parser.on("close", this._handleClose.bind(this));
2008
+ this._parser.on("metadata", this._metadata.bind(this));
2009
+ this._parser.on("gamma", this._gamma.bind(this));
2010
+ this._parser.on(
2011
+ "parsed",
2012
+ function(data) {
2013
+ this.data = data;
2014
+ this.emit("parsed", data);
2015
+ }.bind(this)
2016
+ );
2017
+ this._packer = new Packer(options);
2018
+ this._packer.on("data", this.emit.bind(this, "data"));
2019
+ this._packer.on("end", this.emit.bind(this, "end"));
2020
+ this._parser.on("close", this._handleClose.bind(this));
2021
+ this._packer.on("error", this.emit.bind(this, "error"));
2022
+ };
2023
+ util.inherits(PNG2, Stream);
2024
+ PNG2.sync = PNGSync;
2025
+ PNG2.prototype.pack = function() {
2026
+ if (!this.data || !this.data.length) {
2027
+ this.emit("error", "No data provided");
2028
+ return this;
2029
+ }
2030
+ process.nextTick(
2031
+ function() {
2032
+ this._packer.pack(this.data, this.width, this.height, this.gamma);
2033
+ }.bind(this)
2034
+ );
2035
+ return this;
2036
+ };
2037
+ PNG2.prototype.parse = function(data, callback) {
2038
+ if (callback) {
2039
+ let onParsed, onError;
2040
+ onParsed = function(parsedData) {
2041
+ this.removeListener("error", onError);
2042
+ this.data = parsedData;
2043
+ callback(null, this);
2044
+ }.bind(this);
2045
+ onError = function(err) {
2046
+ this.removeListener("parsed", onParsed);
2047
+ callback(err, null);
2048
+ }.bind(this);
2049
+ this.once("parsed", onParsed);
2050
+ this.once("error", onError);
2051
+ }
2052
+ this.end(data);
2053
+ return this;
2054
+ };
2055
+ PNG2.prototype.write = function(data) {
2056
+ this._parser.write(data);
2057
+ return true;
2058
+ };
2059
+ PNG2.prototype.end = function(data) {
2060
+ this._parser.end(data);
2061
+ };
2062
+ PNG2.prototype._metadata = function(metadata) {
2063
+ this.width = metadata.width;
2064
+ this.height = metadata.height;
2065
+ this.emit("metadata", metadata);
2066
+ };
2067
+ PNG2.prototype._gamma = function(gamma) {
2068
+ this.gamma = gamma;
2069
+ };
2070
+ PNG2.prototype._handleClose = function() {
2071
+ if (!this._parser.writable && !this._packer.readable) {
2072
+ this.emit("close");
2073
+ }
2074
+ };
2075
+ PNG2.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) {
2076
+ srcX |= 0;
2077
+ srcY |= 0;
2078
+ width |= 0;
2079
+ height |= 0;
2080
+ deltaX |= 0;
2081
+ deltaY |= 0;
2082
+ if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
2083
+ throw new Error("bitblt reading outside image");
2084
+ }
2085
+ if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
2086
+ throw new Error("bitblt writing outside image");
2087
+ }
2088
+ for (let y = 0; y < height; y++) {
2089
+ src.data.copy(
2090
+ dst.data,
2091
+ (deltaY + y) * dst.width + deltaX << 2,
2092
+ (srcY + y) * src.width + srcX << 2,
2093
+ (srcY + y) * src.width + srcX + width << 2
2094
+ );
2095
+ }
2096
+ };
2097
+ PNG2.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) {
2098
+ PNG2.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
2099
+ return this;
2100
+ };
2101
+ PNG2.adjustGamma = function(src) {
2102
+ if (src.gamma) {
2103
+ for (let y = 0; y < src.height; y++) {
2104
+ for (let x = 0; x < src.width; x++) {
2105
+ let idx = src.width * y + x << 2;
2106
+ for (let i = 0; i < 3; i++) {
2107
+ let sample = src.data[idx + i] / 255;
2108
+ sample = Math.pow(sample, 1 / 2.2 / src.gamma);
2109
+ src.data[idx + i] = Math.round(sample * 255);
2110
+ }
2111
+ }
2112
+ }
2113
+ src.gamma = 0;
2114
+ }
2115
+ };
2116
+ PNG2.prototype.adjustGamma = function() {
2117
+ PNG2.adjustGamma(this);
2118
+ };
2119
+ }
2120
+ });
2121
+
2122
+ // skills/maker-ui-workflow/scripts/assemble-ui.mjs
2123
+ var import_pngjs = __toESM(require_png(), 1);
2124
+ import assert from "node:assert/strict";
2125
+ import { createHash } from "node:crypto";
2126
+ import fs from "node:fs";
2127
+ import path from "node:path";
2128
+ import { fileURLToPath } from "node:url";
2129
+ var digest = (value) => createHash("sha256").update(value).digest("hex");
2130
+ var layoutDigest = (layout) => digest(JSON.stringify(layout));
2131
+ var geometryFields = [
2132
+ "id",
2133
+ "type",
2134
+ "children",
2135
+ "left",
2136
+ "top",
2137
+ "right",
2138
+ "bottom",
2139
+ "width",
2140
+ "height",
2141
+ "position",
2142
+ "backgroundImage",
2143
+ "pressedBackgroundImage"
2144
+ ];
2145
+ function rect(value, label) {
2146
+ assert(
2147
+ Array.isArray(value) && value.length === 4 && value.every(Number.isFinite),
2148
+ label + ": invalid rect"
2149
+ );
2150
+ assert(value[2] > 0 && value[3] > 0, label + ": non-positive size");
2151
+ }
2152
+ function unique(items, label) {
2153
+ assert(Array.isArray(items), label + ": expected array");
2154
+ const result = /* @__PURE__ */ new Map();
2155
+ for (const item of items) {
2156
+ assert(
2157
+ typeof item.id === "string" && /^[A-Za-z][A-Za-z0-9_-]*$/.test(item.id),
2158
+ label + ": invalid ID"
2159
+ );
2160
+ assert(!result.has(item.id), label + ": duplicate ID " + item.id);
2161
+ result.set(item.id, item);
2162
+ }
2163
+ return result;
2164
+ }
2165
+ function readAsset(project, relative) {
2166
+ assert(
2167
+ typeof relative === "string" && relative.startsWith("assets/") && !relative.includes(String.fromCharCode(92)),
2168
+ "Expected assets/ path"
2169
+ );
2170
+ assert(
2171
+ !relative.split("/").some((part) => part === ".." || part === "." || !part),
2172
+ "Unsafe asset path"
2173
+ );
2174
+ const root = fs.realpathSync(project), file = fs.realpathSync(path.join(root, relative));
2175
+ const rel = path.relative(root, file);
2176
+ assert(rel && !rel.startsWith("..") && !path.isAbsolute(rel), "Asset escapes project");
2177
+ return fs.readFileSync(file);
2178
+ }
2179
+ function verifyImage(project, item) {
2180
+ const bytes = readAsset(project, item.path);
2181
+ assert.equal(digest(bytes), item.sha256, "Image changed: " + item.path);
2182
+ const png = import_pngjs.PNG.sync.read(bytes);
2183
+ assert.equal(png.width, item.width, "Image width changed: " + item.path);
2184
+ assert.equal(png.height, item.height, "Image height changed: " + item.path);
2185
+ }
2186
+ function assemble(layout, correction = null) {
2187
+ assert.equal(layout.version, 1, "Unsupported layout version");
2188
+ assert.equal(layout.coordinateSpace, "design-pixels", "Expected design-pixels");
2189
+ assert.equal(layout.rectBasis, "asset-canvas", "Rects must describe the full placed PNG");
2190
+ assert(layout.design && /^[a-f0-9]{64}$/.test(layout.design.sha256), "Missing source image hash");
2191
+ assert(
2192
+ Number.isInteger(layout.design.width) && layout.design.width > 0 && Number.isInteger(layout.design.height) && layout.design.height > 0,
2193
+ "Invalid design size"
2194
+ );
2195
+ assert(
2196
+ ["recognition", "reconstruction-backfill"].includes(layout.provenance),
2197
+ "Missing coordinate provenance"
2198
+ );
2199
+ const elements = unique(layout.elements, "elements"), assets = unique(layout.assets, "assets");
2200
+ assert(elements.size > 0 && elements.size <= 5e3 && assets.size <= 5e3, "Invalid layout size");
2201
+ const roots = layout.elements.filter((item) => item.parentId === null);
2202
+ assert.equal(roots.length, 1, "Expected exactly one root");
2203
+ const root = roots[0];
2204
+ assert.deepEqual(
2205
+ root.rect,
2206
+ [0, 0, layout.design.width, layout.design.height],
2207
+ "Root must match design"
2208
+ );
2209
+ const used = /* @__PURE__ */ new Set(), counts = /* @__PURE__ */ new Map(), changes = /* @__PURE__ */ new Map(), byParent = /* @__PURE__ */ new Map();
2210
+ for (const item of layout.elements) {
2211
+ rect(item.rect, item.id);
2212
+ assert(
2213
+ ["Panel", "Button", "Label", "Image"].includes(item.type),
2214
+ "Unsupported element type: " + item.id
2215
+ );
2216
+ assert(["container", "image", "text"].includes(item.render), "Missing render role: " + item.id);
2217
+ if (item.render === "image") assert(item.assetId, "Unresolved image binding: " + item.id);
2218
+ else
2219
+ assert(
2220
+ item.assetId === void 0 && item.pressedAssetId === void 0,
2221
+ "Unexpected image binding: " + item.id
2222
+ );
2223
+ if (item.type === "Button" || item.type === "Image") assert.equal(item.render, "image");
2224
+ if (item.type === "Label") assert.equal(item.render, "text");
2225
+ if (item.render === "text") assert.equal(item.type, "Label");
2226
+ assert(
2227
+ item.props && typeof item.props === "object" && !Array.isArray(item.props),
2228
+ "Missing props: " + item.id
2229
+ );
2230
+ assert(
2231
+ !geometryFields.some((key) => Object.hasOwn(item.props, key)),
2232
+ "Geometry or image in props: " + item.id
2233
+ );
2234
+ assert(
2235
+ !["rotate", "scale", "translateX", "translateY", "transformOrigin"].some(
2236
+ (key) => Object.hasOwn(item.props, key)
2237
+ ),
2238
+ "Transformed coordinates require explicit conversion: " + item.id
2239
+ );
2240
+ if (item !== root) assert(elements.has(item.parentId), "Missing parent: " + item.id);
2241
+ const siblings = byParent.get(item.parentId) || [];
2242
+ siblings.push(item);
2243
+ byParent.set(item.parentId, siblings);
2244
+ const refs = [item.assetId, item.pressedAssetId].filter((id) => id !== void 0);
2245
+ if (item.pressedAssetId !== void 0)
2246
+ assert(item.type === "Button" && item.assetId, "State requires button base: " + item.id);
2247
+ for (const id of refs) {
2248
+ assert(assets.has(id), "Missing explicit asset binding: " + item.id + " -> " + id);
2249
+ assert(assets.get(id).role === "bound", "Reserve asset cannot be placed: " + id);
2250
+ used.add(id);
2251
+ if (!counts.has(id)) counts.set(id, /* @__PURE__ */ new Set());
2252
+ counts.get(id).add(item.id);
2253
+ }
2254
+ }
2255
+ for (const asset of assets.values()) {
2256
+ assert(["bound", "reserve"].includes(asset.role), "Invalid asset role: " + asset.id);
2257
+ assert(
2258
+ typeof asset.path === "string" && asset.path.startsWith("assets/") && !asset.path.includes(String.fromCharCode(92)) && !asset.path.split("/").some((part) => !part || part === "." || part === ".."),
2259
+ "Invalid asset path: " + asset.id
2260
+ );
2261
+ assert(/^[a-f0-9]{64}$/.test(asset.sha256), "Missing asset hash: " + asset.id);
2262
+ assert(
2263
+ Number.isInteger(asset.width) && asset.width > 0 && Number.isInteger(asset.height) && asset.height > 0,
2264
+ "Invalid asset size"
2265
+ );
2266
+ if (asset.role === "bound")
2267
+ assert(used.has(asset.id), "Unused asset must be reserve: " + asset.id);
2268
+ }
2269
+ if (correction) {
2270
+ assert.equal(correction.version, 1);
2271
+ assert.equal(
2272
+ correction.layoutSha256,
2273
+ layoutDigest(layout),
2274
+ "Correction belongs to another layout revision"
2275
+ );
2276
+ assert(
2277
+ correction.review && correction.review.designSha256 === layout.design.sha256 && typeof correction.review.evidence === "string" && correction.review.evidence.trim(),
2278
+ "Missing visual review evidence"
2279
+ );
2280
+ unique(correction.adjustments, "adjustments");
2281
+ for (const change of correction.adjustments) {
2282
+ assert(
2283
+ elements.has(change.id) && change.id !== root.id,
2284
+ "Unknown/root correction: " + change.id
2285
+ );
2286
+ assert.deepEqual(
2287
+ change.before,
2288
+ elements.get(change.id).rect,
2289
+ "Stale correction: " + change.id
2290
+ );
2291
+ rect(change.after, change.id);
2292
+ assert(
2293
+ typeof change.reason === "string" && change.reason.trim(),
2294
+ "Missing correction reason"
2295
+ );
2296
+ changes.set(change.id, change);
2297
+ }
2298
+ }
2299
+ const visited = /* @__PURE__ */ new Set(), placements = [];
2300
+ function build(item, parent, parentRect, depth) {
2301
+ assert(depth < 100 && !visited.has(item.id), "Cyclic or excessively deep layout");
2302
+ visited.add(item.id);
2303
+ const base = item.rect, shiftX = parent ? parentRect[0] - parent.rect[0] : 0;
2304
+ const shiftY = parent ? parentRect[1] - parent.rect[1] : 0;
2305
+ const target = changes.get(item.id)?.after || [
2306
+ base[0] + shiftX,
2307
+ base[1] + shiftY,
2308
+ base[2],
2309
+ base[3]
2310
+ ];
2311
+ const node = {
2312
+ ...item.props,
2313
+ type: item.type,
2314
+ id: item.id,
2315
+ width: target[2],
2316
+ height: target[3]
2317
+ };
2318
+ if (parent)
2319
+ Object.assign(node, {
2320
+ position: "absolute",
2321
+ left: target[0] - parentRect[0],
2322
+ top: target[1] - parentRect[1]
2323
+ });
2324
+ if (item.assetId) node.backgroundImage = assets.get(item.assetId).path.slice(7);
2325
+ if (item.pressedAssetId)
2326
+ node.pressedBackgroundImage = assets.get(item.pressedAssetId).path.slice(7);
2327
+ const children = byParent.get(item.id);
2328
+ if (children?.length)
2329
+ node.children = children.map((child) => build(child, item, target, depth + 1));
2330
+ placements.push({
2331
+ id: item.id,
2332
+ parentId: item.parentId,
2333
+ before: base,
2334
+ after: target,
2335
+ reason: changes.get(item.id)?.reason || (shiftX || shiftY ? "parent adjustment" : null)
2336
+ });
2337
+ return node;
2338
+ }
2339
+ const ui = build(root, null, null, 0);
2340
+ assert.equal(visited.size, elements.size, "Disconnected or cyclic elements");
2341
+ return {
2342
+ ui,
2343
+ report: {
2344
+ version: 1,
2345
+ layoutSha256: layoutDigest(layout),
2346
+ provenance: layout.provenance,
2347
+ visualReview: correction ? correction.review : null,
2348
+ reserveAssets: layout.assets.filter((asset) => asset.role === "reserve").map((asset) => asset.id),
2349
+ bindings: Array.from(counts, ([assetId, instances]) => ({
2350
+ assetId,
2351
+ instances: instances.size
2352
+ })),
2353
+ placements
2354
+ }
2355
+ };
2356
+ }
2357
+ function layoutFromBbox(input) {
2358
+ const bbox = input.bbox;
2359
+ if (input.ui) {
2360
+ assert(
2361
+ typeof input.ui.id === "string" && input.ui.id.length > 0,
2362
+ "Missing UI archive identity"
2363
+ );
2364
+ assert.equal(
2365
+ input.ui.bboxSha256,
2366
+ digest(JSON.stringify(bbox)),
2367
+ "Bbox does not match this UI resource bundle"
2368
+ );
2369
+ }
2370
+ assert(
2371
+ bbox && bbox.version === 1 && bbox.coordinateSpace === "design-pixels" && bbox.bboxFormat === "xywh",
2372
+ "Expected version=1 design-pixels xywh Bbox JSON"
2373
+ );
2374
+ assert(
2375
+ bbox.design && bbox.cutSource && Array.isArray(bbox.elements) && bbox.elements.length > 0 && bbox.elements.length <= 500 && Array.isArray(bbox.texts) && bbox.texts.length <= 1e3,
2376
+ "Missing Bbox sources or two-pass results"
2377
+ );
2378
+ for (const image of [bbox.design, bbox.cutSource]) {
2379
+ assert(
2380
+ typeof image.path === "string" && /^[a-f0-9]{64}$/.test(image.sha256) && Number.isInteger(image.width) && image.width > 0 && Number.isInteger(image.height) && image.height > 0,
2381
+ "Invalid Bbox source identity"
2382
+ );
2383
+ }
2384
+ const elements = unique(bbox.elements, "bbox.elements");
2385
+ const texts = unique(bbox.texts, "bbox.texts");
2386
+ const bindings = /* @__PURE__ */ new Map();
2387
+ assert(input.confirmed !== false, "UI asset bindings are not confirmed");
2388
+ assert(
2389
+ Array.isArray(input.bindings) && Array.isArray(input.assets),
2390
+ "Explicit assets and bindings are required"
2391
+ );
2392
+ for (const binding of input.bindings) {
2393
+ assert(binding.review !== "unreviewed", "Unreviewed UI binding: " + binding.elementId);
2394
+ assert(
2395
+ elements.has(binding.elementId) && !bindings.has(binding.elementId) && typeof binding.assetId === "string",
2396
+ "Unknown or duplicate Bbox binding"
2397
+ );
2398
+ bindings.set(binding.elementId, binding);
2399
+ }
2400
+ const checkRect = (value, id) => {
2401
+ rect(value, id);
2402
+ assert(
2403
+ value[0] >= 0 && value[1] >= 0 && value[0] + value[2] <= bbox.design.width && value[1] + value[3] <= bbox.design.height,
2404
+ "Bbox outside design: " + id
2405
+ );
2406
+ };
2407
+ const root = {
2408
+ id: "root",
2409
+ type: "Panel",
2410
+ parentId: null,
2411
+ render: "container",
2412
+ rect: [0, 0, bbox.design.width, bbox.design.height],
2413
+ props: {}
2414
+ };
2415
+ const images = bbox.elements.map((element) => {
2416
+ assert(
2417
+ /^E[0-9]{3,}$/.test(element.id) && ["icon", "frame", "panel", "button", "tab", "title"].includes(element.type) && (element.parent === null || elements.has(element.parent)),
2418
+ "Invalid Bbox element"
2419
+ );
2420
+ checkRect(element.bbox, element.id);
2421
+ const binding = bindings.get(element.id);
2422
+ assert(binding, "Missing explicit PNG binding: " + element.id);
2423
+ return {
2424
+ id: element.id,
2425
+ parentId: element.parent || "root",
2426
+ type: element.type === "button" || element.type === "tab" || binding.pressedAssetId ? "Button" : "Panel",
2427
+ render: "image",
2428
+ rect: [...element.bbox],
2429
+ props: { backgroundFit: element.type === "icon" ? "contain" : "fill" },
2430
+ assetId: binding.assetId,
2431
+ ...binding.pressedAssetId ? { pressedAssetId: binding.pressedAssetId } : {}
2432
+ };
2433
+ });
2434
+ const labels = bbox.texts.map((text) => {
2435
+ assert(
2436
+ /^T[0-9]{3,}$/.test(text.id) && !elements.has(text.id) && typeof text.text === "string" && text.text.trim() && text.cutout === false && (text.parentId === null || elements.has(text.parentId)) && ["left", "center", "right"].includes(text.align) && /^#[a-f0-9]{6}$/i.test(text.color) && typeof text.bold === "boolean",
2437
+ "Invalid Bbox text"
2438
+ );
2439
+ checkRect(text.bbox, text.id);
2440
+ const color = text.color.slice(1);
2441
+ const lines = text.text.split("\n");
2442
+ const widthUnits = Math.max(
2443
+ 1,
2444
+ ...lines.map(
2445
+ (line) => Array.from(line).reduce((sum, char) => sum + (char.codePointAt(0) < 128 ? 0.6 : 1), 0)
2446
+ )
2447
+ );
2448
+ return {
2449
+ id: text.id,
2450
+ parentId: text.parentId || "root",
2451
+ type: "Label",
2452
+ render: "text",
2453
+ rect: [...text.bbox],
2454
+ props: {
2455
+ text: text.text,
2456
+ textAlign: text.align,
2457
+ verticalAlign: "middle",
2458
+ fontSize: Math.max(
2459
+ 1,
2460
+ Math.floor(Math.min(text.bbox[3] / lines.length, text.bbox[2] / widthUnits))
2461
+ ),
2462
+ fontWeight: text.bold ? "bold" : "normal",
2463
+ fontColor: [
2464
+ parseInt(color.slice(0, 2), 16),
2465
+ parseInt(color.slice(2, 4), 16),
2466
+ parseInt(color.slice(4, 6), 16),
2467
+ 255
2468
+ ]
2469
+ }
2470
+ };
2471
+ });
2472
+ assert.equal(texts.size, labels.length);
2473
+ return {
2474
+ version: 1,
2475
+ coordinateSpace: "design-pixels",
2476
+ rectBasis: "asset-canvas",
2477
+ provenance: "recognition",
2478
+ design: { ...bbox.design },
2479
+ assets: input.assets,
2480
+ elements: [
2481
+ root,
2482
+ ...input.backgroundAssetId ? [
2483
+ {
2484
+ id: "background",
2485
+ parentId: "root",
2486
+ type: "Image",
2487
+ render: "image",
2488
+ rect: [...root.rect],
2489
+ props: {},
2490
+ assetId: input.backgroundAssetId
2491
+ }
2492
+ ] : [],
2493
+ ...images,
2494
+ ...labels
2495
+ ]
2496
+ };
2497
+ }
2498
+ function run(project, layoutFile, outputDirectory, correctionFile) {
2499
+ const input = JSON.parse(fs.readFileSync(layoutFile, "utf8"));
2500
+ const cropped = [];
2501
+ if (input.bbox) {
2502
+ for (const asset of input.assets || []) {
2503
+ verifyImage(project, asset);
2504
+ if (!asset.contentRect) continue;
2505
+ const box = asset.contentRect;
2506
+ assert(
2507
+ Array.isArray(box) && box.length === 4 && box.every(Number.isInteger) && box[0] >= 0 && box[1] >= 0 && box[2] > 0 && box[3] > 0 && box[0] + box[2] <= asset.width && box[1] + box[3] <= asset.height,
2508
+ "Invalid content rect: " + asset.id
2509
+ );
2510
+ if (box[0] === 0 && box[1] === 0 && box[2] === asset.width && box[3] === asset.height)
2511
+ continue;
2512
+ assert(/^[A-Za-z][A-Za-z0-9_-]*$/.test(asset.id), "Invalid crop asset ID");
2513
+ const relative = path.relative(
2514
+ fs.realpathSync(project),
2515
+ path.join(
2516
+ fs.realpathSync(path.dirname(path.resolve(outputDirectory))),
2517
+ path.basename(outputDirectory),
2518
+ "images",
2519
+ asset.id + ".png"
2520
+ )
2521
+ ).split(path.sep).join("/");
2522
+ assert(
2523
+ relative.startsWith("assets/") && !relative.split("/").includes(".."),
2524
+ "Cropped UI output must be inside project assets/"
2525
+ );
2526
+ const source = import_pngjs.PNG.sync.read(readAsset(project, asset.path));
2527
+ const target = new import_pngjs.PNG({ width: box[2], height: box[3] });
2528
+ import_pngjs.PNG.bitblt(source, target, ...box, 0, 0);
2529
+ const bytes = import_pngjs.PNG.sync.write(target);
2530
+ cropped.push({ relative, bytes });
2531
+ asset.sourceContentRect = [...box];
2532
+ asset.sourcePath = asset.path;
2533
+ Object.assign(asset, {
2534
+ path: relative,
2535
+ width: box[2],
2536
+ height: box[3],
2537
+ sha256: digest(bytes)
2538
+ });
2539
+ delete asset.contentRect;
2540
+ }
2541
+ }
2542
+ const layout = input.bbox ? layoutFromBbox(input) : input;
2543
+ if (input.bbox) verifyImage(project, input.bbox.cutSource);
2544
+ const correction = correctionFile ? JSON.parse(fs.readFileSync(correctionFile, "utf8")) : null;
2545
+ const result = assemble(layout, correction);
2546
+ for (const item of [layout.design, ...layout.assets])
2547
+ if (!cropped.some((crop) => crop.relative === item.path)) verifyImage(project, item);
2548
+ fs.mkdirSync(outputDirectory);
2549
+ if (cropped.length) fs.mkdirSync(path.join(outputDirectory, "images"));
2550
+ for (const crop of cropped)
2551
+ fs.writeFileSync(path.join(project, crop.relative), crop.bytes, { flag: "wx" });
2552
+ for (const [name, value] of [
2553
+ ["assembled.ui.json", result.ui],
2554
+ ["assembly-map.json", result.report],
2555
+ ...input.bbox ? [["layout.json", layout]] : []
2556
+ ]) {
2557
+ fs.writeFileSync(path.join(outputDirectory, name), JSON.stringify(value, null, 2), {
2558
+ flag: "wx"
2559
+ });
2560
+ }
2561
+ fs.copyFileSync(
2562
+ path.join(fs.realpathSync(project), layout.design.path),
2563
+ path.join(outputDirectory, "assembled.reference.png"),
2564
+ fs.constants.COPYFILE_EXCL
2565
+ );
2566
+ console.log(
2567
+ JSON.stringify({
2568
+ outputDirectory,
2569
+ elements: layout.elements.length,
2570
+ reserveAssets: result.report.reserveAssets.length,
2571
+ visualReview: correction ? "recorded-agent-review" : "pending"
2572
+ })
2573
+ );
2574
+ }
2575
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
2576
+ try {
2577
+ assert(
2578
+ process.argv.length === 5 || process.argv.length === 6,
2579
+ "Usage: node <skill>/scripts/assemble-ui.mjs <project> <layout.json> <new-output-dir> [corrections.json]"
2580
+ );
2581
+ run(...process.argv.slice(2));
2582
+ } catch (error) {
2583
+ console.error("UI \u7EC4\u88C5\u672A\u5B8C\u6210\uFF1A" + error.message);
2584
+ process.exitCode = 1;
2585
+ }
2586
+ }
2587
+ export {
2588
+ assemble,
2589
+ digest,
2590
+ layoutDigest,
2591
+ layoutFromBbox,
2592
+ readAsset,
2593
+ run
2594
+ };