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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/maker.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // TapTap Maker MCP - Standalone Bundle
3
- // TapTap Maker MCP version: 0.0.37-beta.1
3
+ // TapTap Maker MCP version: 0.0.37-beta.2
4
4
  import { createRequire } from 'node:module';
5
5
  const require = createRequire(import.meta.url);
6
6
  const __MAKER_BUNDLE_URL__ = import.meta.url;
@@ -29980,7 +29980,7 @@ function createMakerAgentsPolicyBody() {
29980
29980
  " `mcp report --ide <client> --target-dir <project> --context-stdin --consent --json`.",
29981
29981
  "- This preserves the configured package version and the absolute Windows node.exe/npm-cli.js.",
29982
29982
  "- Only with a known exact installed version, fallback to",
29983
- " `npx -y --package @taptap/maker@0.0.37-beta.1 taptap-maker mcp report ...`.",
29983
+ " `npx -y --package @taptap/maker@0.0.37-beta.2 taptap-maker mcp report ...`.",
29984
29984
  "- Never use an unversioned npm package, or assume `taptap-maker`/`npx` is globally available.",
29985
29985
  "- Never include the complete conversation, project source, other MCP server entries, PAT/token",
29986
29986
  " values, or full environment variables. Normalize the user home path to `~`.",
@@ -39289,7 +39289,7 @@ var init_tracking = __esm({
39289
39289
  MAKER_MCP_TRACKING_ACTION = "tapmaker_mcp_call";
39290
39290
  MAKER_MCP_TRACKING_SOURCE = "local_mcp";
39291
39291
  MAKER_MCP_TRACKING_TIMEOUT_MS = 1500;
39292
- MAKER_MCP_VERSION = "0.0.37-beta.1".trim() ? "0.0.37-beta.1".trim() : "dev";
39292
+ MAKER_MCP_VERSION = "0.0.37-beta.2".trim() ? "0.0.37-beta.2".trim() : "dev";
39293
39293
  TRACKING_ERROR_MAX_LENGTH = 500;
39294
39294
  }
39295
39295
  });
@@ -43298,7 +43298,7 @@ var init_mcp = __esm({
43298
43298
  init_remoteProxyManager();
43299
43299
  init_proxyAssets();
43300
43300
  init_diagnosticRedaction();
43301
- VERSION = true ? "0.0.37-beta.1" : "dev";
43301
+ VERSION = true ? "0.0.37-beta.2" : "dev";
43302
43302
  DEFAULT_BUILD_TIMEOUT_MS = 10 * 60 * 1e3;
43303
43303
  DEFAULT_PROXY_RETRY_ATTEMPTS = 5;
43304
43304
  DEFAULT_PROXY_RETRY_DELAY_MS = 30 * 1e3;
@@ -44507,8 +44507,12 @@ var init_luaLog = __esm({
44507
44507
  if (row.length > 65536) continue;
44508
44508
  try {
44509
44509
  const entry = JSON.parse(row);
44510
- if (typeof entry.m === "string")
44511
- this.append("[lua] " + (entry.l === "ERROR" ? "ERROR: " : "") + entry.m);
44510
+ if (typeof entry.m === "string") {
44511
+ const level = typeof entry.l === "string" && /^(?:INFO|DEBUG|TRACE|NOTICE|LOG|WARN|WARNING|ERROR|FATAL|CRITICAL|PANIC)$/i.test(
44512
+ entry.l
44513
+ ) ? entry.l.toUpperCase() + ": " : "";
44514
+ this.append("[lua] " + level + entry.m);
44515
+ }
44512
44516
  } catch {
44513
44517
  continue;
44514
44518
  }
@@ -57825,8 +57829,7 @@ async function runDirectory(project, id) {
57825
57829
  throw new Error("Invalid validation run directory.");
57826
57830
  return directory;
57827
57831
  }
57828
- async function artifact(directory, name) {
57829
- const max = LIMITS[name];
57832
+ async function artifact(directory, name, max = LIMITS[name]) {
57830
57833
  if (!max) throw new Error("Unknown validation artifact.");
57831
57834
  const filename2 = path38.join(directory, name);
57832
57835
  let file3;
@@ -58038,37 +58041,61 @@ async function readValidationPreparation(project, id) {
58038
58041
  };
58039
58042
  }
58040
58043
  async function cleanValidationHistory(project) {
58041
- const { runs, warnings } = await records(project, Infinity);
58042
- let bytes = 0;
58043
- let count = 0;
58044
- for (const run of runs) {
58045
- const directory = await runDirectory(project, run.run_id);
58046
- const expired = Date.now() - Date.parse(run.finished_at || run.started_at) > RETENTION_MS;
58047
- const inactive = run.finished_at || processPresence(run.owner_pid) === "missing" && !run.runtime_launch_pending && (!run.runtime_pid || processPresence(run.runtime_pid) === "missing");
58048
- if (expired && inactive) {
58049
- await fs37.promises.rm(directory, { recursive: true, force: true });
58050
- continue;
58044
+ let root2;
58045
+ try {
58046
+ root2 = await historyRoot(project);
58047
+ } catch (error2) {
58048
+ if (error2.code === "ENOENT") return [];
58049
+ throw error2;
58050
+ }
58051
+ return withPreviewLock(project, async () => {
58052
+ const previous = await artifact(root2, "cleanup.json", 1024);
58053
+ let completedAt = NaN;
58054
+ if (previous) {
58055
+ try {
58056
+ const state = JSON.parse(previous.toString("utf8"));
58057
+ if (typeof (state == null ? void 0 : state.completed_at) === "string") completedAt = Date.parse(state.completed_at);
58058
+ } catch (error2) {
58059
+ if (!(error2 instanceof SyntaxError)) throw error2;
58060
+ }
58051
58061
  }
58052
- const pending = [directory];
58053
- while (pending.length && count < 5e4) {
58054
- const current = pending.pop();
58055
- for (const entry of await fs37.promises.readdir(current, { withFileTypes: true })) {
58056
- if (count >= 5e4) break;
58057
- count++;
58058
- const filename2 = path38.join(current, entry.name);
58059
- const stat = await fs37.promises.lstat(filename2);
58060
- if (stat.isSymbolicLink()) continue;
58061
- if (stat.isDirectory()) pending.push(filename2);
58062
- else if (stat.isFile()) bytes += stat.size;
58062
+ const elapsed = Date.now() - completedAt;
58063
+ if (elapsed >= 0 && elapsed < CLEANUP_INTERVAL_MS) return [];
58064
+ const { runs, warnings } = await records(project, Infinity);
58065
+ let bytes = 0;
58066
+ let count = 0;
58067
+ for (const run of runs) {
58068
+ const directory = await runDirectory(project, run.run_id);
58069
+ const expired = Date.now() - Date.parse(run.finished_at || run.started_at) > RETENTION_MS;
58070
+ const inactive = run.finished_at || processPresence(run.owner_pid) === "missing" && !run.runtime_launch_pending && (!run.runtime_pid || processPresence(run.runtime_pid) === "missing");
58071
+ if (expired && inactive) {
58072
+ await fs37.promises.rm(directory, { recursive: true, force: true });
58073
+ continue;
58074
+ }
58075
+ const pending = [directory];
58076
+ while (pending.length && count < 5e4) {
58077
+ const current = pending.pop();
58078
+ for (const entry of await fs37.promises.readdir(current, { withFileTypes: true })) {
58079
+ if (count >= 5e4) break;
58080
+ count++;
58081
+ const filename2 = path38.join(current, entry.name);
58082
+ const stat = await fs37.promises.lstat(filename2);
58083
+ if (stat.isSymbolicLink()) continue;
58084
+ if (stat.isDirectory()) pending.push(filename2);
58085
+ else if (stat.isFile()) bytes += stat.size;
58086
+ }
58063
58087
  }
58064
58088
  }
58065
- }
58066
- if (count >= 5e4) warnings.push("Validation disk usage scan truncated at 50000 entries.");
58067
- if (bytes > BUDGET_BYTES)
58068
- warnings.push(
58069
- "Validation cache exceeds 5 GiB. Archive needed evidence before manually removing completed runs; recent runs were not deleted."
58070
- );
58071
- return warnings;
58089
+ if (count >= 5e4) warnings.push("Validation disk usage scan truncated at 50000 entries.");
58090
+ if (bytes > BUDGET_BYTES)
58091
+ warnings.push(
58092
+ "Validation cache exceeds 5 GiB. Archive needed evidence before manually removing completed runs; recent runs were not deleted."
58093
+ );
58094
+ writePrivateJson(path38.join(root2, "cleanup.json"), {
58095
+ completed_at: new Date(Date.now()).toISOString()
58096
+ });
58097
+ return warnings;
58098
+ });
58072
58099
  }
58073
58100
  async function archiveValidationRun(run, outputDir) {
58074
58101
  if (!path38.isAbsolute(outputDir)) throw new Error("--output-dir must be an absolute directory.");
@@ -58108,7 +58135,7 @@ async function archiveValidationRun(run, outputDir) {
58108
58135
  }
58109
58136
  return destination;
58110
58137
  }
58111
- var UUID2, RETENTION_MS, BUDGET_BYTES, LIMITS;
58138
+ var UUID2, RETENTION_MS, CLEANUP_INTERVAL_MS, BUDGET_BYTES, LIMITS;
58112
58139
  var init_validationHistory = __esm({
58113
58140
  "src/maker/preview/validationHistory.ts"() {
58114
58141
  "use strict";
@@ -58116,8 +58143,10 @@ var init_validationHistory = __esm({
58116
58143
  init_storage();
58117
58144
  init_processPresence();
58118
58145
  init_diagnosticRedaction();
58146
+ init_installation();
58119
58147
  UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
58120
58148
  RETENTION_MS = 7 * 864e5;
58149
+ CLEANUP_INTERVAL_MS = 864e5;
58121
58150
  BUDGET_BYTES = 5 * 1024 ** 3;
58122
58151
  LIMITS = {
58123
58152
  "run.json": 16384,
@@ -58185,6 +58214,2167 @@ var init_processLauncher = __esm({
58185
58214
  }
58186
58215
  });
58187
58216
 
58217
+ // node_modules/pngjs/lib/chunkstream.js
58218
+ var require_chunkstream = __commonJS({
58219
+ "node_modules/pngjs/lib/chunkstream.js"(exports, module) {
58220
+ "use strict";
58221
+ var util2 = __require("util");
58222
+ var Stream = __require("stream");
58223
+ var ChunkStream = module.exports = function() {
58224
+ Stream.call(this);
58225
+ this._buffers = [];
58226
+ this._buffered = 0;
58227
+ this._reads = [];
58228
+ this._paused = false;
58229
+ this._encoding = "utf8";
58230
+ this.writable = true;
58231
+ };
58232
+ util2.inherits(ChunkStream, Stream);
58233
+ ChunkStream.prototype.read = function(length, callback) {
58234
+ this._reads.push({
58235
+ length: Math.abs(length),
58236
+ // if length < 0 then at most this length
58237
+ allowLess: length < 0,
58238
+ func: callback
58239
+ });
58240
+ process.nextTick(
58241
+ function() {
58242
+ this._process();
58243
+ if (this._paused && this._reads && this._reads.length > 0) {
58244
+ this._paused = false;
58245
+ this.emit("drain");
58246
+ }
58247
+ }.bind(this)
58248
+ );
58249
+ };
58250
+ ChunkStream.prototype.write = function(data, encoding) {
58251
+ if (!this.writable) {
58252
+ this.emit("error", new Error("Stream not writable"));
58253
+ return false;
58254
+ }
58255
+ let dataBuffer;
58256
+ if (Buffer.isBuffer(data)) {
58257
+ dataBuffer = data;
58258
+ } else {
58259
+ dataBuffer = Buffer.from(data, encoding || this._encoding);
58260
+ }
58261
+ this._buffers.push(dataBuffer);
58262
+ this._buffered += dataBuffer.length;
58263
+ this._process();
58264
+ if (this._reads && this._reads.length === 0) {
58265
+ this._paused = true;
58266
+ }
58267
+ return this.writable && !this._paused;
58268
+ };
58269
+ ChunkStream.prototype.end = function(data, encoding) {
58270
+ if (data) {
58271
+ this.write(data, encoding);
58272
+ }
58273
+ this.writable = false;
58274
+ if (!this._buffers) {
58275
+ return;
58276
+ }
58277
+ if (this._buffers.length === 0) {
58278
+ this._end();
58279
+ } else {
58280
+ this._buffers.push(null);
58281
+ this._process();
58282
+ }
58283
+ };
58284
+ ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
58285
+ ChunkStream.prototype._end = function() {
58286
+ if (this._reads.length > 0) {
58287
+ this.emit("error", new Error("Unexpected end of input"));
58288
+ }
58289
+ this.destroy();
58290
+ };
58291
+ ChunkStream.prototype.destroy = function() {
58292
+ if (!this._buffers) {
58293
+ return;
58294
+ }
58295
+ this.writable = false;
58296
+ this._reads = null;
58297
+ this._buffers = null;
58298
+ this.emit("close");
58299
+ };
58300
+ ChunkStream.prototype._processReadAllowingLess = function(read) {
58301
+ this._reads.shift();
58302
+ let smallerBuf = this._buffers[0];
58303
+ if (smallerBuf.length > read.length) {
58304
+ this._buffered -= read.length;
58305
+ this._buffers[0] = smallerBuf.slice(read.length);
58306
+ read.func.call(this, smallerBuf.slice(0, read.length));
58307
+ } else {
58308
+ this._buffered -= smallerBuf.length;
58309
+ this._buffers.shift();
58310
+ read.func.call(this, smallerBuf);
58311
+ }
58312
+ };
58313
+ ChunkStream.prototype._processRead = function(read) {
58314
+ this._reads.shift();
58315
+ let pos = 0;
58316
+ let count = 0;
58317
+ let data = Buffer.alloc(read.length);
58318
+ while (pos < read.length) {
58319
+ let buf = this._buffers[count++];
58320
+ let len = Math.min(buf.length, read.length - pos);
58321
+ buf.copy(data, pos, 0, len);
58322
+ pos += len;
58323
+ if (len !== buf.length) {
58324
+ this._buffers[--count] = buf.slice(len);
58325
+ }
58326
+ }
58327
+ if (count > 0) {
58328
+ this._buffers.splice(0, count);
58329
+ }
58330
+ this._buffered -= read.length;
58331
+ read.func.call(this, data);
58332
+ };
58333
+ ChunkStream.prototype._process = function() {
58334
+ try {
58335
+ while (this._buffered > 0 && this._reads && this._reads.length > 0) {
58336
+ let read = this._reads[0];
58337
+ if (read.allowLess) {
58338
+ this._processReadAllowingLess(read);
58339
+ } else if (this._buffered >= read.length) {
58340
+ this._processRead(read);
58341
+ } else {
58342
+ break;
58343
+ }
58344
+ }
58345
+ if (this._buffers && !this.writable) {
58346
+ this._end();
58347
+ }
58348
+ } catch (ex) {
58349
+ this.emit("error", ex);
58350
+ }
58351
+ };
58352
+ }
58353
+ });
58354
+
58355
+ // node_modules/pngjs/lib/interlace.js
58356
+ var require_interlace = __commonJS({
58357
+ "node_modules/pngjs/lib/interlace.js"(exports) {
58358
+ "use strict";
58359
+ var imagePasses = [
58360
+ {
58361
+ // pass 1 - 1px
58362
+ x: [0],
58363
+ y: [0]
58364
+ },
58365
+ {
58366
+ // pass 2 - 1px
58367
+ x: [4],
58368
+ y: [0]
58369
+ },
58370
+ {
58371
+ // pass 3 - 2px
58372
+ x: [0, 4],
58373
+ y: [4]
58374
+ },
58375
+ {
58376
+ // pass 4 - 4px
58377
+ x: [2, 6],
58378
+ y: [0, 4]
58379
+ },
58380
+ {
58381
+ // pass 5 - 8px
58382
+ x: [0, 2, 4, 6],
58383
+ y: [2, 6]
58384
+ },
58385
+ {
58386
+ // pass 6 - 16px
58387
+ x: [1, 3, 5, 7],
58388
+ y: [0, 2, 4, 6]
58389
+ },
58390
+ {
58391
+ // pass 7 - 32px
58392
+ x: [0, 1, 2, 3, 4, 5, 6, 7],
58393
+ y: [1, 3, 5, 7]
58394
+ }
58395
+ ];
58396
+ exports.getImagePasses = function(width, height) {
58397
+ let images = [];
58398
+ let xLeftOver = width % 8;
58399
+ let yLeftOver = height % 8;
58400
+ let xRepeats = (width - xLeftOver) / 8;
58401
+ let yRepeats = (height - yLeftOver) / 8;
58402
+ for (let i = 0; i < imagePasses.length; i++) {
58403
+ let pass = imagePasses[i];
58404
+ let passWidth = xRepeats * pass.x.length;
58405
+ let passHeight = yRepeats * pass.y.length;
58406
+ for (let j = 0; j < pass.x.length; j++) {
58407
+ if (pass.x[j] < xLeftOver) {
58408
+ passWidth++;
58409
+ } else {
58410
+ break;
58411
+ }
58412
+ }
58413
+ for (let j = 0; j < pass.y.length; j++) {
58414
+ if (pass.y[j] < yLeftOver) {
58415
+ passHeight++;
58416
+ } else {
58417
+ break;
58418
+ }
58419
+ }
58420
+ if (passWidth > 0 && passHeight > 0) {
58421
+ images.push({ width: passWidth, height: passHeight, index: i });
58422
+ }
58423
+ }
58424
+ return images;
58425
+ };
58426
+ exports.getInterlaceIterator = function(width) {
58427
+ return function(x, y, pass) {
58428
+ let outerXLeftOver = x % imagePasses[pass].x.length;
58429
+ let outerX = (x - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver];
58430
+ let outerYLeftOver = y % imagePasses[pass].y.length;
58431
+ let outerY = (y - outerYLeftOver) / imagePasses[pass].y.length * 8 + imagePasses[pass].y[outerYLeftOver];
58432
+ return outerX * 4 + outerY * width * 4;
58433
+ };
58434
+ };
58435
+ }
58436
+ });
58437
+
58438
+ // node_modules/pngjs/lib/paeth-predictor.js
58439
+ var require_paeth_predictor = __commonJS({
58440
+ "node_modules/pngjs/lib/paeth-predictor.js"(exports, module) {
58441
+ "use strict";
58442
+ module.exports = function paethPredictor(left, above, upLeft) {
58443
+ let paeth = left + above - upLeft;
58444
+ let pLeft = Math.abs(paeth - left);
58445
+ let pAbove = Math.abs(paeth - above);
58446
+ let pUpLeft = Math.abs(paeth - upLeft);
58447
+ if (pLeft <= pAbove && pLeft <= pUpLeft) {
58448
+ return left;
58449
+ }
58450
+ if (pAbove <= pUpLeft) {
58451
+ return above;
58452
+ }
58453
+ return upLeft;
58454
+ };
58455
+ }
58456
+ });
58457
+
58458
+ // node_modules/pngjs/lib/filter-parse.js
58459
+ var require_filter_parse = __commonJS({
58460
+ "node_modules/pngjs/lib/filter-parse.js"(exports, module) {
58461
+ "use strict";
58462
+ var interlaceUtils = require_interlace();
58463
+ var paethPredictor = require_paeth_predictor();
58464
+ function getByteWidth(width, bpp, depth) {
58465
+ let byteWidth = width * bpp;
58466
+ if (depth !== 8) {
58467
+ byteWidth = Math.ceil(byteWidth / (8 / depth));
58468
+ }
58469
+ return byteWidth;
58470
+ }
58471
+ var Filter = module.exports = function(bitmapInfo, dependencies) {
58472
+ let width = bitmapInfo.width;
58473
+ let height = bitmapInfo.height;
58474
+ let interlace = bitmapInfo.interlace;
58475
+ let bpp = bitmapInfo.bpp;
58476
+ let depth = bitmapInfo.depth;
58477
+ this.read = dependencies.read;
58478
+ this.write = dependencies.write;
58479
+ this.complete = dependencies.complete;
58480
+ this._imageIndex = 0;
58481
+ this._images = [];
58482
+ if (interlace) {
58483
+ let passes = interlaceUtils.getImagePasses(width, height);
58484
+ for (let i = 0; i < passes.length; i++) {
58485
+ this._images.push({
58486
+ byteWidth: getByteWidth(passes[i].width, bpp, depth),
58487
+ height: passes[i].height,
58488
+ lineIndex: 0
58489
+ });
58490
+ }
58491
+ } else {
58492
+ this._images.push({
58493
+ byteWidth: getByteWidth(width, bpp, depth),
58494
+ height,
58495
+ lineIndex: 0
58496
+ });
58497
+ }
58498
+ if (depth === 8) {
58499
+ this._xComparison = bpp;
58500
+ } else if (depth === 16) {
58501
+ this._xComparison = bpp * 2;
58502
+ } else {
58503
+ this._xComparison = 1;
58504
+ }
58505
+ };
58506
+ Filter.prototype.start = function() {
58507
+ this.read(
58508
+ this._images[this._imageIndex].byteWidth + 1,
58509
+ this._reverseFilterLine.bind(this)
58510
+ );
58511
+ };
58512
+ Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
58513
+ let xComparison = this._xComparison;
58514
+ let xBiggerThan = xComparison - 1;
58515
+ for (let x = 0; x < byteWidth; x++) {
58516
+ let rawByte = rawData[1 + x];
58517
+ let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
58518
+ unfilteredLine[x] = rawByte + f1Left;
58519
+ }
58520
+ };
58521
+ Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
58522
+ let lastLine = this._lastLine;
58523
+ for (let x = 0; x < byteWidth; x++) {
58524
+ let rawByte = rawData[1 + x];
58525
+ let f2Up = lastLine ? lastLine[x] : 0;
58526
+ unfilteredLine[x] = rawByte + f2Up;
58527
+ }
58528
+ };
58529
+ Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
58530
+ let xComparison = this._xComparison;
58531
+ let xBiggerThan = xComparison - 1;
58532
+ let lastLine = this._lastLine;
58533
+ for (let x = 0; x < byteWidth; x++) {
58534
+ let rawByte = rawData[1 + x];
58535
+ let f3Up = lastLine ? lastLine[x] : 0;
58536
+ let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
58537
+ let f3Add = Math.floor((f3Left + f3Up) / 2);
58538
+ unfilteredLine[x] = rawByte + f3Add;
58539
+ }
58540
+ };
58541
+ Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
58542
+ let xComparison = this._xComparison;
58543
+ let xBiggerThan = xComparison - 1;
58544
+ let lastLine = this._lastLine;
58545
+ for (let x = 0; x < byteWidth; x++) {
58546
+ let rawByte = rawData[1 + x];
58547
+ let f4Up = lastLine ? lastLine[x] : 0;
58548
+ let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
58549
+ let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
58550
+ let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
58551
+ unfilteredLine[x] = rawByte + f4Add;
58552
+ }
58553
+ };
58554
+ Filter.prototype._reverseFilterLine = function(rawData) {
58555
+ let filter = rawData[0];
58556
+ let unfilteredLine;
58557
+ let currentImage = this._images[this._imageIndex];
58558
+ let byteWidth = currentImage.byteWidth;
58559
+ if (filter === 0) {
58560
+ unfilteredLine = rawData.slice(1, byteWidth + 1);
58561
+ } else {
58562
+ unfilteredLine = Buffer.alloc(byteWidth);
58563
+ switch (filter) {
58564
+ case 1:
58565
+ this._unFilterType1(rawData, unfilteredLine, byteWidth);
58566
+ break;
58567
+ case 2:
58568
+ this._unFilterType2(rawData, unfilteredLine, byteWidth);
58569
+ break;
58570
+ case 3:
58571
+ this._unFilterType3(rawData, unfilteredLine, byteWidth);
58572
+ break;
58573
+ case 4:
58574
+ this._unFilterType4(rawData, unfilteredLine, byteWidth);
58575
+ break;
58576
+ default:
58577
+ throw new Error("Unrecognised filter type - " + filter);
58578
+ }
58579
+ }
58580
+ this.write(unfilteredLine);
58581
+ currentImage.lineIndex++;
58582
+ if (currentImage.lineIndex >= currentImage.height) {
58583
+ this._lastLine = null;
58584
+ this._imageIndex++;
58585
+ currentImage = this._images[this._imageIndex];
58586
+ } else {
58587
+ this._lastLine = unfilteredLine;
58588
+ }
58589
+ if (currentImage) {
58590
+ this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
58591
+ } else {
58592
+ this._lastLine = null;
58593
+ this.complete();
58594
+ }
58595
+ };
58596
+ }
58597
+ });
58598
+
58599
+ // node_modules/pngjs/lib/filter-parse-async.js
58600
+ var require_filter_parse_async = __commonJS({
58601
+ "node_modules/pngjs/lib/filter-parse-async.js"(exports, module) {
58602
+ "use strict";
58603
+ var util2 = __require("util");
58604
+ var ChunkStream = require_chunkstream();
58605
+ var Filter = require_filter_parse();
58606
+ var FilterAsync = module.exports = function(bitmapInfo) {
58607
+ ChunkStream.call(this);
58608
+ let buffers = [];
58609
+ let that = this;
58610
+ this._filter = new Filter(bitmapInfo, {
58611
+ read: this.read.bind(this),
58612
+ write: function(buffer) {
58613
+ buffers.push(buffer);
58614
+ },
58615
+ complete: function() {
58616
+ that.emit("complete", Buffer.concat(buffers));
58617
+ }
58618
+ });
58619
+ this._filter.start();
58620
+ };
58621
+ util2.inherits(FilterAsync, ChunkStream);
58622
+ }
58623
+ });
58624
+
58625
+ // node_modules/pngjs/lib/constants.js
58626
+ var require_constants2 = __commonJS({
58627
+ "node_modules/pngjs/lib/constants.js"(exports, module) {
58628
+ "use strict";
58629
+ module.exports = {
58630
+ PNG_SIGNATURE: [137, 80, 78, 71, 13, 10, 26, 10],
58631
+ TYPE_IHDR: 1229472850,
58632
+ TYPE_IEND: 1229278788,
58633
+ TYPE_IDAT: 1229209940,
58634
+ TYPE_PLTE: 1347179589,
58635
+ TYPE_tRNS: 1951551059,
58636
+ // eslint-disable-line camelcase
58637
+ TYPE_gAMA: 1732332865,
58638
+ // eslint-disable-line camelcase
58639
+ // color-type bits
58640
+ COLORTYPE_GRAYSCALE: 0,
58641
+ COLORTYPE_PALETTE: 1,
58642
+ COLORTYPE_COLOR: 2,
58643
+ COLORTYPE_ALPHA: 4,
58644
+ // e.g. grayscale and alpha
58645
+ // color-type combinations
58646
+ COLORTYPE_PALETTE_COLOR: 3,
58647
+ COLORTYPE_COLOR_ALPHA: 6,
58648
+ COLORTYPE_TO_BPP_MAP: {
58649
+ 0: 1,
58650
+ 2: 3,
58651
+ 3: 1,
58652
+ 4: 2,
58653
+ 6: 4
58654
+ },
58655
+ GAMMA_DIVISION: 1e5
58656
+ };
58657
+ }
58658
+ });
58659
+
58660
+ // node_modules/pngjs/lib/crc.js
58661
+ var require_crc = __commonJS({
58662
+ "node_modules/pngjs/lib/crc.js"(exports, module) {
58663
+ "use strict";
58664
+ var crcTable = [];
58665
+ (function() {
58666
+ for (let i = 0; i < 256; i++) {
58667
+ let currentCrc = i;
58668
+ for (let j = 0; j < 8; j++) {
58669
+ if (currentCrc & 1) {
58670
+ currentCrc = 3988292384 ^ currentCrc >>> 1;
58671
+ } else {
58672
+ currentCrc = currentCrc >>> 1;
58673
+ }
58674
+ }
58675
+ crcTable[i] = currentCrc;
58676
+ }
58677
+ })();
58678
+ var CrcCalculator = module.exports = function() {
58679
+ this._crc = -1;
58680
+ };
58681
+ CrcCalculator.prototype.write = function(data) {
58682
+ for (let i = 0; i < data.length; i++) {
58683
+ this._crc = crcTable[(this._crc ^ data[i]) & 255] ^ this._crc >>> 8;
58684
+ }
58685
+ return true;
58686
+ };
58687
+ CrcCalculator.prototype.crc32 = function() {
58688
+ return this._crc ^ -1;
58689
+ };
58690
+ CrcCalculator.crc32 = function(buf) {
58691
+ let crc = -1;
58692
+ for (let i = 0; i < buf.length; i++) {
58693
+ crc = crcTable[(crc ^ buf[i]) & 255] ^ crc >>> 8;
58694
+ }
58695
+ return crc ^ -1;
58696
+ };
58697
+ }
58698
+ });
58699
+
58700
+ // node_modules/pngjs/lib/parser.js
58701
+ var require_parser = __commonJS({
58702
+ "node_modules/pngjs/lib/parser.js"(exports, module) {
58703
+ "use strict";
58704
+ var constants = require_constants2();
58705
+ var CrcCalculator = require_crc();
58706
+ var Parser = module.exports = function(options3, dependencies) {
58707
+ this._options = options3;
58708
+ options3.checkCRC = options3.checkCRC !== false;
58709
+ this._hasIHDR = false;
58710
+ this._hasIEND = false;
58711
+ this._emittedHeadersFinished = false;
58712
+ this._palette = [];
58713
+ this._colorType = 0;
58714
+ this._chunks = {};
58715
+ this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
58716
+ this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
58717
+ this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
58718
+ this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
58719
+ this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
58720
+ this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
58721
+ this.read = dependencies.read;
58722
+ this.error = dependencies.error;
58723
+ this.metadata = dependencies.metadata;
58724
+ this.gamma = dependencies.gamma;
58725
+ this.transColor = dependencies.transColor;
58726
+ this.palette = dependencies.palette;
58727
+ this.parsed = dependencies.parsed;
58728
+ this.inflateData = dependencies.inflateData;
58729
+ this.finished = dependencies.finished;
58730
+ this.simpleTransparency = dependencies.simpleTransparency;
58731
+ this.headersFinished = dependencies.headersFinished || function() {
58732
+ };
58733
+ };
58734
+ Parser.prototype.start = function() {
58735
+ this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));
58736
+ };
58737
+ Parser.prototype._parseSignature = function(data) {
58738
+ let signature = constants.PNG_SIGNATURE;
58739
+ for (let i = 0; i < signature.length; i++) {
58740
+ if (data[i] !== signature[i]) {
58741
+ this.error(new Error("Invalid file signature"));
58742
+ return;
58743
+ }
58744
+ }
58745
+ this.read(8, this._parseChunkBegin.bind(this));
58746
+ };
58747
+ Parser.prototype._parseChunkBegin = function(data) {
58748
+ let length = data.readUInt32BE(0);
58749
+ let type = data.readUInt32BE(4);
58750
+ let name = "";
58751
+ for (let i = 4; i < 8; i++) {
58752
+ name += String.fromCharCode(data[i]);
58753
+ }
58754
+ let ancillary = Boolean(data[4] & 32);
58755
+ if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
58756
+ this.error(new Error("Expected IHDR on beggining"));
58757
+ return;
58758
+ }
58759
+ this._crc = new CrcCalculator();
58760
+ this._crc.write(Buffer.from(name));
58761
+ if (this._chunks[type]) {
58762
+ return this._chunks[type](length);
58763
+ }
58764
+ if (!ancillary) {
58765
+ this.error(new Error("Unsupported critical chunk type " + name));
58766
+ return;
58767
+ }
58768
+ this.read(length + 4, this._skipChunk.bind(this));
58769
+ };
58770
+ Parser.prototype._skipChunk = function() {
58771
+ this.read(8, this._parseChunkBegin.bind(this));
58772
+ };
58773
+ Parser.prototype._handleChunkEnd = function() {
58774
+ this.read(4, this._parseChunkEnd.bind(this));
58775
+ };
58776
+ Parser.prototype._parseChunkEnd = function(data) {
58777
+ let fileCrc = data.readInt32BE(0);
58778
+ let calcCrc = this._crc.crc32();
58779
+ if (this._options.checkCRC && calcCrc !== fileCrc) {
58780
+ this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc));
58781
+ return;
58782
+ }
58783
+ if (!this._hasIEND) {
58784
+ this.read(8, this._parseChunkBegin.bind(this));
58785
+ }
58786
+ };
58787
+ Parser.prototype._handleIHDR = function(length) {
58788
+ this.read(length, this._parseIHDR.bind(this));
58789
+ };
58790
+ Parser.prototype._parseIHDR = function(data) {
58791
+ this._crc.write(data);
58792
+ let width = data.readUInt32BE(0);
58793
+ let height = data.readUInt32BE(4);
58794
+ let depth = data[8];
58795
+ let colorType = data[9];
58796
+ let compr = data[10];
58797
+ let filter = data[11];
58798
+ let interlace = data[12];
58799
+ if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
58800
+ this.error(new Error("Unsupported bit depth " + depth));
58801
+ return;
58802
+ }
58803
+ if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
58804
+ this.error(new Error("Unsupported color type"));
58805
+ return;
58806
+ }
58807
+ if (compr !== 0) {
58808
+ this.error(new Error("Unsupported compression method"));
58809
+ return;
58810
+ }
58811
+ if (filter !== 0) {
58812
+ this.error(new Error("Unsupported filter method"));
58813
+ return;
58814
+ }
58815
+ if (interlace !== 0 && interlace !== 1) {
58816
+ this.error(new Error("Unsupported interlace method"));
58817
+ return;
58818
+ }
58819
+ this._colorType = colorType;
58820
+ let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
58821
+ this._hasIHDR = true;
58822
+ this.metadata({
58823
+ width,
58824
+ height,
58825
+ depth,
58826
+ interlace: Boolean(interlace),
58827
+ palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
58828
+ color: Boolean(colorType & constants.COLORTYPE_COLOR),
58829
+ alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
58830
+ bpp,
58831
+ colorType
58832
+ });
58833
+ this._handleChunkEnd();
58834
+ };
58835
+ Parser.prototype._handlePLTE = function(length) {
58836
+ this.read(length, this._parsePLTE.bind(this));
58837
+ };
58838
+ Parser.prototype._parsePLTE = function(data) {
58839
+ this._crc.write(data);
58840
+ let entries = Math.floor(data.length / 3);
58841
+ for (let i = 0; i < entries; i++) {
58842
+ this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 255]);
58843
+ }
58844
+ this.palette(this._palette);
58845
+ this._handleChunkEnd();
58846
+ };
58847
+ Parser.prototype._handleTRNS = function(length) {
58848
+ this.simpleTransparency();
58849
+ this.read(length, this._parseTRNS.bind(this));
58850
+ };
58851
+ Parser.prototype._parseTRNS = function(data) {
58852
+ this._crc.write(data);
58853
+ if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
58854
+ if (this._palette.length === 0) {
58855
+ this.error(new Error("Transparency chunk must be after palette"));
58856
+ return;
58857
+ }
58858
+ if (data.length > this._palette.length) {
58859
+ this.error(new Error("More transparent colors than palette size"));
58860
+ return;
58861
+ }
58862
+ for (let i = 0; i < data.length; i++) {
58863
+ this._palette[i][3] = data[i];
58864
+ }
58865
+ this.palette(this._palette);
58866
+ }
58867
+ if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
58868
+ this.transColor([data.readUInt16BE(0)]);
58869
+ }
58870
+ if (this._colorType === constants.COLORTYPE_COLOR) {
58871
+ this.transColor([
58872
+ data.readUInt16BE(0),
58873
+ data.readUInt16BE(2),
58874
+ data.readUInt16BE(4)
58875
+ ]);
58876
+ }
58877
+ this._handleChunkEnd();
58878
+ };
58879
+ Parser.prototype._handleGAMA = function(length) {
58880
+ this.read(length, this._parseGAMA.bind(this));
58881
+ };
58882
+ Parser.prototype._parseGAMA = function(data) {
58883
+ this._crc.write(data);
58884
+ this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
58885
+ this._handleChunkEnd();
58886
+ };
58887
+ Parser.prototype._handleIDAT = function(length) {
58888
+ if (!this._emittedHeadersFinished) {
58889
+ this._emittedHeadersFinished = true;
58890
+ this.headersFinished();
58891
+ }
58892
+ this.read(-length, this._parseIDAT.bind(this, length));
58893
+ };
58894
+ Parser.prototype._parseIDAT = function(length, data) {
58895
+ this._crc.write(data);
58896
+ if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
58897
+ throw new Error("Expected palette not found");
58898
+ }
58899
+ this.inflateData(data);
58900
+ let leftOverLength = length - data.length;
58901
+ if (leftOverLength > 0) {
58902
+ this._handleIDAT(leftOverLength);
58903
+ } else {
58904
+ this._handleChunkEnd();
58905
+ }
58906
+ };
58907
+ Parser.prototype._handleIEND = function(length) {
58908
+ this.read(length, this._parseIEND.bind(this));
58909
+ };
58910
+ Parser.prototype._parseIEND = function(data) {
58911
+ this._crc.write(data);
58912
+ this._hasIEND = true;
58913
+ this._handleChunkEnd();
58914
+ if (this.finished) {
58915
+ this.finished();
58916
+ }
58917
+ };
58918
+ }
58919
+ });
58920
+
58921
+ // node_modules/pngjs/lib/bitmapper.js
58922
+ var require_bitmapper = __commonJS({
58923
+ "node_modules/pngjs/lib/bitmapper.js"(exports) {
58924
+ "use strict";
58925
+ var interlaceUtils = require_interlace();
58926
+ var pixelBppMapper = [
58927
+ // 0 - dummy entry
58928
+ function() {
58929
+ },
58930
+ // 1 - L
58931
+ // 0: 0, 1: 0, 2: 0, 3: 0xff
58932
+ function(pxData, data, pxPos, rawPos) {
58933
+ if (rawPos === data.length) {
58934
+ throw new Error("Ran out of data");
58935
+ }
58936
+ let pixel = data[rawPos];
58937
+ pxData[pxPos] = pixel;
58938
+ pxData[pxPos + 1] = pixel;
58939
+ pxData[pxPos + 2] = pixel;
58940
+ pxData[pxPos + 3] = 255;
58941
+ },
58942
+ // 2 - LA
58943
+ // 0: 0, 1: 0, 2: 0, 3: 1
58944
+ function(pxData, data, pxPos, rawPos) {
58945
+ if (rawPos + 1 >= data.length) {
58946
+ throw new Error("Ran out of data");
58947
+ }
58948
+ let pixel = data[rawPos];
58949
+ pxData[pxPos] = pixel;
58950
+ pxData[pxPos + 1] = pixel;
58951
+ pxData[pxPos + 2] = pixel;
58952
+ pxData[pxPos + 3] = data[rawPos + 1];
58953
+ },
58954
+ // 3 - RGB
58955
+ // 0: 0, 1: 1, 2: 2, 3: 0xff
58956
+ function(pxData, data, pxPos, rawPos) {
58957
+ if (rawPos + 2 >= data.length) {
58958
+ throw new Error("Ran out of data");
58959
+ }
58960
+ pxData[pxPos] = data[rawPos];
58961
+ pxData[pxPos + 1] = data[rawPos + 1];
58962
+ pxData[pxPos + 2] = data[rawPos + 2];
58963
+ pxData[pxPos + 3] = 255;
58964
+ },
58965
+ // 4 - RGBA
58966
+ // 0: 0, 1: 1, 2: 2, 3: 3
58967
+ function(pxData, data, pxPos, rawPos) {
58968
+ if (rawPos + 3 >= data.length) {
58969
+ throw new Error("Ran out of data");
58970
+ }
58971
+ pxData[pxPos] = data[rawPos];
58972
+ pxData[pxPos + 1] = data[rawPos + 1];
58973
+ pxData[pxPos + 2] = data[rawPos + 2];
58974
+ pxData[pxPos + 3] = data[rawPos + 3];
58975
+ }
58976
+ ];
58977
+ var pixelBppCustomMapper = [
58978
+ // 0 - dummy entry
58979
+ function() {
58980
+ },
58981
+ // 1 - L
58982
+ // 0: 0, 1: 0, 2: 0, 3: 0xff
58983
+ function(pxData, pixelData, pxPos, maxBit) {
58984
+ let pixel = pixelData[0];
58985
+ pxData[pxPos] = pixel;
58986
+ pxData[pxPos + 1] = pixel;
58987
+ pxData[pxPos + 2] = pixel;
58988
+ pxData[pxPos + 3] = maxBit;
58989
+ },
58990
+ // 2 - LA
58991
+ // 0: 0, 1: 0, 2: 0, 3: 1
58992
+ function(pxData, pixelData, pxPos) {
58993
+ let pixel = pixelData[0];
58994
+ pxData[pxPos] = pixel;
58995
+ pxData[pxPos + 1] = pixel;
58996
+ pxData[pxPos + 2] = pixel;
58997
+ pxData[pxPos + 3] = pixelData[1];
58998
+ },
58999
+ // 3 - RGB
59000
+ // 0: 0, 1: 1, 2: 2, 3: 0xff
59001
+ function(pxData, pixelData, pxPos, maxBit) {
59002
+ pxData[pxPos] = pixelData[0];
59003
+ pxData[pxPos + 1] = pixelData[1];
59004
+ pxData[pxPos + 2] = pixelData[2];
59005
+ pxData[pxPos + 3] = maxBit;
59006
+ },
59007
+ // 4 - RGBA
59008
+ // 0: 0, 1: 1, 2: 2, 3: 3
59009
+ function(pxData, pixelData, pxPos) {
59010
+ pxData[pxPos] = pixelData[0];
59011
+ pxData[pxPos + 1] = pixelData[1];
59012
+ pxData[pxPos + 2] = pixelData[2];
59013
+ pxData[pxPos + 3] = pixelData[3];
59014
+ }
59015
+ ];
59016
+ function bitRetriever(data, depth) {
59017
+ let leftOver = [];
59018
+ let i = 0;
59019
+ function split() {
59020
+ if (i === data.length) {
59021
+ throw new Error("Ran out of data");
59022
+ }
59023
+ let byte = data[i];
59024
+ i++;
59025
+ let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
59026
+ switch (depth) {
59027
+ default:
59028
+ throw new Error("unrecognised depth");
59029
+ case 16:
59030
+ byte2 = data[i];
59031
+ i++;
59032
+ leftOver.push((byte << 8) + byte2);
59033
+ break;
59034
+ case 4:
59035
+ byte2 = byte & 15;
59036
+ byte1 = byte >> 4;
59037
+ leftOver.push(byte1, byte2);
59038
+ break;
59039
+ case 2:
59040
+ byte4 = byte & 3;
59041
+ byte3 = byte >> 2 & 3;
59042
+ byte2 = byte >> 4 & 3;
59043
+ byte1 = byte >> 6 & 3;
59044
+ leftOver.push(byte1, byte2, byte3, byte4);
59045
+ break;
59046
+ case 1:
59047
+ byte8 = byte & 1;
59048
+ byte7 = byte >> 1 & 1;
59049
+ byte6 = byte >> 2 & 1;
59050
+ byte5 = byte >> 3 & 1;
59051
+ byte4 = byte >> 4 & 1;
59052
+ byte3 = byte >> 5 & 1;
59053
+ byte2 = byte >> 6 & 1;
59054
+ byte1 = byte >> 7 & 1;
59055
+ leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
59056
+ break;
59057
+ }
59058
+ }
59059
+ return {
59060
+ get: function(count) {
59061
+ while (leftOver.length < count) {
59062
+ split();
59063
+ }
59064
+ let returner = leftOver.slice(0, count);
59065
+ leftOver = leftOver.slice(count);
59066
+ return returner;
59067
+ },
59068
+ resetAfterLine: function() {
59069
+ leftOver.length = 0;
59070
+ },
59071
+ end: function() {
59072
+ if (i !== data.length) {
59073
+ throw new Error("extra data found");
59074
+ }
59075
+ }
59076
+ };
59077
+ }
59078
+ function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) {
59079
+ let imageWidth = image.width;
59080
+ let imageHeight = image.height;
59081
+ let imagePass = image.index;
59082
+ for (let y = 0; y < imageHeight; y++) {
59083
+ for (let x = 0; x < imageWidth; x++) {
59084
+ let pxPos = getPxPos(x, y, imagePass);
59085
+ pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
59086
+ rawPos += bpp;
59087
+ }
59088
+ }
59089
+ return rawPos;
59090
+ }
59091
+ function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) {
59092
+ let imageWidth = image.width;
59093
+ let imageHeight = image.height;
59094
+ let imagePass = image.index;
59095
+ for (let y = 0; y < imageHeight; y++) {
59096
+ for (let x = 0; x < imageWidth; x++) {
59097
+ let pixelData = bits.get(bpp);
59098
+ let pxPos = getPxPos(x, y, imagePass);
59099
+ pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
59100
+ }
59101
+ bits.resetAfterLine();
59102
+ }
59103
+ }
59104
+ exports.dataToBitMap = function(data, bitmapInfo) {
59105
+ let width = bitmapInfo.width;
59106
+ let height = bitmapInfo.height;
59107
+ let depth = bitmapInfo.depth;
59108
+ let bpp = bitmapInfo.bpp;
59109
+ let interlace = bitmapInfo.interlace;
59110
+ let bits;
59111
+ if (depth !== 8) {
59112
+ bits = bitRetriever(data, depth);
59113
+ }
59114
+ let pxData;
59115
+ if (depth <= 8) {
59116
+ pxData = Buffer.alloc(width * height * 4);
59117
+ } else {
59118
+ pxData = new Uint16Array(width * height * 4);
59119
+ }
59120
+ let maxBit = Math.pow(2, depth) - 1;
59121
+ let rawPos = 0;
59122
+ let images;
59123
+ let getPxPos;
59124
+ if (interlace) {
59125
+ images = interlaceUtils.getImagePasses(width, height);
59126
+ getPxPos = interlaceUtils.getInterlaceIterator(width, height);
59127
+ } else {
59128
+ let nonInterlacedPxPos = 0;
59129
+ getPxPos = function() {
59130
+ let returner = nonInterlacedPxPos;
59131
+ nonInterlacedPxPos += 4;
59132
+ return returner;
59133
+ };
59134
+ images = [{ width, height }];
59135
+ }
59136
+ for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {
59137
+ if (depth === 8) {
59138
+ rawPos = mapImage8Bit(
59139
+ images[imageIndex],
59140
+ pxData,
59141
+ getPxPos,
59142
+ bpp,
59143
+ data,
59144
+ rawPos
59145
+ );
59146
+ } else {
59147
+ mapImageCustomBit(
59148
+ images[imageIndex],
59149
+ pxData,
59150
+ getPxPos,
59151
+ bpp,
59152
+ bits,
59153
+ maxBit
59154
+ );
59155
+ }
59156
+ }
59157
+ if (depth === 8) {
59158
+ if (rawPos !== data.length) {
59159
+ throw new Error("extra data found");
59160
+ }
59161
+ } else {
59162
+ bits.end();
59163
+ }
59164
+ return pxData;
59165
+ };
59166
+ }
59167
+ });
59168
+
59169
+ // node_modules/pngjs/lib/format-normaliser.js
59170
+ var require_format_normaliser = __commonJS({
59171
+ "node_modules/pngjs/lib/format-normaliser.js"(exports, module) {
59172
+ "use strict";
59173
+ function dePalette(indata, outdata, width, height, palette) {
59174
+ let pxPos = 0;
59175
+ for (let y = 0; y < height; y++) {
59176
+ for (let x = 0; x < width; x++) {
59177
+ let color = palette[indata[pxPos]];
59178
+ if (!color) {
59179
+ throw new Error("index " + indata[pxPos] + " not in palette");
59180
+ }
59181
+ for (let i = 0; i < 4; i++) {
59182
+ outdata[pxPos + i] = color[i];
59183
+ }
59184
+ pxPos += 4;
59185
+ }
59186
+ }
59187
+ }
59188
+ function replaceTransparentColor(indata, outdata, width, height, transColor) {
59189
+ let pxPos = 0;
59190
+ for (let y = 0; y < height; y++) {
59191
+ for (let x = 0; x < width; x++) {
59192
+ let makeTrans = false;
59193
+ if (transColor.length === 1) {
59194
+ if (transColor[0] === indata[pxPos]) {
59195
+ makeTrans = true;
59196
+ }
59197
+ } else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
59198
+ makeTrans = true;
59199
+ }
59200
+ if (makeTrans) {
59201
+ for (let i = 0; i < 4; i++) {
59202
+ outdata[pxPos + i] = 0;
59203
+ }
59204
+ }
59205
+ pxPos += 4;
59206
+ }
59207
+ }
59208
+ }
59209
+ function scaleDepth(indata, outdata, width, height, depth) {
59210
+ let maxOutSample = 255;
59211
+ let maxInSample = Math.pow(2, depth) - 1;
59212
+ let pxPos = 0;
59213
+ for (let y = 0; y < height; y++) {
59214
+ for (let x = 0; x < width; x++) {
59215
+ for (let i = 0; i < 4; i++) {
59216
+ outdata[pxPos + i] = Math.floor(
59217
+ indata[pxPos + i] * maxOutSample / maxInSample + 0.5
59218
+ );
59219
+ }
59220
+ pxPos += 4;
59221
+ }
59222
+ }
59223
+ }
59224
+ module.exports = function(indata, imageData, skipRescale = false) {
59225
+ let depth = imageData.depth;
59226
+ let width = imageData.width;
59227
+ let height = imageData.height;
59228
+ let colorType = imageData.colorType;
59229
+ let transColor = imageData.transColor;
59230
+ let palette = imageData.palette;
59231
+ let outdata = indata;
59232
+ if (colorType === 3) {
59233
+ dePalette(indata, outdata, width, height, palette);
59234
+ } else {
59235
+ if (transColor) {
59236
+ replaceTransparentColor(indata, outdata, width, height, transColor);
59237
+ }
59238
+ if (depth !== 8 && !skipRescale) {
59239
+ if (depth === 16) {
59240
+ outdata = Buffer.alloc(width * height * 4);
59241
+ }
59242
+ scaleDepth(indata, outdata, width, height, depth);
59243
+ }
59244
+ }
59245
+ return outdata;
59246
+ };
59247
+ }
59248
+ });
59249
+
59250
+ // node_modules/pngjs/lib/parser-async.js
59251
+ var require_parser_async = __commonJS({
59252
+ "node_modules/pngjs/lib/parser-async.js"(exports, module) {
59253
+ "use strict";
59254
+ var util2 = __require("util");
59255
+ var zlib = __require("zlib");
59256
+ var ChunkStream = require_chunkstream();
59257
+ var FilterAsync = require_filter_parse_async();
59258
+ var Parser = require_parser();
59259
+ var bitmapper = require_bitmapper();
59260
+ var formatNormaliser = require_format_normaliser();
59261
+ var ParserAsync = module.exports = function(options3) {
59262
+ ChunkStream.call(this);
59263
+ this._parser = new Parser(options3, {
59264
+ read: this.read.bind(this),
59265
+ error: this._handleError.bind(this),
59266
+ metadata: this._handleMetaData.bind(this),
59267
+ gamma: this.emit.bind(this, "gamma"),
59268
+ palette: this._handlePalette.bind(this),
59269
+ transColor: this._handleTransColor.bind(this),
59270
+ finished: this._finished.bind(this),
59271
+ inflateData: this._inflateData.bind(this),
59272
+ simpleTransparency: this._simpleTransparency.bind(this),
59273
+ headersFinished: this._headersFinished.bind(this)
59274
+ });
59275
+ this._options = options3;
59276
+ this.writable = true;
59277
+ this._parser.start();
59278
+ };
59279
+ util2.inherits(ParserAsync, ChunkStream);
59280
+ ParserAsync.prototype._handleError = function(err) {
59281
+ this.emit("error", err);
59282
+ this.writable = false;
59283
+ this.destroy();
59284
+ if (this._inflate && this._inflate.destroy) {
59285
+ this._inflate.destroy();
59286
+ }
59287
+ if (this._filter) {
59288
+ this._filter.destroy();
59289
+ this._filter.on("error", function() {
59290
+ });
59291
+ }
59292
+ this.errord = true;
59293
+ };
59294
+ ParserAsync.prototype._inflateData = function(data) {
59295
+ if (!this._inflate) {
59296
+ if (this._bitmapInfo.interlace) {
59297
+ this._inflate = zlib.createInflate();
59298
+ this._inflate.on("error", this.emit.bind(this, "error"));
59299
+ this._filter.on("complete", this._complete.bind(this));
59300
+ this._inflate.pipe(this._filter);
59301
+ } else {
59302
+ let rowSize = (this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7 >> 3) + 1;
59303
+ let imageSize = rowSize * this._bitmapInfo.height;
59304
+ let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
59305
+ this._inflate = zlib.createInflate({ chunkSize });
59306
+ let leftToInflate = imageSize;
59307
+ let emitError = this.emit.bind(this, "error");
59308
+ this._inflate.on("error", function(err) {
59309
+ if (!leftToInflate) {
59310
+ return;
59311
+ }
59312
+ emitError(err);
59313
+ });
59314
+ this._filter.on("complete", this._complete.bind(this));
59315
+ let filterWrite = this._filter.write.bind(this._filter);
59316
+ this._inflate.on("data", function(chunk) {
59317
+ if (!leftToInflate) {
59318
+ return;
59319
+ }
59320
+ if (chunk.length > leftToInflate) {
59321
+ chunk = chunk.slice(0, leftToInflate);
59322
+ }
59323
+ leftToInflate -= chunk.length;
59324
+ filterWrite(chunk);
59325
+ });
59326
+ this._inflate.on("end", this._filter.end.bind(this._filter));
59327
+ }
59328
+ }
59329
+ this._inflate.write(data);
59330
+ };
59331
+ ParserAsync.prototype._handleMetaData = function(metaData) {
59332
+ this._metaData = metaData;
59333
+ this._bitmapInfo = Object.create(metaData);
59334
+ this._filter = new FilterAsync(this._bitmapInfo);
59335
+ };
59336
+ ParserAsync.prototype._handleTransColor = function(transColor) {
59337
+ this._bitmapInfo.transColor = transColor;
59338
+ };
59339
+ ParserAsync.prototype._handlePalette = function(palette) {
59340
+ this._bitmapInfo.palette = palette;
59341
+ };
59342
+ ParserAsync.prototype._simpleTransparency = function() {
59343
+ this._metaData.alpha = true;
59344
+ };
59345
+ ParserAsync.prototype._headersFinished = function() {
59346
+ this.emit("metadata", this._metaData);
59347
+ };
59348
+ ParserAsync.prototype._finished = function() {
59349
+ if (this.errord) {
59350
+ return;
59351
+ }
59352
+ if (!this._inflate) {
59353
+ this.emit("error", "No Inflate block");
59354
+ } else {
59355
+ this._inflate.end();
59356
+ }
59357
+ };
59358
+ ParserAsync.prototype._complete = function(filteredData) {
59359
+ if (this.errord) {
59360
+ return;
59361
+ }
59362
+ let normalisedBitmapData;
59363
+ try {
59364
+ let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
59365
+ normalisedBitmapData = formatNormaliser(
59366
+ bitmapData,
59367
+ this._bitmapInfo,
59368
+ this._options.skipRescale
59369
+ );
59370
+ bitmapData = null;
59371
+ } catch (ex) {
59372
+ this._handleError(ex);
59373
+ return;
59374
+ }
59375
+ this.emit("parsed", normalisedBitmapData);
59376
+ };
59377
+ }
59378
+ });
59379
+
59380
+ // node_modules/pngjs/lib/bitpacker.js
59381
+ var require_bitpacker = __commonJS({
59382
+ "node_modules/pngjs/lib/bitpacker.js"(exports, module) {
59383
+ "use strict";
59384
+ var constants = require_constants2();
59385
+ module.exports = function(dataIn, width, height, options3) {
59386
+ let outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(
59387
+ options3.colorType
59388
+ ) !== -1;
59389
+ if (options3.colorType === options3.inputColorType) {
59390
+ let bigEndian = (function() {
59391
+ let buffer = new ArrayBuffer(2);
59392
+ new DataView(buffer).setInt16(
59393
+ 0,
59394
+ 256,
59395
+ true
59396
+ /* littleEndian */
59397
+ );
59398
+ return new Int16Array(buffer)[0] !== 256;
59399
+ })();
59400
+ if (options3.bitDepth === 8 || options3.bitDepth === 16 && bigEndian) {
59401
+ return dataIn;
59402
+ }
59403
+ }
59404
+ let data = options3.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
59405
+ let maxValue = 255;
59406
+ let inBpp = constants.COLORTYPE_TO_BPP_MAP[options3.inputColorType];
59407
+ if (inBpp === 4 && !options3.inputHasAlpha) {
59408
+ inBpp = 3;
59409
+ }
59410
+ let outBpp = constants.COLORTYPE_TO_BPP_MAP[options3.colorType];
59411
+ if (options3.bitDepth === 16) {
59412
+ maxValue = 65535;
59413
+ outBpp *= 2;
59414
+ }
59415
+ let outData = Buffer.alloc(width * height * outBpp);
59416
+ let inIndex = 0;
59417
+ let outIndex = 0;
59418
+ let bgColor = options3.bgColor || {};
59419
+ if (bgColor.red === void 0) {
59420
+ bgColor.red = maxValue;
59421
+ }
59422
+ if (bgColor.green === void 0) {
59423
+ bgColor.green = maxValue;
59424
+ }
59425
+ if (bgColor.blue === void 0) {
59426
+ bgColor.blue = maxValue;
59427
+ }
59428
+ function getRGBA() {
59429
+ let red;
59430
+ let green;
59431
+ let blue;
59432
+ let alpha = maxValue;
59433
+ switch (options3.inputColorType) {
59434
+ case constants.COLORTYPE_COLOR_ALPHA:
59435
+ alpha = data[inIndex + 3];
59436
+ red = data[inIndex];
59437
+ green = data[inIndex + 1];
59438
+ blue = data[inIndex + 2];
59439
+ break;
59440
+ case constants.COLORTYPE_COLOR:
59441
+ red = data[inIndex];
59442
+ green = data[inIndex + 1];
59443
+ blue = data[inIndex + 2];
59444
+ break;
59445
+ case constants.COLORTYPE_ALPHA:
59446
+ alpha = data[inIndex + 1];
59447
+ red = data[inIndex];
59448
+ green = red;
59449
+ blue = red;
59450
+ break;
59451
+ case constants.COLORTYPE_GRAYSCALE:
59452
+ red = data[inIndex];
59453
+ green = red;
59454
+ blue = red;
59455
+ break;
59456
+ default:
59457
+ throw new Error(
59458
+ "input color type:" + options3.inputColorType + " is not supported at present"
59459
+ );
59460
+ }
59461
+ if (options3.inputHasAlpha) {
59462
+ if (!outHasAlpha) {
59463
+ alpha /= maxValue;
59464
+ red = Math.min(
59465
+ Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0),
59466
+ maxValue
59467
+ );
59468
+ green = Math.min(
59469
+ Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0),
59470
+ maxValue
59471
+ );
59472
+ blue = Math.min(
59473
+ Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0),
59474
+ maxValue
59475
+ );
59476
+ }
59477
+ }
59478
+ return { red, green, blue, alpha };
59479
+ }
59480
+ for (let y = 0; y < height; y++) {
59481
+ for (let x = 0; x < width; x++) {
59482
+ let rgba = getRGBA(data, inIndex);
59483
+ switch (options3.colorType) {
59484
+ case constants.COLORTYPE_COLOR_ALPHA:
59485
+ case constants.COLORTYPE_COLOR:
59486
+ if (options3.bitDepth === 8) {
59487
+ outData[outIndex] = rgba.red;
59488
+ outData[outIndex + 1] = rgba.green;
59489
+ outData[outIndex + 2] = rgba.blue;
59490
+ if (outHasAlpha) {
59491
+ outData[outIndex + 3] = rgba.alpha;
59492
+ }
59493
+ } else {
59494
+ outData.writeUInt16BE(rgba.red, outIndex);
59495
+ outData.writeUInt16BE(rgba.green, outIndex + 2);
59496
+ outData.writeUInt16BE(rgba.blue, outIndex + 4);
59497
+ if (outHasAlpha) {
59498
+ outData.writeUInt16BE(rgba.alpha, outIndex + 6);
59499
+ }
59500
+ }
59501
+ break;
59502
+ case constants.COLORTYPE_ALPHA:
59503
+ case constants.COLORTYPE_GRAYSCALE: {
59504
+ let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
59505
+ if (options3.bitDepth === 8) {
59506
+ outData[outIndex] = grayscale;
59507
+ if (outHasAlpha) {
59508
+ outData[outIndex + 1] = rgba.alpha;
59509
+ }
59510
+ } else {
59511
+ outData.writeUInt16BE(grayscale, outIndex);
59512
+ if (outHasAlpha) {
59513
+ outData.writeUInt16BE(rgba.alpha, outIndex + 2);
59514
+ }
59515
+ }
59516
+ break;
59517
+ }
59518
+ default:
59519
+ throw new Error("unrecognised color Type " + options3.colorType);
59520
+ }
59521
+ inIndex += inBpp;
59522
+ outIndex += outBpp;
59523
+ }
59524
+ }
59525
+ return outData;
59526
+ };
59527
+ }
59528
+ });
59529
+
59530
+ // node_modules/pngjs/lib/filter-pack.js
59531
+ var require_filter_pack = __commonJS({
59532
+ "node_modules/pngjs/lib/filter-pack.js"(exports, module) {
59533
+ "use strict";
59534
+ var paethPredictor = require_paeth_predictor();
59535
+ function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
59536
+ for (let x = 0; x < byteWidth; x++) {
59537
+ rawData[rawPos + x] = pxData[pxPos + x];
59538
+ }
59539
+ }
59540
+ function filterSumNone(pxData, pxPos, byteWidth) {
59541
+ let sum = 0;
59542
+ let length = pxPos + byteWidth;
59543
+ for (let i = pxPos; i < length; i++) {
59544
+ sum += Math.abs(pxData[i]);
59545
+ }
59546
+ return sum;
59547
+ }
59548
+ function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
59549
+ for (let x = 0; x < byteWidth; x++) {
59550
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
59551
+ let val = pxData[pxPos + x] - left;
59552
+ rawData[rawPos + x] = val;
59553
+ }
59554
+ }
59555
+ function filterSumSub(pxData, pxPos, byteWidth, bpp) {
59556
+ let sum = 0;
59557
+ for (let x = 0; x < byteWidth; x++) {
59558
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
59559
+ let val = pxData[pxPos + x] - left;
59560
+ sum += Math.abs(val);
59561
+ }
59562
+ return sum;
59563
+ }
59564
+ function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
59565
+ for (let x = 0; x < byteWidth; x++) {
59566
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
59567
+ let val = pxData[pxPos + x] - up;
59568
+ rawData[rawPos + x] = val;
59569
+ }
59570
+ }
59571
+ function filterSumUp(pxData, pxPos, byteWidth) {
59572
+ let sum = 0;
59573
+ let length = pxPos + byteWidth;
59574
+ for (let x = pxPos; x < length; x++) {
59575
+ let up = pxPos > 0 ? pxData[x - byteWidth] : 0;
59576
+ let val = pxData[x] - up;
59577
+ sum += Math.abs(val);
59578
+ }
59579
+ return sum;
59580
+ }
59581
+ function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
59582
+ for (let x = 0; x < byteWidth; x++) {
59583
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
59584
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
59585
+ let val = pxData[pxPos + x] - (left + up >> 1);
59586
+ rawData[rawPos + x] = val;
59587
+ }
59588
+ }
59589
+ function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
59590
+ let sum = 0;
59591
+ for (let x = 0; x < byteWidth; x++) {
59592
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
59593
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
59594
+ let val = pxData[pxPos + x] - (left + up >> 1);
59595
+ sum += Math.abs(val);
59596
+ }
59597
+ return sum;
59598
+ }
59599
+ function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
59600
+ for (let x = 0; x < byteWidth; x++) {
59601
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
59602
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
59603
+ let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
59604
+ let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
59605
+ rawData[rawPos + x] = val;
59606
+ }
59607
+ }
59608
+ function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
59609
+ let sum = 0;
59610
+ for (let x = 0; x < byteWidth; x++) {
59611
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
59612
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
59613
+ let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
59614
+ let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
59615
+ sum += Math.abs(val);
59616
+ }
59617
+ return sum;
59618
+ }
59619
+ var filters = {
59620
+ 0: filterNone,
59621
+ 1: filterSub,
59622
+ 2: filterUp,
59623
+ 3: filterAvg,
59624
+ 4: filterPaeth
59625
+ };
59626
+ var filterSums = {
59627
+ 0: filterSumNone,
59628
+ 1: filterSumSub,
59629
+ 2: filterSumUp,
59630
+ 3: filterSumAvg,
59631
+ 4: filterSumPaeth
59632
+ };
59633
+ module.exports = function(pxData, width, height, options3, bpp) {
59634
+ let filterTypes;
59635
+ if (!("filterType" in options3) || options3.filterType === -1) {
59636
+ filterTypes = [0, 1, 2, 3, 4];
59637
+ } else if (typeof options3.filterType === "number") {
59638
+ filterTypes = [options3.filterType];
59639
+ } else {
59640
+ throw new Error("unrecognised filter types");
59641
+ }
59642
+ if (options3.bitDepth === 16) {
59643
+ bpp *= 2;
59644
+ }
59645
+ let byteWidth = width * bpp;
59646
+ let rawPos = 0;
59647
+ let pxPos = 0;
59648
+ let rawData = Buffer.alloc((byteWidth + 1) * height);
59649
+ let sel = filterTypes[0];
59650
+ for (let y = 0; y < height; y++) {
59651
+ if (filterTypes.length > 1) {
59652
+ let min = Infinity;
59653
+ for (let i = 0; i < filterTypes.length; i++) {
59654
+ let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
59655
+ if (sum < min) {
59656
+ sel = filterTypes[i];
59657
+ min = sum;
59658
+ }
59659
+ }
59660
+ }
59661
+ rawData[rawPos] = sel;
59662
+ rawPos++;
59663
+ filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
59664
+ rawPos += byteWidth;
59665
+ pxPos += byteWidth;
59666
+ }
59667
+ return rawData;
59668
+ };
59669
+ }
59670
+ });
59671
+
59672
+ // node_modules/pngjs/lib/packer.js
59673
+ var require_packer = __commonJS({
59674
+ "node_modules/pngjs/lib/packer.js"(exports, module) {
59675
+ "use strict";
59676
+ var constants = require_constants2();
59677
+ var CrcStream = require_crc();
59678
+ var bitPacker = require_bitpacker();
59679
+ var filter = require_filter_pack();
59680
+ var zlib = __require("zlib");
59681
+ var Packer = module.exports = function(options3) {
59682
+ this._options = options3;
59683
+ options3.deflateChunkSize = options3.deflateChunkSize || 32 * 1024;
59684
+ options3.deflateLevel = options3.deflateLevel != null ? options3.deflateLevel : 9;
59685
+ options3.deflateStrategy = options3.deflateStrategy != null ? options3.deflateStrategy : 3;
59686
+ options3.inputHasAlpha = options3.inputHasAlpha != null ? options3.inputHasAlpha : true;
59687
+ options3.deflateFactory = options3.deflateFactory || zlib.createDeflate;
59688
+ options3.bitDepth = options3.bitDepth || 8;
59689
+ options3.colorType = typeof options3.colorType === "number" ? options3.colorType : constants.COLORTYPE_COLOR_ALPHA;
59690
+ options3.inputColorType = typeof options3.inputColorType === "number" ? options3.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
59691
+ if ([
59692
+ constants.COLORTYPE_GRAYSCALE,
59693
+ constants.COLORTYPE_COLOR,
59694
+ constants.COLORTYPE_COLOR_ALPHA,
59695
+ constants.COLORTYPE_ALPHA
59696
+ ].indexOf(options3.colorType) === -1) {
59697
+ throw new Error(
59698
+ "option color type:" + options3.colorType + " is not supported at present"
59699
+ );
59700
+ }
59701
+ if ([
59702
+ constants.COLORTYPE_GRAYSCALE,
59703
+ constants.COLORTYPE_COLOR,
59704
+ constants.COLORTYPE_COLOR_ALPHA,
59705
+ constants.COLORTYPE_ALPHA
59706
+ ].indexOf(options3.inputColorType) === -1) {
59707
+ throw new Error(
59708
+ "option input color type:" + options3.inputColorType + " is not supported at present"
59709
+ );
59710
+ }
59711
+ if (options3.bitDepth !== 8 && options3.bitDepth !== 16) {
59712
+ throw new Error(
59713
+ "option bit depth:" + options3.bitDepth + " is not supported at present"
59714
+ );
59715
+ }
59716
+ };
59717
+ Packer.prototype.getDeflateOptions = function() {
59718
+ return {
59719
+ chunkSize: this._options.deflateChunkSize,
59720
+ level: this._options.deflateLevel,
59721
+ strategy: this._options.deflateStrategy
59722
+ };
59723
+ };
59724
+ Packer.prototype.createDeflate = function() {
59725
+ return this._options.deflateFactory(this.getDeflateOptions());
59726
+ };
59727
+ Packer.prototype.filterData = function(data, width, height) {
59728
+ let packedData = bitPacker(data, width, height, this._options);
59729
+ let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
59730
+ let filteredData = filter(packedData, width, height, this._options, bpp);
59731
+ return filteredData;
59732
+ };
59733
+ Packer.prototype._packChunk = function(type, data) {
59734
+ let len = data ? data.length : 0;
59735
+ let buf = Buffer.alloc(len + 12);
59736
+ buf.writeUInt32BE(len, 0);
59737
+ buf.writeUInt32BE(type, 4);
59738
+ if (data) {
59739
+ data.copy(buf, 8);
59740
+ }
59741
+ buf.writeInt32BE(
59742
+ CrcStream.crc32(buf.slice(4, buf.length - 4)),
59743
+ buf.length - 4
59744
+ );
59745
+ return buf;
59746
+ };
59747
+ Packer.prototype.packGAMA = function(gamma) {
59748
+ let buf = Buffer.alloc(4);
59749
+ buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
59750
+ return this._packChunk(constants.TYPE_gAMA, buf);
59751
+ };
59752
+ Packer.prototype.packIHDR = function(width, height) {
59753
+ let buf = Buffer.alloc(13);
59754
+ buf.writeUInt32BE(width, 0);
59755
+ buf.writeUInt32BE(height, 4);
59756
+ buf[8] = this._options.bitDepth;
59757
+ buf[9] = this._options.colorType;
59758
+ buf[10] = 0;
59759
+ buf[11] = 0;
59760
+ buf[12] = 0;
59761
+ return this._packChunk(constants.TYPE_IHDR, buf);
59762
+ };
59763
+ Packer.prototype.packIDAT = function(data) {
59764
+ return this._packChunk(constants.TYPE_IDAT, data);
59765
+ };
59766
+ Packer.prototype.packIEND = function() {
59767
+ return this._packChunk(constants.TYPE_IEND, null);
59768
+ };
59769
+ }
59770
+ });
59771
+
59772
+ // node_modules/pngjs/lib/packer-async.js
59773
+ var require_packer_async = __commonJS({
59774
+ "node_modules/pngjs/lib/packer-async.js"(exports, module) {
59775
+ "use strict";
59776
+ var util2 = __require("util");
59777
+ var Stream = __require("stream");
59778
+ var constants = require_constants2();
59779
+ var Packer = require_packer();
59780
+ var PackerAsync = module.exports = function(opt) {
59781
+ Stream.call(this);
59782
+ let options3 = opt || {};
59783
+ this._packer = new Packer(options3);
59784
+ this._deflate = this._packer.createDeflate();
59785
+ this.readable = true;
59786
+ };
59787
+ util2.inherits(PackerAsync, Stream);
59788
+ PackerAsync.prototype.pack = function(data, width, height, gamma) {
59789
+ this.emit("data", Buffer.from(constants.PNG_SIGNATURE));
59790
+ this.emit("data", this._packer.packIHDR(width, height));
59791
+ if (gamma) {
59792
+ this.emit("data", this._packer.packGAMA(gamma));
59793
+ }
59794
+ let filteredData = this._packer.filterData(data, width, height);
59795
+ this._deflate.on("error", this.emit.bind(this, "error"));
59796
+ this._deflate.on(
59797
+ "data",
59798
+ function(compressedData) {
59799
+ this.emit("data", this._packer.packIDAT(compressedData));
59800
+ }.bind(this)
59801
+ );
59802
+ this._deflate.on(
59803
+ "end",
59804
+ function() {
59805
+ this.emit("data", this._packer.packIEND());
59806
+ this.emit("end");
59807
+ }.bind(this)
59808
+ );
59809
+ this._deflate.end(filteredData);
59810
+ };
59811
+ }
59812
+ });
59813
+
59814
+ // node_modules/pngjs/lib/sync-inflate.js
59815
+ var require_sync_inflate = __commonJS({
59816
+ "node_modules/pngjs/lib/sync-inflate.js"(exports, module) {
59817
+ "use strict";
59818
+ var assert2 = __require("assert").ok;
59819
+ var zlib = __require("zlib");
59820
+ var util2 = __require("util");
59821
+ var kMaxLength = __require("buffer").kMaxLength;
59822
+ function Inflate(opts) {
59823
+ if (!(this instanceof Inflate)) {
59824
+ return new Inflate(opts);
59825
+ }
59826
+ if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
59827
+ opts.chunkSize = zlib.Z_MIN_CHUNK;
59828
+ }
59829
+ zlib.Inflate.call(this, opts);
59830
+ this._offset = this._offset === void 0 ? this._outOffset : this._offset;
59831
+ this._buffer = this._buffer || this._outBuffer;
59832
+ if (opts && opts.maxLength != null) {
59833
+ this._maxLength = opts.maxLength;
59834
+ }
59835
+ }
59836
+ function createInflate(opts) {
59837
+ return new Inflate(opts);
59838
+ }
59839
+ function _close(engine, callback) {
59840
+ if (callback) {
59841
+ process.nextTick(callback);
59842
+ }
59843
+ if (!engine._handle) {
59844
+ return;
59845
+ }
59846
+ engine._handle.close();
59847
+ engine._handle = null;
59848
+ }
59849
+ Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
59850
+ if (typeof asyncCb === "function") {
59851
+ return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
59852
+ }
59853
+ let self2 = this;
59854
+ let availInBefore = chunk && chunk.length;
59855
+ let availOutBefore = this._chunkSize - this._offset;
59856
+ let leftToInflate = this._maxLength;
59857
+ let inOff = 0;
59858
+ let buffers = [];
59859
+ let nread = 0;
59860
+ let error2;
59861
+ this.on("error", function(err) {
59862
+ error2 = err;
59863
+ });
59864
+ function handleChunk(availInAfter, availOutAfter) {
59865
+ if (self2._hadError) {
59866
+ return;
59867
+ }
59868
+ let have = availOutBefore - availOutAfter;
59869
+ assert2(have >= 0, "have should not go down");
59870
+ if (have > 0) {
59871
+ let out = self2._buffer.slice(self2._offset, self2._offset + have);
59872
+ self2._offset += have;
59873
+ if (out.length > leftToInflate) {
59874
+ out = out.slice(0, leftToInflate);
59875
+ }
59876
+ buffers.push(out);
59877
+ nread += out.length;
59878
+ leftToInflate -= out.length;
59879
+ if (leftToInflate === 0) {
59880
+ return false;
59881
+ }
59882
+ }
59883
+ if (availOutAfter === 0 || self2._offset >= self2._chunkSize) {
59884
+ availOutBefore = self2._chunkSize;
59885
+ self2._offset = 0;
59886
+ self2._buffer = Buffer.allocUnsafe(self2._chunkSize);
59887
+ }
59888
+ if (availOutAfter === 0) {
59889
+ inOff += availInBefore - availInAfter;
59890
+ availInBefore = availInAfter;
59891
+ return true;
59892
+ }
59893
+ return false;
59894
+ }
59895
+ assert2(this._handle, "zlib binding closed");
59896
+ let res;
59897
+ do {
59898
+ res = this._handle.writeSync(
59899
+ flushFlag,
59900
+ chunk,
59901
+ // in
59902
+ inOff,
59903
+ // in_off
59904
+ availInBefore,
59905
+ // in_len
59906
+ this._buffer,
59907
+ // out
59908
+ this._offset,
59909
+ //out_off
59910
+ availOutBefore
59911
+ );
59912
+ res = res || this._writeState;
59913
+ } while (!this._hadError && handleChunk(res[0], res[1]));
59914
+ if (this._hadError) {
59915
+ throw error2;
59916
+ }
59917
+ if (nread >= kMaxLength) {
59918
+ _close(this);
59919
+ throw new RangeError(
59920
+ "Cannot create final Buffer. It would be larger than 0x" + kMaxLength.toString(16) + " bytes"
59921
+ );
59922
+ }
59923
+ let buf = Buffer.concat(buffers, nread);
59924
+ _close(this);
59925
+ return buf;
59926
+ };
59927
+ util2.inherits(Inflate, zlib.Inflate);
59928
+ function zlibBufferSync(engine, buffer) {
59929
+ if (typeof buffer === "string") {
59930
+ buffer = Buffer.from(buffer);
59931
+ }
59932
+ if (!(buffer instanceof Buffer)) {
59933
+ throw new TypeError("Not a string or buffer");
59934
+ }
59935
+ let flushFlag = engine._finishFlushFlag;
59936
+ if (flushFlag == null) {
59937
+ flushFlag = zlib.Z_FINISH;
59938
+ }
59939
+ return engine._processChunk(buffer, flushFlag);
59940
+ }
59941
+ function inflateSync(buffer, opts) {
59942
+ return zlibBufferSync(new Inflate(opts), buffer);
59943
+ }
59944
+ module.exports = exports = inflateSync;
59945
+ exports.Inflate = Inflate;
59946
+ exports.createInflate = createInflate;
59947
+ exports.inflateSync = inflateSync;
59948
+ }
59949
+ });
59950
+
59951
+ // node_modules/pngjs/lib/sync-reader.js
59952
+ var require_sync_reader = __commonJS({
59953
+ "node_modules/pngjs/lib/sync-reader.js"(exports, module) {
59954
+ "use strict";
59955
+ var SyncReader = module.exports = function(buffer) {
59956
+ this._buffer = buffer;
59957
+ this._reads = [];
59958
+ };
59959
+ SyncReader.prototype.read = function(length, callback) {
59960
+ this._reads.push({
59961
+ length: Math.abs(length),
59962
+ // if length < 0 then at most this length
59963
+ allowLess: length < 0,
59964
+ func: callback
59965
+ });
59966
+ };
59967
+ SyncReader.prototype.process = function() {
59968
+ while (this._reads.length > 0 && this._buffer.length) {
59969
+ let read = this._reads[0];
59970
+ if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
59971
+ this._reads.shift();
59972
+ let buf = this._buffer;
59973
+ this._buffer = buf.slice(read.length);
59974
+ read.func.call(this, buf.slice(0, read.length));
59975
+ } else {
59976
+ break;
59977
+ }
59978
+ }
59979
+ if (this._reads.length > 0) {
59980
+ throw new Error("There are some read requests waitng on finished stream");
59981
+ }
59982
+ if (this._buffer.length > 0) {
59983
+ throw new Error("unrecognised content at end of stream");
59984
+ }
59985
+ };
59986
+ }
59987
+ });
59988
+
59989
+ // node_modules/pngjs/lib/filter-parse-sync.js
59990
+ var require_filter_parse_sync = __commonJS({
59991
+ "node_modules/pngjs/lib/filter-parse-sync.js"(exports) {
59992
+ "use strict";
59993
+ var SyncReader = require_sync_reader();
59994
+ var Filter = require_filter_parse();
59995
+ exports.process = function(inBuffer, bitmapInfo) {
59996
+ let outBuffers = [];
59997
+ let reader = new SyncReader(inBuffer);
59998
+ let filter = new Filter(bitmapInfo, {
59999
+ read: reader.read.bind(reader),
60000
+ write: function(bufferPart) {
60001
+ outBuffers.push(bufferPart);
60002
+ },
60003
+ complete: function() {
60004
+ }
60005
+ });
60006
+ filter.start();
60007
+ reader.process();
60008
+ return Buffer.concat(outBuffers);
60009
+ };
60010
+ }
60011
+ });
60012
+
60013
+ // node_modules/pngjs/lib/parser-sync.js
60014
+ var require_parser_sync = __commonJS({
60015
+ "node_modules/pngjs/lib/parser-sync.js"(exports, module) {
60016
+ "use strict";
60017
+ var hasSyncZlib = true;
60018
+ var zlib = __require("zlib");
60019
+ var inflateSync = require_sync_inflate();
60020
+ if (!zlib.deflateSync) {
60021
+ hasSyncZlib = false;
60022
+ }
60023
+ var SyncReader = require_sync_reader();
60024
+ var FilterSync = require_filter_parse_sync();
60025
+ var Parser = require_parser();
60026
+ var bitmapper = require_bitmapper();
60027
+ var formatNormaliser = require_format_normaliser();
60028
+ module.exports = function(buffer, options3) {
60029
+ if (!hasSyncZlib) {
60030
+ throw new Error(
60031
+ "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
60032
+ );
60033
+ }
60034
+ let err;
60035
+ function handleError(_err_) {
60036
+ err = _err_;
60037
+ }
60038
+ let metaData;
60039
+ function handleMetaData(_metaData_) {
60040
+ metaData = _metaData_;
60041
+ }
60042
+ function handleTransColor(transColor) {
60043
+ metaData.transColor = transColor;
60044
+ }
60045
+ function handlePalette(palette) {
60046
+ metaData.palette = palette;
60047
+ }
60048
+ function handleSimpleTransparency() {
60049
+ metaData.alpha = true;
60050
+ }
60051
+ let gamma;
60052
+ function handleGamma(_gamma_) {
60053
+ gamma = _gamma_;
60054
+ }
60055
+ let inflateDataList = [];
60056
+ function handleInflateData(inflatedData2) {
60057
+ inflateDataList.push(inflatedData2);
60058
+ }
60059
+ let reader = new SyncReader(buffer);
60060
+ let parser2 = new Parser(options3, {
60061
+ read: reader.read.bind(reader),
60062
+ error: handleError,
60063
+ metadata: handleMetaData,
60064
+ gamma: handleGamma,
60065
+ palette: handlePalette,
60066
+ transColor: handleTransColor,
60067
+ inflateData: handleInflateData,
60068
+ simpleTransparency: handleSimpleTransparency
60069
+ });
60070
+ parser2.start();
60071
+ reader.process();
60072
+ if (err) {
60073
+ throw err;
60074
+ }
60075
+ let inflateData = Buffer.concat(inflateDataList);
60076
+ inflateDataList.length = 0;
60077
+ let inflatedData;
60078
+ if (metaData.interlace) {
60079
+ inflatedData = zlib.inflateSync(inflateData);
60080
+ } else {
60081
+ let rowSize = (metaData.width * metaData.bpp * metaData.depth + 7 >> 3) + 1;
60082
+ let imageSize = rowSize * metaData.height;
60083
+ inflatedData = inflateSync(inflateData, {
60084
+ chunkSize: imageSize,
60085
+ maxLength: imageSize
60086
+ });
60087
+ }
60088
+ inflateData = null;
60089
+ if (!inflatedData || !inflatedData.length) {
60090
+ throw new Error("bad png - invalid inflate data response");
60091
+ }
60092
+ let unfilteredData = FilterSync.process(inflatedData, metaData);
60093
+ inflateData = null;
60094
+ let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
60095
+ unfilteredData = null;
60096
+ let normalisedBitmapData = formatNormaliser(
60097
+ bitmapData,
60098
+ metaData,
60099
+ options3.skipRescale
60100
+ );
60101
+ metaData.data = normalisedBitmapData;
60102
+ metaData.gamma = gamma || 0;
60103
+ return metaData;
60104
+ };
60105
+ }
60106
+ });
60107
+
60108
+ // node_modules/pngjs/lib/packer-sync.js
60109
+ var require_packer_sync = __commonJS({
60110
+ "node_modules/pngjs/lib/packer-sync.js"(exports, module) {
60111
+ "use strict";
60112
+ var hasSyncZlib = true;
60113
+ var zlib = __require("zlib");
60114
+ if (!zlib.deflateSync) {
60115
+ hasSyncZlib = false;
60116
+ }
60117
+ var constants = require_constants2();
60118
+ var Packer = require_packer();
60119
+ module.exports = function(metaData, opt) {
60120
+ if (!hasSyncZlib) {
60121
+ throw new Error(
60122
+ "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
60123
+ );
60124
+ }
60125
+ let options3 = opt || {};
60126
+ let packer = new Packer(options3);
60127
+ let chunks = [];
60128
+ chunks.push(Buffer.from(constants.PNG_SIGNATURE));
60129
+ chunks.push(packer.packIHDR(metaData.width, metaData.height));
60130
+ if (metaData.gamma) {
60131
+ chunks.push(packer.packGAMA(metaData.gamma));
60132
+ }
60133
+ let filteredData = packer.filterData(
60134
+ metaData.data,
60135
+ metaData.width,
60136
+ metaData.height
60137
+ );
60138
+ let compressedData = zlib.deflateSync(
60139
+ filteredData,
60140
+ packer.getDeflateOptions()
60141
+ );
60142
+ filteredData = null;
60143
+ if (!compressedData || !compressedData.length) {
60144
+ throw new Error("bad png - invalid compressed data response");
60145
+ }
60146
+ chunks.push(packer.packIDAT(compressedData));
60147
+ chunks.push(packer.packIEND());
60148
+ return Buffer.concat(chunks);
60149
+ };
60150
+ }
60151
+ });
60152
+
60153
+ // node_modules/pngjs/lib/png-sync.js
60154
+ var require_png_sync = __commonJS({
60155
+ "node_modules/pngjs/lib/png-sync.js"(exports) {
60156
+ "use strict";
60157
+ var parse4 = require_parser_sync();
60158
+ var pack = require_packer_sync();
60159
+ exports.read = function(buffer, options3) {
60160
+ return parse4(buffer, options3 || {});
60161
+ };
60162
+ exports.write = function(png, options3) {
60163
+ return pack(png, options3);
60164
+ };
60165
+ }
60166
+ });
60167
+
60168
+ // node_modules/pngjs/lib/png.js
60169
+ var require_png = __commonJS({
60170
+ "node_modules/pngjs/lib/png.js"(exports) {
60171
+ "use strict";
60172
+ var util2 = __require("util");
60173
+ var Stream = __require("stream");
60174
+ var Parser = require_parser_async();
60175
+ var Packer = require_packer_async();
60176
+ var PNGSync = require_png_sync();
60177
+ var PNG2 = exports.PNG = function(options3) {
60178
+ Stream.call(this);
60179
+ options3 = options3 || {};
60180
+ this.width = options3.width | 0;
60181
+ this.height = options3.height | 0;
60182
+ this.data = this.width > 0 && this.height > 0 ? Buffer.alloc(4 * this.width * this.height) : null;
60183
+ if (options3.fill && this.data) {
60184
+ this.data.fill(0);
60185
+ }
60186
+ this.gamma = 0;
60187
+ this.readable = this.writable = true;
60188
+ this._parser = new Parser(options3);
60189
+ this._parser.on("error", this.emit.bind(this, "error"));
60190
+ this._parser.on("close", this._handleClose.bind(this));
60191
+ this._parser.on("metadata", this._metadata.bind(this));
60192
+ this._parser.on("gamma", this._gamma.bind(this));
60193
+ this._parser.on(
60194
+ "parsed",
60195
+ function(data) {
60196
+ this.data = data;
60197
+ this.emit("parsed", data);
60198
+ }.bind(this)
60199
+ );
60200
+ this._packer = new Packer(options3);
60201
+ this._packer.on("data", this.emit.bind(this, "data"));
60202
+ this._packer.on("end", this.emit.bind(this, "end"));
60203
+ this._parser.on("close", this._handleClose.bind(this));
60204
+ this._packer.on("error", this.emit.bind(this, "error"));
60205
+ };
60206
+ util2.inherits(PNG2, Stream);
60207
+ PNG2.sync = PNGSync;
60208
+ PNG2.prototype.pack = function() {
60209
+ if (!this.data || !this.data.length) {
60210
+ this.emit("error", "No data provided");
60211
+ return this;
60212
+ }
60213
+ process.nextTick(
60214
+ function() {
60215
+ this._packer.pack(this.data, this.width, this.height, this.gamma);
60216
+ }.bind(this)
60217
+ );
60218
+ return this;
60219
+ };
60220
+ PNG2.prototype.parse = function(data, callback) {
60221
+ if (callback) {
60222
+ let onParsed, onError;
60223
+ onParsed = function(parsedData) {
60224
+ this.removeListener("error", onError);
60225
+ this.data = parsedData;
60226
+ callback(null, this);
60227
+ }.bind(this);
60228
+ onError = function(err) {
60229
+ this.removeListener("parsed", onParsed);
60230
+ callback(err, null);
60231
+ }.bind(this);
60232
+ this.once("parsed", onParsed);
60233
+ this.once("error", onError);
60234
+ }
60235
+ this.end(data);
60236
+ return this;
60237
+ };
60238
+ PNG2.prototype.write = function(data) {
60239
+ this._parser.write(data);
60240
+ return true;
60241
+ };
60242
+ PNG2.prototype.end = function(data) {
60243
+ this._parser.end(data);
60244
+ };
60245
+ PNG2.prototype._metadata = function(metadata) {
60246
+ this.width = metadata.width;
60247
+ this.height = metadata.height;
60248
+ this.emit("metadata", metadata);
60249
+ };
60250
+ PNG2.prototype._gamma = function(gamma) {
60251
+ this.gamma = gamma;
60252
+ };
60253
+ PNG2.prototype._handleClose = function() {
60254
+ if (!this._parser.writable && !this._packer.readable) {
60255
+ this.emit("close");
60256
+ }
60257
+ };
60258
+ PNG2.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) {
60259
+ srcX |= 0;
60260
+ srcY |= 0;
60261
+ width |= 0;
60262
+ height |= 0;
60263
+ deltaX |= 0;
60264
+ deltaY |= 0;
60265
+ if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
60266
+ throw new Error("bitblt reading outside image");
60267
+ }
60268
+ if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
60269
+ throw new Error("bitblt writing outside image");
60270
+ }
60271
+ for (let y = 0; y < height; y++) {
60272
+ src.data.copy(
60273
+ dst.data,
60274
+ (deltaY + y) * dst.width + deltaX << 2,
60275
+ (srcY + y) * src.width + srcX << 2,
60276
+ (srcY + y) * src.width + srcX + width << 2
60277
+ );
60278
+ }
60279
+ };
60280
+ PNG2.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) {
60281
+ PNG2.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
60282
+ return this;
60283
+ };
60284
+ PNG2.adjustGamma = function(src) {
60285
+ if (src.gamma) {
60286
+ for (let y = 0; y < src.height; y++) {
60287
+ for (let x = 0; x < src.width; x++) {
60288
+ let idx = src.width * y + x << 2;
60289
+ for (let i = 0; i < 3; i++) {
60290
+ let sample = src.data[idx + i] / 255;
60291
+ sample = Math.pow(sample, 1 / 2.2 / src.gamma);
60292
+ src.data[idx + i] = Math.round(sample * 255);
60293
+ }
60294
+ }
60295
+ }
60296
+ src.gamma = 0;
60297
+ }
60298
+ };
60299
+ PNG2.prototype.adjustGamma = function() {
60300
+ PNG2.adjustGamma(this);
60301
+ };
60302
+ }
60303
+ });
60304
+
60305
+ // src/maker/preview/validationScreenshot.ts
60306
+ function laterScreenshotFrame(assessment) {
60307
+ const next = Math.max(
60308
+ assessment.frame + 180,
60309
+ assessment.frame * 2,
60310
+ (assessment.bootstrap_completed_frame ?? 0) + 180
60311
+ );
60312
+ return Number.isSafeInteger(next) && next <= 2147483567 ? next : void 0;
60313
+ }
60314
+ var import_pngjs, PNG, ValidationScreenshot;
60315
+ var init_validationScreenshot = __esm({
60316
+ "src/maker/preview/validationScreenshot.ts"() {
60317
+ "use strict";
60318
+ import_pngjs = __toESM(require_png());
60319
+ PNG = import_pngjs.default.PNG;
60320
+ ValidationScreenshot = class {
60321
+ constructor(frame) {
60322
+ this.frame = frame;
60323
+ this.bootstrap = "unobserved";
60324
+ }
60325
+ observe(line) {
60326
+ const log = /^(?:\[[0-9 _:-]+\]\[(\d+)\] )?INFO: (.*)$/.exec(line);
60327
+ if (!log) return;
60328
+ const message = log[2];
60329
+ if (/^BootstrapPipeline: starting\b/.test(message)) {
60330
+ this.bootstrap = "incomplete";
60331
+ this.completedFrame = void 0;
60332
+ } else if (message === "BootstrapPipeline: completed successfully") {
60333
+ this.bootstrap = "complete";
60334
+ this.completedFrame = log[1] === void 0 ? void 0 : Number(log[1]);
60335
+ }
60336
+ const capture = /^\[Screenshot\] (?:captured|requested) at frame (\d+)\b/.exec(message);
60337
+ if (capture && Number(capture[1]) === this.frame) {
60338
+ this.atCapture ??= this.bootstrap;
60339
+ this.capturedFrame = Number(capture[1]);
60340
+ }
60341
+ }
60342
+ assess(bytes) {
60343
+ const width = bytes.readUInt32BE(16);
60344
+ const height = bytes.readUInt32BE(20);
60345
+ if (width > 4096 || height > 4096)
60346
+ throw new Error("Screenshot dimensions exceed the supported 4096x4096 limit.");
60347
+ const image = PNG.sync.read(bytes);
60348
+ if (image.width !== width || image.height !== height || image.data.length !== width * height * 4)
60349
+ throw new Error("Screenshot pixel data is incomplete.");
60350
+ let blank = 0;
60351
+ for (let i = 0; i < image.data.length; i += 4) {
60352
+ if (image.data[i + 3] <= 3 || image.data[i] <= 3 && image.data[i + 1] <= 3 && image.data[i + 2] <= 3)
60353
+ blank++;
60354
+ }
60355
+ const ratio = blank / (width * height);
60356
+ const bootstrapAtCapture = this.completedFrame !== void 0 && this.completedFrame !== this.frame ? this.completedFrame < this.frame ? "complete" : "incomplete" : this.atCapture ?? (this.bootstrap === "incomplete" ? "incomplete" : "unobserved");
60357
+ const reasons = [
60358
+ ...bootstrapAtCapture === "incomplete" ? ["bootstrap_incomplete"] : [],
60359
+ ...ratio >= 0.999 ? ["near_total_black_or_transparent"] : []
60360
+ ];
60361
+ return {
60362
+ status: reasons.length ? "NOT_READY" : "REVIEW_REQUIRED",
60363
+ reasons,
60364
+ frame: this.frame,
60365
+ captured_frame: this.capturedFrame,
60366
+ bootstrap_at_capture: bootstrapAtCapture,
60367
+ bootstrap_completed_frame: this.completedFrame,
60368
+ black_or_transparent_ratio: ratio,
60369
+ effective_visual_evidence: reasons.length ? false : void 0,
60370
+ width,
60371
+ height
60372
+ };
60373
+ }
60374
+ };
60375
+ }
60376
+ });
60377
+
58188
60378
  // src/maker/preview/validation.ts
58189
60379
  import fs38 from "node:fs";
58190
60380
  import path39 from "node:path";
@@ -58230,69 +60420,137 @@ function readArtifact(filename2, max) {
58230
60420
  throw new Error("Missing, empty or invalid artifact: " + filename2);
58231
60421
  return fs38.readFileSync(filename2);
58232
60422
  }
60423
+ function screenshotRetryTimeout(options3, nextFrame, runtimeMs, explicitTimeout = options3.validate_timeout !== void 0) {
60424
+ const frame = Number(options3.screenshot_frame);
60425
+ const frames = Number(options3.validate_frames ?? frame + 80);
60426
+ const ratio = options3.mode === "both" ? Math.max(frames, nextFrame + 80) / frames : nextFrame / frame;
60427
+ const timeout = Number(options3.validate_timeout ?? 100);
60428
+ const budget = !explicitTimeout ? Math.min(580, Math.ceil(timeout * ratio)) : timeout;
60429
+ return Number.isFinite(runtimeMs) && runtimeMs * ratio < budget * 1e3 ? budget : void 0;
60430
+ }
58233
60431
  async function runSkillValidation(project, options3, signal) {
58234
- const run = await createValidationRun(project);
58235
- const paths = {
58236
- run_id: run.run_id,
58237
- evidence_directory: run.directory,
58238
- log_path: path39.join(run.directory, "runtime.log"),
58239
- invocation_path: path39.join(run.directory, "invocation.json"),
58240
- started_at: run.started_at
58241
- };
58242
- process.stderr.write(JSON.stringify({ event: "validation.started", ...paths }) + "\n");
58243
- let output2;
58244
- try {
58245
- writePrivateJson(paths.invocation_path, {
58246
- requested_options: sanitizeDiagnosticValue(options3)
58247
- });
58248
- if (options3.output_dir !== void 0 && (typeof options3.output_dir !== "string" || !path39.isAbsolute(options3.output_dir)))
58249
- throw new Error("--output-dir must be an absolute directory.");
58250
- output2 = await executeSkillValidation(project, options3, signal, run);
58251
- } catch (error2) {
60432
+ const attemptRunIds = [];
60433
+ let attemptOptions = options3;
60434
+ for (let attempt = 0; ; attempt++) {
60435
+ const run = await createValidationRun(project);
60436
+ attemptRunIds.push(run.run_id);
60437
+ const paths = {
60438
+ run_id: run.run_id,
60439
+ evidence_directory: run.directory,
60440
+ log_path: path39.join(run.directory, "runtime.log"),
60441
+ invocation_path: path39.join(run.directory, "invocation.json"),
60442
+ started_at: run.started_at
60443
+ };
60444
+ process.stderr.write(JSON.stringify({ event: "validation.started", ...paths }) + "\n");
60445
+ let output2;
60446
+ try {
60447
+ writePrivateJson(paths.invocation_path, {
60448
+ requested_options: sanitizeDiagnosticValue(attemptOptions)
60449
+ });
60450
+ if (options3.output_dir !== void 0 && (typeof options3.output_dir !== "string" || !path39.isAbsolute(options3.output_dir)))
60451
+ throw new Error("--output-dir must be an absolute directory.");
60452
+ output2 = await executeSkillValidation(project, attemptOptions, signal, run);
60453
+ } catch (error2) {
60454
+ output2 = {
60455
+ ok: false,
60456
+ result: signal.aborted ? "CANCELLED" : "FAIL",
60457
+ error: sanitizeDiagnosticValue(error2 instanceof Error ? error2.message : String(error2))
60458
+ };
60459
+ try {
60460
+ new PreviewLogs(run.directory).append(String(output2.error));
60461
+ } catch (logError) {
60462
+ output2.error = String(output2.error) + "\nValidation error log could not be saved: " + String(sanitizeDiagnosticValue(String(logError)));
60463
+ }
60464
+ }
60465
+ const {
60466
+ _screenshot_retry_eligible: retryEligible,
60467
+ _runtime_duration_ms: runtimeMs,
60468
+ ...collected
60469
+ } = output2;
60470
+ const assessment = output2.screenshot_assessment;
60471
+ const nextFrame = assessment && laterScreenshotFrame(assessment);
60472
+ let retry = retryEligible === true && attempt < 2 && nextFrame !== void 0;
60473
+ const retryTimeout = retry ? screenshotRetryTimeout(
60474
+ attemptOptions,
60475
+ nextFrame,
60476
+ Number(runtimeMs),
60477
+ options3.validate_timeout !== void 0
60478
+ ) : void 0;
60479
+ const budgetExceeded = retry && retryTimeout === void 0;
60480
+ if (budgetExceeded) retry = false;
58252
60481
  output2 = {
58253
- ok: false,
58254
- result: signal.aborted ? "CANCELLED" : "FAIL",
58255
- error: sanitizeDiagnosticValue(error2 instanceof Error ? error2.message : String(error2))
60482
+ ...collected,
60483
+ ...paths,
60484
+ project_realpath: project,
60485
+ finished_at: (/* @__PURE__ */ new Date()).toISOString(),
60486
+ ...options3.mode === "screenshot" || options3.mode === "both" ? {
60487
+ attempt_run_ids: [...attemptRunIds],
60488
+ next_step: "AI must inspect every PNG for arbitrary in-game loading and gameplay; automatic checks only detect near-total black/transparent pixels and known bootstrap ordering." + ((assessment == null ? void 0 : assessment.status) === "NOT_READY" ? " This screenshot is not effective visual evidence. " + (retry ? `Waiting 3 seconds before a new Runtime launch at screenshot frame ${nextFrame}.` : budgetExceeded ? "Automatic retry skipped: the estimated later-frame runtime exceeds the timeout budget. Inspect retained evidence and explicitly choose a suitable --validate-timeout before retrying." : "Automatic retries are exhausted or unsafe. Inspect all attempt logs and the raw game report; choose a later frame or a controlled entry after resolving the cause.") : "")
60489
+ } : {}
58256
60490
  };
58257
- try {
58258
- new PreviewLogs(run.directory).append(String(output2.error));
58259
- } catch (logError) {
58260
- output2.error = String(output2.error) + "\nValidation error log could not be saved: " + String(sanitizeDiagnosticValue(String(logError)));
60491
+ finishValidationRun(run, output2);
60492
+ if (retry) {
60493
+ await new Promise((resolve) => {
60494
+ const done = () => {
60495
+ clearTimeout(timer);
60496
+ signal.removeEventListener("abort", done);
60497
+ resolve();
60498
+ };
60499
+ const timer = setTimeout(done, 3e3);
60500
+ signal.addEventListener("abort", done, { once: true });
60501
+ if (signal.aborted) done();
60502
+ });
60503
+ if (signal.aborted) {
60504
+ retry = false;
60505
+ output2.ok = false;
60506
+ output2.result = "CANCELLED";
60507
+ output2.error = [
60508
+ output2.error,
60509
+ "Cancelled during screenshot retry delay; no new Runtime was launched."
60510
+ ].filter(Boolean).join("\n");
60511
+ output2.next_step = "Screenshot retry cancelled. Retained PNGs require AI inspection and are not effective visual evidence.";
60512
+ }
58261
60513
  }
58262
- }
58263
- output2 = {
58264
- ...output2,
58265
- ...paths,
58266
- project_realpath: project,
58267
- finished_at: (/* @__PURE__ */ new Date()).toISOString()
58268
- };
58269
- finishValidationRun(run, output2);
58270
- try {
58271
- output2.warnings = [
58272
- ...Array.isArray(output2.warnings) ? output2.warnings : [],
58273
- ...await cleanValidationHistory(project)
58274
- ];
58275
- } catch (error2) {
58276
- output2.warnings = [
58277
- ...Array.isArray(output2.warnings) ? output2.warnings : [],
58278
- "Validation history cleanup skipped: " + String(sanitizeDiagnosticValue(String(error2)))
58279
- ];
58280
- }
58281
- finishValidationRun(run, output2);
58282
- if (typeof options3.output_dir === "string") {
58283
60514
  try {
58284
- output2.archive_directory = await archiveValidationRun(run, options3.output_dir);
60515
+ output2.warnings = [
60516
+ ...Array.isArray(output2.warnings) ? output2.warnings : [],
60517
+ ...await cleanValidationHistory(project)
60518
+ ];
58285
60519
  } catch (error2) {
58286
- output2.ok = false;
58287
- output2.result = "FAIL";
58288
- output2.error = [
58289
- output2.error,
58290
- "Evidence archive failed: " + String(sanitizeDiagnosticValue(String(error2)))
58291
- ].filter(Boolean).join("\n");
60520
+ output2.warnings = [
60521
+ ...Array.isArray(output2.warnings) ? output2.warnings : [],
60522
+ "Validation history cleanup skipped: " + String(sanitizeDiagnosticValue(String(error2)))
60523
+ ];
58292
60524
  }
58293
60525
  finishValidationRun(run, output2);
60526
+ if (typeof options3.output_dir === "string") {
60527
+ try {
60528
+ output2.archive_directory = await archiveValidationRun(run, options3.output_dir);
60529
+ } catch (error2) {
60530
+ output2.ok = false;
60531
+ output2.result = "FAIL";
60532
+ retry = false;
60533
+ output2.error = [
60534
+ output2.error,
60535
+ "Evidence archive failed: " + String(sanitizeDiagnosticValue(String(error2)))
60536
+ ].filter(Boolean).join("\n");
60537
+ if (options3.mode === "screenshot" || options3.mode === "both")
60538
+ output2.next_step = "Evidence archive failed; no screenshot retry was launched. Inspect the retained local PNGs and resolve the archive error before retrying.";
60539
+ }
60540
+ finishValidationRun(run, output2);
60541
+ }
60542
+ if (!retry) return output2;
60543
+ attemptOptions = {
60544
+ ...options3,
60545
+ screenshot_frame: String(nextFrame),
60546
+ validate_timeout: String(retryTimeout),
60547
+ ...options3.mode === "both" ? {
60548
+ validate_frames: String(
60549
+ Math.max(Number(options3.validate_frames ?? 0), nextFrame + 80)
60550
+ )
60551
+ } : {}
60552
+ };
58294
60553
  }
58295
- return output2;
58296
60554
  }
58297
60555
  async function executeSkillValidation(project, options3, signal, run) {
58298
60556
  return withPreviewLock(project, async () => {
@@ -58362,9 +60620,13 @@ async function executeSkillValidation(project, options3, signal, run) {
58362
60620
  };
58363
60621
  const directory = run.directory;
58364
60622
  const logs = new PreviewLogs(directory);
60623
+ const screenshot = capture ? new ValidationScreenshot(frame) : void 0;
58365
60624
  const failures = [];
58366
60625
  let logWriteFailed = false;
60626
+ let runtimeErrorObserved = false;
58367
60627
  const appendLog = (line) => {
60628
+ if (/\b(?:ERROR|FATAL|CRITICAL|PANIC):|stack traceback:/.test(line))
60629
+ runtimeErrorObserved = true;
58368
60630
  try {
58369
60631
  logs.append(line);
58370
60632
  } catch (error2) {
@@ -58381,12 +60643,14 @@ async function executeSkillValidation(project, options3, signal, run) {
58381
60643
  const artifacts = [];
58382
60644
  const warnings = repairLocalValidationSkillFilter(project);
58383
60645
  let report;
60646
+ let screenshotAssessment;
58384
60647
  let preparation;
58385
60648
  let assets;
58386
60649
  let cache;
58387
60650
  let exitCode = null;
58388
60651
  let exitSignal = null;
58389
60652
  let timedOut = false;
60653
+ let runtimeDurationMs;
58390
60654
  const started = run.started_at;
58391
60655
  const invocationPath = path39.join(directory, "invocation.json");
58392
60656
  try {
@@ -58432,6 +60696,7 @@ async function executeSkillValidation(project, options3, signal, run) {
58432
60696
  cwd: source
58433
60697
  });
58434
60698
  updateValidationRun(run, { phase: "starting", runtime_launch_pending: true });
60699
+ const runtimeStarted = performance.now();
58435
60700
  const child = spawn9(executable, args, {
58436
60701
  cwd: source,
58437
60702
  shell: false,
@@ -58441,6 +60706,7 @@ async function executeSkillValidation(project, options3, signal, run) {
58441
60706
  env: process.platform === "win32" ? selectWindowsBackgroundEnvironment(process.env) : process.env
58442
60707
  });
58443
60708
  const append = (line) => {
60709
+ screenshot == null ? void 0 : screenshot.observe(line);
58444
60710
  lua.observe(line);
58445
60711
  appendLog(assets ? line.split(assets.url).join("[local-preview]/") : line);
58446
60712
  };
@@ -58485,6 +60751,7 @@ async function executeSkillValidation(project, options3, signal, run) {
58485
60751
  }
58486
60752
  if (signal.aborted) stop();
58487
60753
  });
60754
+ runtimeDurationMs = performance.now() - runtimeStarted;
58488
60755
  } catch (error2) {
58489
60756
  failures.push(
58490
60757
  String(sanitizeDiagnosticValue(error2 instanceof Error ? error2.message : error2))
@@ -58526,12 +60793,15 @@ async function executeSkillValidation(project, options3, signal, run) {
58526
60793
  const png = readArtifact(pngPath, 128 * 1024 * 1024);
58527
60794
  if (!isCompleteValidationPng(png))
58528
60795
  throw new Error("Runtime did not produce a complete PNG.");
60796
+ const assessed = screenshot.assess(png);
60797
+ screenshotAssessment = assessed;
58529
60798
  artifacts.push({
58530
60799
  kind: "screenshot",
58531
60800
  path: pngPath,
58532
60801
  frame,
58533
- width: png.readUInt32BE(16),
58534
- height: png.readUInt32BE(20)
60802
+ width: assessed.width,
60803
+ height: assessed.height,
60804
+ effective_visual_evidence: assessed.effective_visual_evidence
58535
60805
  });
58536
60806
  } catch (error2) {
58537
60807
  failures.push(
@@ -58543,7 +60813,17 @@ async function executeSkillValidation(project, options3, signal, run) {
58543
60813
  if (fs38.existsSync(prepareLog)) artifacts.push({ kind: "prepare-log", path: prepareLog });
58544
60814
  if (exitCode !== 0 && !(exitCode === 1 && (report == null ? void 0 : report.result) === "FAIL"))
58545
60815
  failures.push("Runtime did not complete normally; inspect its logs and original report.");
58546
- const result = signal.aborted ? "CANCELLED" : timedOut || (report == null ? void 0 : report.result) === "TIMEOUT" ? "TIMEOUT" : failures.length ? "FAIL" : "COMPLETED";
60816
+ const collectionResult = signal.aborted ? "CANCELLED" : timedOut || (report == null ? void 0 : report.result) === "TIMEOUT" ? "TIMEOUT" : failures.length ? "FAIL" : "COMPLETED";
60817
+ const visuallyNotReady = (screenshotAssessment == null ? void 0 : screenshotAssessment.status) === "NOT_READY";
60818
+ const retryEligible = collectionResult === "COMPLETED" && visuallyNotReady && // A complete report is authoritative; do not reclassify its raw startup/game logs.
60819
+ (report ? report.result === "PASS" && ["lua_errors", "resource_errors", "engine_errors", "total_errors"].every(
60820
+ (key) => report.summary[key] === 0
60821
+ ) && report.missing_resources.length === 0 && report.test_result !== "FAILED" : !runtimeErrorObserved);
60822
+ if (visuallyNotReady)
60823
+ failures.push(
60824
+ "Screenshot is not effective visual evidence: " + screenshotAssessment.reasons.join(", ") + ". Inspect the retained PNG and logs; the raw game report is unchanged."
60825
+ );
60826
+ const result = collectionResult === "COMPLETED" && visuallyNotReady ? "FAIL" : collectionResult;
58547
60827
  const output2 = {
58548
60828
  ...identity,
58549
60829
  protocol_version: 1,
@@ -58552,6 +60832,9 @@ async function executeSkillValidation(project, options3, signal, run) {
58552
60832
  mode,
58553
60833
  game_review_required: true,
58554
60834
  visual_check_required: capture,
60835
+ screenshot_assessment: screenshotAssessment,
60836
+ _screenshot_retry_eligible: retryEligible,
60837
+ _runtime_duration_ms: runtimeDurationMs,
58555
60838
  report,
58556
60839
  artifacts,
58557
60840
  preparation,
@@ -58584,6 +60867,7 @@ var init_validation = __esm({
58584
60867
  init_backgroundProcess();
58585
60868
  init_diagnosticRedaction();
58586
60869
  init_devKit();
60870
+ init_validationScreenshot();
58587
60871
  init_validationHistory();
58588
60872
  }
58589
60873
  });
@@ -63509,7 +65793,7 @@ var consoleIconLicense, consoleIcons;
63509
65793
  var init_webIcons = __esm({
63510
65794
  "src/maker/console/webIcons.ts"() {
63511
65795
  "use strict";
63512
- consoleIconLicense = `Lucide icon-node snapshot: lucide-vue-next v1.0.0; copy/link: lucide v0.468.0
65796
+ consoleIconLicense = `Lucide icon-node snapshot: lucide-vue-next v1.0.0; copy/link/severity: lucide v0.468.0
63513
65797
  ISC License
63514
65798
  Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2026 as part
63515
65799
  of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2026.
@@ -63542,6 +65826,21 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
63542
65826
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
63543
65827
  SOFTWARE.`;
63544
65828
  consoleIcons = {
65829
+ info: [
65830
+ ["circle", { cx: "12", cy: "12", r: "10" }],
65831
+ ["path", { d: "M12 16v-4" }],
65832
+ ["path", { d: "M12 8h.01" }]
65833
+ ],
65834
+ warning: [
65835
+ ["path", { d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" }],
65836
+ ["path", { d: "M12 9v4" }],
65837
+ ["path", { d: "M12 17h.01" }]
65838
+ ],
65839
+ error: [
65840
+ ["circle", { cx: "12", cy: "12", r: "10" }],
65841
+ ["line", { x1: "12", x2: "12", y1: "8", y2: "12" }],
65842
+ ["line", { x1: "12", x2: "12.01", y1: "16", y2: "16" }]
65843
+ ],
63545
65844
  copy: [
63546
65845
  ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }],
63547
65846
  ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }]
@@ -63949,21 +66248,58 @@ const settledTaskPending = new Map();
63949
66248
  const logViews = new Map();
63950
66249
  const validationViews = new Map();
63951
66250
  let validationTimer;
66251
+ const validationImages = [];
66252
+ let validationImageLoading = null;
66253
+ const validationImageObserver = typeof IntersectionObserver === 'function' ?
66254
+ new IntersectionObserver(entries => {
66255
+ entries.forEach(entry => {
66256
+ if (!entry.isIntersecting) return;
66257
+ validationImageObserver.unobserve(entry.target);
66258
+ if (entry.target.dataset.discarded || entry.target.src || entry.target.dataset.queued) return;
66259
+ entry.target.dataset.queued = 'true';
66260
+ validationImages.push(entry.target);
66261
+ });
66262
+ loadValidationImages();
66263
+ },{rootMargin:'300px'}) : null;
66264
+ function loadValidationImages() {
66265
+ if (validationImageLoading || !validationActive()) return;
66266
+ while (validationImages.length) {
66267
+ const image = validationImages.shift();
66268
+ delete image.dataset.queued;
66269
+ if (image.dataset.discarded) continue;
66270
+ if (!image.isConnected || image.dataset.project !== selected) {
66271
+ validationImageObserver?.observe(image);
66272
+ continue;
66273
+ }
66274
+ validationImageLoading = image;
66275
+ image.loading = 'eager';
66276
+ image.src = image.dataset.source;
66277
+ return;
66278
+ }
66279
+ }
66280
+ function finishValidationImage(image) {
66281
+ if (validationImageLoading === image) validationImageLoading = null;
66282
+ loadValidationImages();
66283
+ }
63952
66284
  const validationRunId = value => typeof value === 'string' &&
63953
66285
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
63954
66286
  function validationView() {
63955
66287
  if (!validationViews.has(selected)) validationViews.set(selected,{
63956
- runs:[],selectedRun:'',entries:new Map(),nextCursor:'',paged:false,
66288
+ runs:[],entries:new Map(),nextCursor:'',paged:false,scrollTop:0,
63957
66289
  initialized:false,listRequest:0,request:0,loading:false,detailLoading:false,warnings:[],error:''
63958
66290
  });
63959
66291
  return validationViews.get(selected);
63960
66292
  }
63961
- function validationEntry(view = validationView()) {
63962
- if (!view.selectedRun) return null;
63963
- if (!view.entries.has(view.selectedRun)) view.entries.set(view.selectedRun,{
66293
+ function validationEntry(id, view = validationView()) {
66294
+ if (!validationRunId(id)) return null;
66295
+ if (!view.entries.has(id)) view.entries.set(id,{
63964
66296
  cursor:0,runtime:'',prepare:'',json:'',truncated:false,errors:[],clearedPrepare:'',clearedJson:''
63965
66297
  });
63966
- return view.entries.get(view.selectedRun);
66298
+ return view.entries.get(id);
66299
+ }
66300
+ function validationChronology(view = validationView()) {
66301
+ return [...view.runs].sort((a,b) => String(b.started_at).localeCompare(String(a.started_at)) ||
66302
+ b.run_id.localeCompare(a.run_id));
63967
66303
  }
63968
66304
  function validationActive() {
63969
66305
  return !disposed && !offline && !document.hidden && page === 'build' &&
@@ -63974,11 +66310,12 @@ function syncValidationPolling() {
63974
66310
  clearTimeout(validationTimer); validationTimer = undefined;
63975
66311
  return;
63976
66312
  }
66313
+ loadValidationImages();
63977
66314
  if (validationTimer !== undefined) return;
63978
- validationTimer = setTimeout(async () => {
66315
+ validationTimer = setTimeout(() => {
63979
66316
  validationTimer = undefined;
63980
66317
  if (!validationActive()) return;
63981
- await refreshValidation();
66318
+ void refreshValidation();
63982
66319
  syncValidationPolling();
63983
66320
  },5000);
63984
66321
  }
@@ -63992,17 +66329,25 @@ function validationStatus(run) {
63992
66329
  }
63993
66330
  function validationVisibleText(entry) {
63994
66331
  if (!entry) return '';
63995
- const prepare = entry.clearedPrepare && entry.prepare.startsWith(entry.clearedPrepare)
63996
- ? entry.prepare.slice(entry.clearedPrepare.length) : entry.prepare;
66332
+ const logs = validationLogContent(entry);
66333
+ const prepare = filteredLogText(logs.prepare), runtime = filteredLogText(logs.runtime);
63997
66334
  const json = entry.json === entry.clearedJson ? '' : entry.json;
63998
66335
  return [
63999
66336
  entry.truncated ? '日志已截断,仅显示有界片段。' : '',
64000
66337
  ...entry.errors,
64001
66338
  prepare ? '准备日志\n' + prepare : '',
64002
- entry.runtime ? 'Runtime / Lua 日志\n' + entry.runtime : '',
66339
+ runtime ? 'Runtime / Lua 日志\n' + runtime : '',
64003
66340
  json ? 'JSON\n' + json : ''
64004
66341
  ].filter(Boolean).join('\n\n');
64005
66342
  }
66343
+ function validationLogContent(entry) {
66344
+ if (!entry) return {prepare:'',runtime:''};
66345
+ return {
66346
+ prepare:entry.clearedPrepare && entry.prepare.startsWith(entry.clearedPrepare)
66347
+ ? entry.prepare.slice(entry.clearedPrepare.length) : entry.prepare,
66348
+ runtime:entry.runtime
66349
+ };
66350
+ }
64006
66351
  async function refreshValidation(options = {}) {
64007
66352
  if (!validationActive()) return;
64008
66353
  const key = selected, epoch = selectionEpoch, viewEpochAtStart = viewEpoch;
@@ -64022,15 +66367,16 @@ async function refreshValidation(options = {}) {
64022
66367
  const incoming = result.runs.filter(run => validationRunId(run.run_id));
64023
66368
  const merged = new Map((options.more ? [...view.runs,...incoming] : [...incoming,...view.runs])
64024
66369
  .map(run => [run.run_id,run]));
64025
- // Refresh current summaries without changing history order or the user's selection.
66370
+ // Keep older loaded pages while refreshing the newest summaries.
64026
66371
  incoming.forEach(run => merged.set(run.run_id,run));
64027
66372
  view.runs = Array.from(merged.values());
64028
66373
  if (options.more || !view.paged) view.nextCursor = validationRunId(result.next_cursor) ? result.next_cursor : '';
64029
66374
  if (options.more) view.paged = true;
64030
66375
  view.warnings = Array.isArray(result.warnings) ? result.warnings : [];
64031
66376
  view.initialized = true;
64032
- if (!view.selectedRun && view.runs.length) view.selectedRun = view.runs[0].run_id;
64033
- if (view.selectedRun) await loadValidationEvidence();
66377
+ // Summary pagination is independent of the bounded evidence reader.
66378
+ view.loading = false;
66379
+ await loadValidationEvidence();
64034
66380
  } catch (error) {
64035
66381
  if (matches()) {
64036
66382
  view.error = error.message;
@@ -64044,20 +66390,41 @@ async function refreshValidation(options = {}) {
64044
66390
  async function loadValidationEvidence() {
64045
66391
  if (!validationActive()) return;
64046
66392
  const key = selected, epoch = selectionEpoch, viewAtStart = viewEpoch;
64047
- const view = validationView(), id = view.selectedRun, entry = validationEntry(view);
64048
- if (!entry || !validationRunId(id)) return;
66393
+ const view = validationView();
64049
66394
  if (view.detailLoading && view.detailEpoch === epoch) return;
64050
66395
  const request = ++view.request;
64051
66396
  const matches = () => selectionMatches(key,epoch) && viewEpoch === viewAtStart &&
64052
- validationActive() && view.selectedRun === id && view.request === request;
64053
- const base = projectPath(key,'/validation/' + encodeURIComponent(id));
66397
+ validationActive() && view.request === request;
66398
+ const visited = new Set();
66399
+ const needsEvidence = run => {
66400
+ const entry = validationEntry(run.run_id,view);
66401
+ return !visited.has(run.run_id) && (run.status === 'running' || entry.errors.length || entry.pendingLogs ||
66402
+ entry.signature !== JSON.stringify(run));
66403
+ };
64054
66404
  view.detailLoading = true; view.detailEpoch = epoch;
64055
66405
  renderConsoleLogs();
64056
66406
  try {
64057
- const results = await Promise.allSettled([
64058
- api(base), api(base + '/prepare'), api(base + '/logs?cursor=' + entry.cursor)
64059
- ]);
66407
+ // Two evidence reads leave slots for a thumbnail and independent summary pagination.
66408
+ while (matches()) {
66409
+ const run = validationChronology(view).find(needsEvidence);
66410
+ if (!run) break;
66411
+ visited.add(run.run_id);
66412
+ await loadValidationRound(key,view,run,matches);
66413
+ if (matches()) renderConsoleLogs();
66414
+ }
66415
+ } finally {
66416
+ if (request === view.request) view.detailLoading = false;
66417
+ if (matches()) renderConsoleLogs();
66418
+ }
66419
+ }
66420
+ async function loadValidationRound(key,view,run,matches) {
66421
+ const id = run.run_id, entry = validationEntry(id,view);
66422
+ const base = projectPath(key,'/validation/' + encodeURIComponent(id));
66423
+ const results = await Promise.allSettled([api(base), api(base + '/prepare')]);
66424
+ if (!matches()) return;
66425
+ results.push(...await Promise.allSettled([api(base + '/logs?cursor=' + entry.cursor)]));
64060
66426
  if (!matches()) return;
66427
+ entry.revision = (entry.revision || 0) + 1;
64061
66428
  entry.errors = [];
64062
66429
  const [detail,prepare,logs] = results;
64063
66430
  results.forEach((result,index) => {
@@ -64091,42 +66458,47 @@ async function loadValidationEvidence() {
64091
66458
  entry.runtime = bounded.text;
64092
66459
  entry.truncated ||= bounded.truncated || Boolean(data.truncated);
64093
66460
  entry.cursor = data.next_cursor;
66461
+ entry.pendingLogs = Boolean(data.truncated) && added.length > 0;
64094
66462
  } else entry.errors.push('Runtime / Lua 日志游标无效');
64095
66463
  }
64096
- } finally {
64097
- if (request === view.request) view.detailLoading = false;
64098
- if (matches()) renderConsoleLogs();
64099
- }
64100
- }
64101
- async function chooseValidationRun(id) {
64102
- const view = validationView();
64103
- if (!view.runs.some(run => run.run_id === id)) return;
64104
- view.request++; view.detailLoading = false;
64105
- view.selectedRun = id;
64106
- renderConsoleLogs();
64107
- await loadValidationEvidence();
66464
+ if (!entry.errors.length) entry.signature = JSON.stringify(view.runs.find(run => run.run_id === id));
64108
66465
  }
64109
66466
  function clearValidationDisplay() {
64110
- const view = validationView(), entry = validationEntry(view);
66467
+ const view = validationView();
64111
66468
  view.listRequest++; view.loading = false;
64112
66469
  view.request++; view.detailLoading = false;
64113
- if (!entry) return;
64114
- entry.runtime = ''; entry.clearedPrepare = entry.prepare; entry.clearedJson = entry.json;
64115
- entry.imageCleared = Boolean(entry.data?.artifacts?.some(artifact =>
64116
- artifact.kind === 'screenshot' && artifact.id === 'screenshot.png'));
64117
- entry.truncated = false; entry.errors = []; entry.image = null; entry.imageError = false;
66470
+ view.entries.forEach(entry => {
66471
+ entry.revision = (entry.revision || 0) + 1;
66472
+ entry.runtime = ''; entry.clearedPrepare = entry.prepare; entry.clearedJson = entry.json;
66473
+ entry.imageCleared = Boolean(entry.data?.artifacts?.some(artifact =>
66474
+ artifact.kind === 'screenshot' && artifact.id === 'screenshot.png'));
66475
+ if (entry.image) {
66476
+ entry.image.dataset.discarded = 'true';
66477
+ validationImageObserver?.unobserve(entry.image);
66478
+ }
66479
+ entry.truncated = false; entry.errors = []; entry.image = null; entry.imageError = false;
66480
+ });
66481
+ for (let i = validationImages.length - 1; i >= 0; i--) {
66482
+ if (!validationImages[i].dataset.discarded) continue;
66483
+ delete validationImages[i].dataset.queued;
66484
+ validationImages.splice(i,1);
66485
+ }
64118
66486
  }
64119
- function validationSection(entry, id, title, open) {
66487
+ function validationSection(entry, runId, id, title) {
64120
66488
  entry.sections ||= new Map();
64121
66489
  if (!entry.sections.has(id)) {
64122
- const section = node('details',undefined,'task validation-evidence');
64123
- section.dataset.key = selected + ':' + validationView().selectedRun + ':' + id;
66490
+ const section = node(id === 'screenshot' ? 'section' : 'details',undefined,'validation-evidence');
66491
+ section.dataset.key = selected + ':' + runId + ':' + id;
64124
66492
  section.dataset.evidence = id;
64125
- section.open = open;
64126
- section.append(node('summary',title));
66493
+ if (id !== 'screenshot') section.open = false;
66494
+ const heading = node(id === 'screenshot' ? 'h3' : 'summary');
66495
+ heading.append(node('span',title,'validation-evidence-title'));
66496
+ const preview = node('span',undefined,'validation-preview');
66497
+ if (id !== 'screenshot') heading.append(preview);
66498
+ section.append(heading);
64127
66499
  const body = node('div',undefined,'validation-evidence-body');
64128
66500
  section.append(body);
64129
- entry.sections.set(id,{section,body});
66501
+ entry.sections.set(id,{section,body,preview});
64130
66502
  }
64131
66503
  return entry.sections.get(id);
64132
66504
  }
@@ -64135,9 +66507,12 @@ function renderValidationEvidence(entry, run) {
64135
66507
  if (!entry) return feed;
64136
66508
  if (entry.truncated) feed.append(node('p','日志已截断,仅显示有界片段。','pending'));
64137
66509
  entry.errors.forEach(error => feed.append(node('p',error,'bad')));
64138
- const log = (id,title,value,open) => {
66510
+ const log = (id,title,value) => {
64139
66511
  if (!value) return;
64140
- const block = validationSection(entry,id,title,open);
66512
+ const visible = id === 'json' ? value : filteredLogText(value);
66513
+ const display = visible || '当前筛选无匹配日志';
66514
+ const block = validationSection(entry,run.run_id,id,title);
66515
+ block.preview.textContent = display.trimEnd().split('\n').slice(-3).join('\n');
64141
66516
  if (!block.output) {
64142
66517
  block.output = node('pre');
64143
66518
  block.output.addEventListener('scroll',() => {
@@ -64146,40 +66521,44 @@ function renderValidationEvidence(entry, run) {
64146
66521
  });
64147
66522
  block.body.append(block.output);
64148
66523
  }
64149
- if (block.value !== value) {
66524
+ if (block.value !== display) {
64150
66525
  const top = block.output.scrollTop, left = block.output.scrollLeft;
64151
- block.output.replaceChildren(renderLogLines(value));
66526
+ block.output.replaceChildren(renderLogLines(display));
64152
66527
  block.output.scrollTop = top; block.output.scrollLeft = left;
64153
- block.value = value;
66528
+ block.value = display;
64154
66529
  }
64155
66530
  block.output.className = 'validation-log' + (logView().wrap ? ' wrap' : '');
64156
66531
  feed.append(block.section);
64157
66532
  };
64158
- const prepare = entry.clearedPrepare && entry.prepare.startsWith(entry.clearedPrepare)
64159
- ? entry.prepare.slice(entry.clearedPrepare.length) : entry.prepare;
64160
- log('prepare','准备日志',prepare,false);
64161
- log('runtime','Runtime / Lua 日志',entry.runtime,false);
64162
- const screenshot = validationSection(entry,'screenshot','截图',true);
66533
+ const {prepare} = validationLogContent(entry);
66534
+ log('prepare','准备日志',prepare);
66535
+ log('runtime','Runtime / Lua 日志',entry.runtime);
66536
+ const screenshot = validationSection(entry,run.run_id,'screenshot','截图');
64163
66537
  const data = entry.data;
64164
66538
  const available = data?.run.status !== 'running' &&
64165
66539
  data?.artifacts?.some(artifact => artifact.kind === 'screenshot' && artifact.id === 'screenshot.png');
64166
66540
  const key = selected, id = run.run_id;
64167
- const visible = () => selected === key && validationView().selectedRun === id && validationActive();
66541
+ const visible = () => selected === key && validationActive();
64168
66542
  if (available && !entry.image && !entry.imageError && !entry.imageCleared) {
64169
66543
  const image = node('img');
64170
66544
  image.alt = 'Validate 截图'; image.className = 'validation-screenshot'; image.loading = 'lazy';
66545
+ image.dataset.project = key;
66546
+ image.dataset.source = projectPath(key,'/validation/' + encodeURIComponent(id) + '/screenshot.png');
66547
+ image.addEventListener('load',() => finishValidationImage(image));
64171
66548
  image.addEventListener('error',() => {
66549
+ finishValidationImage(image);
64172
66550
  if (entry.image !== image) return;
64173
66551
  entry.image = null; entry.imageError = true;
64174
66552
  if (visible()) renderConsoleLogs();
64175
66553
  });
64176
- image.src = projectPath(key,'/validation/' + encodeURIComponent(id) + '/screenshot.png');
64177
66554
  entry.image = image;
66555
+ if (validationImageObserver) validationImageObserver.observe(image);
66556
+ else image.src = image.dataset.source;
64178
66557
  }
64179
66558
  const content = [];
64180
66559
  if (available && entry.image) {
64181
66560
  const link = node('a');
64182
- link.href = entry.image.src; link.target = '_blank'; link.rel = 'noopener noreferrer';
66561
+ link.href = entry.image.dataset.source; link.target = '_blank'; link.rel = 'noopener noreferrer';
64183
66562
  link.setAttribute('aria-label','查看截图原图'); link.append(entry.image);
64184
66563
  content.push(link);
64185
66564
  } else {
@@ -64197,49 +66576,67 @@ function renderValidationEvidence(entry, run) {
64197
66576
  }
64198
66577
  screenshot.body.replaceChildren(...content);
64199
66578
  feed.append(screenshot.section);
64200
- log('json','调用参数与原始 JSON',entry.json === entry.clearedJson ? '' : entry.json,false);
66579
+ log('json','调用参数与原始 JSON',entry.json === entry.clearedJson ? '' : entry.json);
64201
66580
  return feed;
64202
66581
  }
64203
66582
  function renderValidationPanel() {
64204
- const view = validationView(), entry = validationEntry(view);
66583
+ const view = validationView();
64205
66584
  const panel = node('div',undefined,'validation-panel');
66585
+ panel.dataset.project = selected;
64206
66586
  const history = node('div',undefined,'validation-history');
64207
- const label = node('label','调用历史');
64208
- const picker = node('select');
64209
- picker.setAttribute('aria-label','Validate 调用历史'); picker.dataset.focus = 'validation-run';
64210
- if (!view.runs.length) {
64211
- const option = node('option',view.loading ? '读取中…' : '暂无 Validate 调用'); option.value = ''; picker.append(option);
64212
- }
64213
- view.runs.forEach(run => {
64214
- const option = node('option',run.started_at + ' · ' + validationStatus(run) + ' · ' + run.run_id);
64215
- option.value = run.run_id; picker.append(option);
64216
- });
64217
- picker.value = view.selectedRun; picker.disabled = !view.runs.length;
64218
- picker.addEventListener('change',event => void chooseValidationRun(event.target.value));
64219
- label.append(picker); history.append(label);
64220
- if (view.nextCursor) history.append(button('加载更多',
64221
- () => void refreshValidation({more:true}),{disabled:view.loading,loading:view.loading}));
66587
+ history.append(node('span',view.runs.length ? view.runs.length + ' 轮 Validate' :
66588
+ view.loading ? '读取中…' : '暂无 Validate 调用','muted'));
64222
66589
  panel.append(history);
64223
66590
  if (view.error) panel.append(node('p',view.error,'bad'));
64224
- const warnings = [view.warnings,entry?.data?.warnings,entry?.data?.result?.warnings]
64225
- .flatMap(items => Array.isArray(items) ? items : []);
64226
- if (warnings.length) panel.append(node('p',boundedValidationText(warnings.join('\n')).text,'pending'));
64227
- const run = view.runs.find(run => run.run_id === view.selectedRun) || entry?.data?.run;
64228
- if (!run) return panel;
64229
- const status = node('div',undefined,'validation-status');
64230
- status.append(node('span','采集状态:' + validationStatus(run),run.status === 'incomplete' ? 'pending' : 'muted'),
64231
- node('span','阶段:' + text(run.phase)),
64232
- node('span','游戏结果:' + text(run.game_result,'未提供')));
64233
- panel.append(status);
64234
- if (run.result) panel.append(node('p','采集结果:' + run.result,'muted'));
64235
- if (run.finished_at) panel.append(node('p','结束时间:' + run.finished_at,'muted'));
64236
- panel.append(renderValidationEvidence(entry,run));
66591
+ if (view.warnings.length) panel.append(node('p',boundedValidationText(view.warnings.join('\n')).text,'pending'));
66592
+ const runs = validationChronology(view);
66593
+ panel.dataset.firstRun = runs[0]?.run_id || '';
66594
+ runs.forEach(run => {
66595
+ const entry = validationEntry(run.run_id,view);
66596
+ const renderKey = JSON.stringify([run,entry.revision,entry.imageError,entry.imageCleared,
66597
+ logView().wrap,logFilters()]);
66598
+ if (entry.round && entry.renderKey === renderKey) {
66599
+ panel.append(entry.round);
66600
+ return;
66601
+ }
66602
+ const round = node('article',undefined,'validation-round');
66603
+ round.dataset.validationRun = run.run_id;
66604
+ const time = node('time',new Date(run.started_at).toLocaleString(),'validation-time');
66605
+ time.dateTime = run.started_at; time.title = run.run_id;
66606
+ round.append(time);
66607
+ const status = node('div',undefined,'validation-status');
66608
+ status.append(node('span','采集状态:' + validationStatus(run),run.status === 'incomplete' ? 'pending' : 'muted'),
66609
+ node('span','阶段:' + text(run.phase)),
66610
+ node('span','游戏结果:' + text(run.game_result,'未提供')));
66611
+ round.append(status);
66612
+ if (run.result) round.append(node('span','采集结果:' + run.result,'muted'));
66613
+ const warnings = [entry.data?.warnings,entry.data?.result?.warnings]
66614
+ .flatMap(items => Array.isArray(items) ? items : []);
66615
+ if (warnings.length) round.append(node('p',boundedValidationText(warnings.join('\n')).text,'pending'));
66616
+ round.append(renderValidationEvidence(entry,run));
66617
+ entry.round = round; entry.renderKey = renderKey;
66618
+ panel.append(round);
66619
+ });
66620
+ if (view.nextCursor) panel.append(button('加载更早记录',
66621
+ () => void refreshValidation({more:true}),{disabled:view.loading,loading:view.loading}));
66622
+ const key = selected;
66623
+ panel.addEventListener('scroll',() => {
66624
+ if (selected !== key || !panel.isConnected) return;
66625
+ view.scrollTop = panel.scrollTop;
66626
+ if (panel.scrollHeight - panel.scrollTop - panel.clientHeight < 80 &&
66627
+ view.nextCursor && !view.loading)
66628
+ void refreshValidation({more:true});
66629
+ });
64237
66630
  return panel;
64238
66631
  }
64239
66632
  function logView() {
64240
- if (!logViews.has(selected)) logViews.set(selected,{tab:'build',runtime:'',loading:false,wrap:false,cleared:{}});
66633
+ if (!logViews.has(selected)) logViews.set(selected,{tab:'build',runtime:'',loading:false,wrap:false,cleared:{},filters:{}});
64241
66634
  return logViews.get(selected);
64242
66635
  }
66636
+ function logFilters() {
66637
+ const view = logView();
66638
+ return view.filters[view.tab] ||= {info:true,warning:true,error:true};
66639
+ }
64243
66640
  function selectLog(tab) {
64244
66641
  logView().tab = tab;
64245
66642
  renderConsoleLogs();
@@ -64249,7 +66646,7 @@ function selectLog(tab) {
64249
66646
  }
64250
66647
  function consoleLogSnapshot() {
64251
66648
  const view = logView();
64252
- if (view.tab === 'runtime') return {id:view.runtimeId || 'runtime',output:view.runtime,details:''};
66649
+ if (view.tab === 'runtime') return {id:view.runtimeId || 'runtime',output:view.runtime,details:'',notice:view.runtimeNotice || ''};
64253
66650
  const task = tasksFor(selected).find(t => t.action === (view.tab === 'lua' ? 'lua-lsp.check' : view.tab === 'qrcode' ? 'qrcode' : 'build'));
64254
66651
  if (!task) return {id:'',output:'',details:''};
64255
66652
  const result = nestedResult(task);
@@ -64264,31 +66661,107 @@ function clearConsoleLogs() {
64264
66661
  view.cleared[view.tab] = consoleLogSnapshot();
64265
66662
  renderConsoleLogs();
64266
66663
  }
64267
- function consoleLogText() {
64268
- if (logView().tab === 'validate') return validationVisibleText(validationEntry()) ||
64269
- (validationView().selectedRun ? '暂无显示内容' : '暂无 Validate 调用');
66664
+ function consoleLogContent() {
64270
66665
  const view = logView(), snapshot = consoleLogSnapshot(), cleared = view.cleared[view.tab];
64271
- if (view.tab === 'runtime' && view.loading) return '正在读取运行时日志…';
64272
66666
  let {output,details} = snapshot;
64273
66667
  if (cleared && cleared.id === snapshot.id) {
64274
66668
  if (output.startsWith(cleared.output)) output = output.slice(cleared.output.length);
64275
66669
  if (details === cleared.details) details = '';
64276
- return [output,details].filter(Boolean).join('\n\n') || '日志已清理';
64277
66670
  }
64278
- return [output,details].filter(Boolean).join('\n\n') ||
64279
- (view.tab === 'runtime' ? '点击刷新读取运行时日志' : snapshot.id ? '等待任务输出' : '暂无日志');
66671
+ return [output,details].filter(Boolean).join('\n\n');
66672
+ }
66673
+ function consoleLogText() {
66674
+ const view = logView();
66675
+ if (view.tab === 'validate') return validationChronology().map(run => {
66676
+ const output = validationVisibleText(validationEntry(run.run_id));
66677
+ return output ? run.started_at + ' · ' + run.run_id + '\n' + output : '';
66678
+ }).filter(Boolean).join('\n\n') || (validationView().runs.length ? '暂无显示内容' : '暂无 Validate 调用');
66679
+ if (view.tab === 'runtime' && view.loading) return '正在读取运行时日志…';
66680
+ const snapshot = consoleLogSnapshot(), cleared = view.cleared[view.tab];
66681
+ const notice = cleared?.id === snapshot.id && cleared.notice === snapshot.notice ? '' : snapshot.notice;
66682
+ const content = consoleLogContent();
66683
+ if (content) return [notice,filteredLogText(content) || '当前筛选无匹配日志'].filter(Boolean).join('\n');
66684
+ if (notice) return notice;
66685
+ if (view.cleared[view.tab]?.id === snapshot.id) return '日志已清理';
66686
+ return view.tab === 'runtime' ? '点击刷新读取运行时日志' : snapshot.id ? '等待任务输出' : '暂无日志';
66687
+ }
66688
+ function explicitLogLevel(line) {
66689
+ const level = value => {
66690
+ if (typeof value !== 'string') return null;
66691
+ if (/^(?:error|fatal|critical|panic)$/i.test(value)) return 'error';
66692
+ if (/^warn(?:ing)?$/i.test(value)) return 'warning';
66693
+ if (/^(?:info|debug|trace|notice|log)$/i.test(value)) return 'info';
66694
+ return null;
66695
+ };
66696
+ const prefix = /^\s*(?:\[(?!(?:ERROR|FATAL|CRITICAL|PANIC|WARN|WARNING|INFO|DEBUG|TRACE|NOTICE|LOG)\])[^\]\r\n]+\]\s*)*/i;
66697
+ const message = line.replace(prefix,'');
66698
+ if (message.startsWith('{')) {
66699
+ try {
66700
+ const entry = JSON.parse(message);
66701
+ const structured = level(entry?.l ?? entry?.level ?? entry?.severity);
66702
+ if (structured) return structured;
66703
+ } catch (_) {}
66704
+ }
66705
+ const marker = /^(?:\[(ERROR|FATAL|CRITICAL|PANIC|WARN|WARNING|INFO|DEBUG|TRACE|NOTICE|LOG)\]|(ERROR|FATAL|CRITICAL|PANIC|WARN|WARNING|INFO|DEBUG|TRACE|NOTICE|LOG)(?=\s|:|\||$))/i.exec(message);
66706
+ return level(marker?.[1] || marker?.[2]);
66707
+ }
66708
+ function logLineSeverity(line) {
66709
+ const explicit = explicitLogLevel(line);
66710
+ if (explicit) return explicit;
66711
+ if (/\b(?:error|fatal)\b|失败|错误|异常/i.test(line)) return 'error';
66712
+ if (/\bwarn(?:ing)?\b|警告|注意/i.test(line)) return 'warning';
66713
+ return 'info';
64280
66714
  }
64281
66715
  function logLineClass(line) {
64282
- if (/(?:^|\b)(?:error|fatal|失败|错误|异常)(?:\b|$)/i.test(line)) return 'log-line log-error';
64283
- if (/(?:^|\b)(?:warn(?:ing)?|警告|注意)(?:\b|$)/i.test(line)) return 'log-line log-warning';
64284
- return 'log-line';
66716
+ const severity = logLineSeverity(line);
66717
+ return 'log-line' + (severity === 'info' ? '' : ' log-' + severity);
66718
+ }
66719
+ function logRows(output) {
66720
+ if (!output) return [];
66721
+ let previous = 'info';
66722
+ return String(output).split('\n').map(text => {
66723
+ // Keep traceback continuations with their preceding severity when filtering.
66724
+ const severity = explicitLogLevel(text) ||
66725
+ (/^\s*$|^\s+|^stack traceback:|^at \S/.test(text) ? previous : logLineSeverity(text));
66726
+ previous = severity;
66727
+ return {text,severity};
66728
+ });
66729
+ }
66730
+ function filteredLogText(output) {
66731
+ const filters = logFilters();
66732
+ const rows = logRows(output).filter(row => filters[row.severity]);
66733
+ return rows.some(row => row.text.trim()) ? rows.map(row => row.text).join('\n') : '';
66734
+ }
66735
+ function renderLogFilters() {
66736
+ const group = node('div',undefined,'console-log-filters');
66737
+ group.setAttribute('role','group'); group.setAttribute('aria-label','日志类型筛选');
66738
+ const filters = logFilters(), counts = {info:0,warning:0,error:0};
66739
+ const content = logView().tab === 'validate' ? validationView().runs.flatMap(run =>
66740
+ Object.values(validationLogContent(validationEntry(run.run_id)))) :
66741
+ [consoleLogContent()];
66742
+ content.forEach(output => logRows(output).forEach(row => {
66743
+ if (row.text.trim()) counts[row.severity]++;
66744
+ }));
66745
+ [['info','普通'],['warning','警告'],['error','错误']].forEach(([level,label]) => {
66746
+ const control = button(label,() => {
66747
+ filters[level] = !filters[level]; renderConsoleLogs();
66748
+ },{icon:level,className:'log-filter log-filter-' + level,focus:'log-filter-' + level});
66749
+ control.dataset.level = level;
66750
+ control.setAttribute('aria-label',label + '日志');
66751
+ control.setAttribute('aria-pressed',String(filters[level]));
66752
+ control.setAttribute('aria-controls','console-log-output');
66753
+ control.title = (filters[level] ? '隐藏' : '显示') + label + '日志(' + counts[level] + ' 行)';
66754
+ control.append(node('span',String(counts[level]),'log-count'));
66755
+ group.append(control);
66756
+ });
66757
+ return group;
64285
66758
  }
64286
66759
  function renderLogLines(output) {
64287
66760
  const fragment = document.createDocumentFragment();
64288
- const lines = String(output || '').split('\n');
64289
- lines.forEach((line,index) => {
64290
- fragment.append(node('span',line,logLineClass(line)));
64291
- if (index < lines.length - 1) fragment.append(document.createTextNode('\n'));
66761
+ const rows = logRows(output);
66762
+ rows.forEach((row,index) => {
66763
+ fragment.append(node('span',row.text,'log-line' + (row.severity === 'info' ? '' : ' log-' + row.severity)));
66764
+ if (index < rows.length - 1) fragment.append(document.createTextNode('\n'));
64292
66765
  });
64293
66766
  return fragment;
64294
66767
  }
@@ -64296,6 +66769,15 @@ function renderConsoleLogs() {
64296
66769
  const host = $('console-logs');
64297
66770
  if (!host) return;
64298
66771
  const view = logView();
66772
+ const previous = $('console-log-output');
66773
+ const sameProject = previous?.dataset.project === selected;
66774
+ const top = previous?.scrollTop || 0, left = previous?.scrollLeft || 0;
66775
+ // Keep the visible round stable even when earlier evidence is filled over several redraws.
66776
+ const anchor = sameProject && top > 0 &&
66777
+ Array.from(previous.querySelectorAll('[data-validation-run]'))
66778
+ .find(round => round.getBoundingClientRect().bottom > previous.getBoundingClientRect().top);
66779
+ const anchorOffset = anchor ?
66780
+ anchor.getBoundingClientRect().top - previous.getBoundingClientRect().top : 0;
64299
66781
  const toolbar = node('div',undefined,'console-log-toolbar');
64300
66782
  const tabs = node('div',undefined,'console-log-tabs');
64301
66783
  tabs.setAttribute('role','tablist');
@@ -64317,14 +66799,22 @@ function renderConsoleLogs() {
64317
66799
  node('pre',undefined,'console-log-output' + (view.wrap ? ' wrap' : ''));
64318
66800
  if (view.tab !== 'validate') output.append(renderLogLines(consoleLogText()));
64319
66801
  output.id = 'console-log-output'; output.setAttribute('role','tabpanel'); output.tabIndex = 0;
64320
- const previous = $('console-log-output');
64321
- const top = previous?.scrollTop || 0, left = previous?.scrollLeft || 0;
64322
- replace(host,[toolbar,tabs,output]);
64323
- output.scrollTop = top; output.scrollLeft = left;
64324
- if (view.tab === 'validate') validationEntry()?.sections?.forEach(block => {
64325
- if (!block.output?.isConnected || !block.section.open) return;
64326
- block.output.scrollTop = block.scrollTop || 0; block.output.scrollLeft = block.scrollLeft || 0;
64327
- });
66802
+ replace(host,[toolbar,tabs,renderLogFilters(),output]);
66803
+ if (view.tab === 'validate') {
66804
+ output.scrollTop = sameProject ? top : validationView().scrollTop;
66805
+ if (anchor) {
66806
+ const restored = Array.from(output.querySelectorAll('[data-validation-run]'))
66807
+ .find(round => round.dataset.validationRun === anchor.dataset.validationRun);
66808
+ if (restored)
66809
+ output.scrollTop += restored.getBoundingClientRect().top -
66810
+ output.getBoundingClientRect().top - anchorOffset;
66811
+ }
66812
+ validationView().entries.forEach(entry => entry.sections?.forEach(block => {
66813
+ if (!block.output?.isConnected || !block.section.open) return;
66814
+ block.output.scrollTop = block.scrollTop || 0; block.output.scrollLeft = block.scrollLeft || 0;
66815
+ }));
66816
+ } else output.scrollTop = top;
66817
+ output.scrollLeft = left;
64328
66818
  syncValidationPolling();
64329
66819
  }
64330
66820
  let git = null;
@@ -64505,6 +66995,7 @@ function dispose() {
64505
66995
  disposed = true;
64506
66996
  clearTimeout(pollTimer);
64507
66997
  clearTimeout(validationTimer); validationTimer = undefined;
66998
+ validationImageObserver?.disconnect(); validationImages.length = 0;
64508
66999
  clearInterval(activityTimer);
64509
67000
  activityTimer = undefined;
64510
67001
  requests.forEach(controller => controller.abort());
@@ -65565,9 +68056,11 @@ async function loadLogs() {
65565
68056
  try {
65566
68057
  const logs = await api(projectPath(key,'/preview/logs'));
65567
68058
  entry.runtimeId = String(logs.session_id || '') + ':' + String(logs.reload_id || 0);
65568
- entry.runtime = (logs.truncated ? '仅显示最近日志,完整分页记录可通过 preview logs 读取。\n' : '') + (Array.isArray(logs.logs) ? logs.logs.map(row => text(row.text,'')).join('\n') : text(logs));
68059
+ entry.runtimeNotice = logs.truncated ? '仅显示最近日志,完整分页记录可通过 preview logs 读取。' : '';
68060
+ entry.runtime = Array.isArray(logs.logs) ? logs.logs.map(row => text(row.text,'')).join('\n') : text(logs);
65569
68061
  } catch (error) {
65570
- entry.runtime = '日志读取失败:' + error.message;
68062
+ entry.runtime = '';
68063
+ entry.runtimeNotice = '日志读取失败:' + error.message;
65571
68064
  } finally {
65572
68065
  entry.loading = false;
65573
68066
  if (selectionMatches(key,epoch) && view === viewEpoch) renderConsoleLogs();
@@ -66423,23 +68916,37 @@ pre{white-space:pre-wrap;tab-size:2;margin:10px 0 0;background:var(--code);paddi
66423
68916
  .console-log-tabs{display:flex;gap:22px;padding:0 16px;background:var(--top);border:1px solid var(--border);border-radius:4px 4px 0 0;overflow:auto}
66424
68917
  .console-log-tabs button{border:0;border-bottom:2px solid transparent;background:none;border-radius:0;font-size:12px;color:var(--muted);padding:10px 0;flex-shrink:0}
66425
68918
  .console-log-tabs [aria-selected="true"]{color:var(--accent);border-bottom-color:var(--accent)}
68919
+ .console-log-filters{display:flex;flex-wrap:wrap;gap:6px;padding:8px 12px;background:var(--top);border:1px solid var(--border);border-top:0}
68920
+ .console-log-filters .log-filter{display:inline-flex;align-items:center;gap:8px;min-height:32px;padding:4px 10px;font-size:12px;border-radius:3px;color:var(--muted);background:transparent}
68921
+ .console-log-filters .log-filter[aria-pressed="true"]{color:var(--text);background:var(--soft);border-color:var(--muted)}
68922
+ .console-log-filters .log-filter[aria-pressed="false"]{opacity:.6}
68923
+ .console-log-filters .log-filter-warning[aria-pressed="true"]{color:var(--yellow)}
68924
+ .console-log-filters .log-filter-error[aria-pressed="true"]{color:var(--red)}
68925
+ :root[data-theme="light"] .console-log-filters .log-filter-warning[aria-pressed="true"]{color:var(--accent)}
68926
+ .log-count{font-variant-numeric:tabular-nums;min-width:2ch;text-align:right}
66426
68927
  .console-logs .console-log-output{height:360px;max-height:60vh;width:100%;max-width:100%;overflow:auto;white-space:pre;overflow-wrap:normal;word-break:normal;margin:0;border-top:0;border-radius:0 0 4px 4px;line-height:1.9}
66427
68928
  .console-logs .console-log-output.wrap{white-space:pre-wrap;overflow-wrap:anywhere}
66428
68929
  .console-logs .log-line{color:var(--text)}
66429
68930
  .console-logs .log-error{color:var(--red)}
66430
68931
  .console-logs .log-warning{color:var(--yellow)}
66431
- .validation-panel{border:1px solid var(--border);border-top:0;padding:12px 16px;min-width:0}
68932
+ .validation-panel{border:1px solid var(--border);border-top:0;padding:12px 16px;min-width:0;height:640px;max-height:70vh;overflow:auto;overflow-anchor:none}
66432
68933
  .validation-history,.validation-status{display:flex;align-items:center;flex-wrap:wrap;gap:12px}
66433
- .validation-history label{display:flex;align-items:center;gap:10px;flex:1;min-width:0}
66434
- .validation-history select{min-width:0;max-width:100%;flex:1}
66435
- .validation-status{margin-top:12px;font-size:12px;overflow-wrap:anywhere}
68934
+ .validation-history{justify-content:space-between}
68935
+ .validation-round{padding:18px 0;border-bottom:1px solid var(--border);min-width:0}
68936
+ .validation-round:last-child{border-bottom:0}
68937
+ .validation-time{font-size:12px;font-variant-numeric:tabular-nums;color:var(--muted)}
68938
+ .validation-status{margin:6px 0;font-size:12px;overflow-wrap:anywhere}
66436
68939
  .validation-panel p{white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0}
66437
- .validation-feed{display:grid;gap:12px;margin-top:16px;min-width:0}
66438
- .validation-evidence{border:1px solid var(--border);border-radius:4px;background:var(--top);padding:6px 12px;max-width:100%}
68940
+ .validation-feed{display:grid;gap:8px;margin-top:10px;min-width:0}
68941
+ .validation-evidence{border:1px solid var(--border);border-radius:4px;background:var(--top);padding:8px 12px;min-width:0;max-width:100%}
68942
+ .validation-evidence summary{cursor:pointer}
68943
+ .validation-evidence h3,.validation-evidence-title{font-size:12px;font-weight:600;margin:0;line-height:1.8}
68944
+ .validation-preview{display:block;font:12px/1.65 "SFMono-Regular",Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin-top:5px;max-height:4.95em;overflow:hidden;color:var(--muted)}
68945
+ .validation-evidence[open] .validation-preview{display:none}
66439
68946
  .validation-evidence-body{min-width:0}
66440
- .validation-evidence-body .validation-log{margin:0 0 6px;max-height:280px;white-space:pre;overflow-wrap:normal;word-break:normal}
68947
+ .validation-evidence-body .validation-log{margin:8px 0 0;max-height:280px;white-space:pre;overflow-wrap:normal;word-break:normal}
66441
68948
  .validation-evidence-body .validation-log.wrap{white-space:pre-wrap;overflow-wrap:anywhere}
66442
- .validation-screenshot{display:block;width:auto;height:auto;max-width:100%;max-height:480px;object-fit:contain;margin:6px auto 12px}
68949
+ .validation-screenshot{display:block;width:auto;height:auto;max-width:min(240px,100%);max-height:150px;object-fit:contain;margin:8px 0 0;background:var(--code)}
66443
68950
  button.link.bad{color:var(--red)}button.link.good{color:var(--green)}button.link.pending{color:var(--accent)}
66444
68951
  .preview-status-summary{display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;min-height:32px;font-size:13px}
66445
68952
  .preview-status-summary button{margin-left:auto}
@@ -67151,7 +69658,7 @@ var init_cli = __esm({
67151
69658
  init_types3();
67152
69659
  init_owner();
67153
69660
  init_diagnosticRedaction();
67154
- VERSION3 = false ? "dev" : "0.0.37-beta.1";
69661
+ VERSION3 = false ? "dev" : "0.0.37-beta.2";
67155
69662
  CONSOLE_PROTOCOL_VERSION = 3;
67156
69663
  }
67157
69664
  });
@@ -73870,7 +76377,7 @@ var require_line_counter = __commonJS({
73870
76377
  });
73871
76378
 
73872
76379
  // node_modules/yaml/dist/parse/parser.js
73873
- var require_parser = __commonJS({
76380
+ var require_parser2 = __commonJS({
73874
76381
  "node_modules/yaml/dist/parse/parser.js"(exports) {
73875
76382
  "use strict";
73876
76383
  var node_process = __require("process");
@@ -74749,7 +77256,7 @@ var require_public_api = __commonJS({
74749
77256
  var log = require_log();
74750
77257
  var identity = require_identity();
74751
77258
  var lineCounter = require_line_counter();
74752
- var parser2 = require_parser();
77259
+ var parser2 = require_parser2();
74753
77260
  function parseOptions(options3) {
74754
77261
  const prettyErrors = options3.prettyErrors !== false;
74755
77262
  const lineCounter$1 = options3.lineCounter || prettyErrors && new lineCounter.LineCounter() || null;
@@ -74853,7 +77360,7 @@ var require_dist2 = __commonJS({
74853
77360
  var cst = require_cst();
74854
77361
  var lexer2 = require_lexer();
74855
77362
  var lineCounter = require_line_counter();
74856
- var parser2 = require_parser();
77363
+ var parser2 = require_parser2();
74857
77364
  var publicApi = require_public_api();
74858
77365
  var visit = require_visit();
74859
77366
  exports.Composer = composer.Composer;
@@ -78884,7 +81391,7 @@ function hasControlCharacter(value) {
78884
81391
  }
78885
81392
 
78886
81393
  // src/maker/cli/commands.ts
78887
- var VERSION4 = true ? "0.0.37-beta.1" : "dev";
81394
+ var VERSION4 = true ? "0.0.37-beta.2" : "dev";
78888
81395
  var DEFAULT_MCP_NAME = "taptap-maker";
78889
81396
  var MAKER_NPM_PACKAGE = "@taptap/maker";
78890
81397
  var TWO_PART_COMMANDS = /* @__PURE__ */ new Set([