@thedeck/mcp 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +1316 -14
  2. package/dist/index.js +178 -140
  3. package/package.json +38 -38
package/dist/cli.js CHANGED
@@ -4,13 +4,13 @@ import path from "node:path";
4
4
  import { z } from "zod";
5
5
  import { execFile, spawn } from "node:child_process";
6
6
  import crypto$1, { randomBytes } from "node:crypto";
7
- import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
7
+ import { cp, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { createServer } from "node:http";
9
9
  import os, { homedir, tmpdir } from "node:os";
10
10
  import { discoverAuthorizationServerMetadata, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, refreshAuthorization, registerClient, startAuthorization } from "@modelcontextprotocol/sdk/client/auth.js";
11
11
  import { pipeline } from "node:stream/promises";
12
12
  import { promisify } from "node:util";
13
- import fs from "node:fs";
13
+ import fs, { createWriteStream } from "node:fs";
14
14
  import stream from "node:stream";
15
15
  import process$1 from "node:process";
16
16
  import tty from "node:tty";
@@ -217,6 +217,8 @@ var postDraftOutput = z.object({
217
217
  quest_id: questId,
218
218
  review_url: z.url(),
219
219
  pay_url: z.url(),
220
+ reward_cents: z.number().int().nonnegative(),
221
+ deposit_cents: z.number().int().nonnegative().describe("What the pay link charges now: the held deposit, 30% of the reward. The rest is charged when the person accepts a submission."),
220
222
  missing: z.array(z.object({
221
223
  part: postPart,
222
224
  label: z.string()
@@ -226,8 +228,8 @@ var postDraftOutput = z.object({
226
228
  var addExampleCopyInput = z.object({
227
229
  quest_id: questId,
228
230
  pair: z.number().int().positive(),
229
- role: z.enum(["input", "expected"]),
230
- filename: z.string().trim().min(1).max(255),
231
+ role: z.enum(["input", "expected"]).describe("input: a file the program reads. An example’s input can be several files: send each with the same pair and role input. expected: the one answer file of that pair."),
232
+ filename: z.string().trim().min(1).max(255).describe("A file sent again under the same name, pair and role replaces the one sent before."),
231
233
  content: z.string(),
232
234
  blanked_summary: z.string().trim().min(1),
233
235
  shown_to_builders: z.boolean().optional().describe("True when the person chose to show this example to builders. Leave it out to keep it hidden for judging, like a hidden test."),
@@ -245,11 +247,15 @@ var isJson = (text) => {
245
247
  return false;
246
248
  }
247
249
  };
250
+ var exampleCopyRef = z.object({
251
+ pair: z.number().int().positive(),
252
+ role: z.enum(["input", "expected"])
253
+ }).describe("An example copy already sent with deck.add_example_copy, named by its pair and role, in place of inline text.");
248
254
  var proposedTest = z.object({
249
255
  name: z.string().trim().min(1),
250
256
  kind: z.enum(["sample", "hidden"]),
251
- input: z.string(),
252
- expected: z.string().describe("The expected output. For outcome fails_cleanly, a short note of why the input is bad; it is shown to the person, not compared."),
257
+ input: z.union([z.string(), exampleCopyRef]).describe("The input as text, or an example copy by its pair and role. For a large input, send the file once with deck.add_example_copy (hidden unless the person shows it) and name it here instead of writing it out. When that example’s input is several files, the program gets a folder holding them."),
258
+ expected: z.union([z.string(), exampleCopyRef]).describe("The expected output as text, or an example copy by its pair and role. For outcome fails_cleanly, a short note of why the input is bad; it is shown to the person, not compared."),
253
259
  category: z.string().trim().min(1).optional().describe("The part of the test plan this test covers: the confirmed scenario it checks, or an edge case such as empty input, malformed input, large input or boundary values. Builders see how many hidden tests failed in each category."),
254
260
  compare: z.enum(TEST_COMPARES).optional().describe("How the output is checked against expected. exact (the default): the same text, ignoring line endings and trailing space. unordered_lines: the same lines in any order, for rows whose order does not matter. numbers: every number within tolerance and the text around them the same. json: the same JSON value, whatever the key order and spacing."),
255
261
  tolerance: z.number().nonnegative().optional().describe(`Only with compare numbers: how far each number may be from the expected one. Default ${TEST_DEFAULTS.tolerance}.`),
@@ -258,7 +264,7 @@ var proposedTest = z.object({
258
264
  }).refine((t) => t.tolerance === void 0 || t.compare === "numbers", {
259
265
  path: ["tolerance"],
260
266
  error: "tolerance applies only with compare numbers"
261
- }).refine((t) => t.compare !== "json" || t.outcome === "fails_cleanly" || isJson(t.expected), {
267
+ }).refine((t) => t.compare !== "json" || t.outcome === "fails_cleanly" || typeof t.expected !== "string" || isJson(t.expected), {
262
268
  path: ["expected"],
263
269
  error: "with compare json, expected must be valid JSON"
264
270
  });
@@ -349,6 +355,7 @@ var precheckKitOutput = z.object({
349
355
  name: z.string(),
350
356
  input_file: z.string().min(1),
351
357
  input: z.base64(),
358
+ input_folder: z.boolean().optional().describe("true when input is a zip of several files, unpacked into a folder that is passed as {input}."),
352
359
  expected_file: z.string().min(1),
353
360
  expected: z.base64(),
354
361
  compare: z.enum(TEST_COMPARES).optional(),
@@ -370,7 +377,8 @@ var realDataReportInput = z.object({
370
377
  total: z.number().int().positive()
371
378
  });
372
379
  var reportedOutput = z.object({ reported: z.literal(true) });
373
- var reportIssueInput = z.object({
380
+ var reportFields = z.object({
381
+ kind: z.enum(["problem", "workflow_change"]).optional().describe("problem (the default): the person struggled or was held up. workflow_change: the person went through the steps their own way, which shows how people prefer to work with an agent."),
374
382
  side: z.enum(["poster", "builder"]),
375
383
  step: z.enum([
376
384
  "understanding_the_deck",
@@ -395,15 +403,21 @@ var reportIssueInput = z.object({
395
403
  "blocker",
396
404
  "annoying",
397
405
  "minor"
398
- ]),
406
+ ]).optional().describe("How much the problem held the person up. Needed for a problem; leave it out for a workflow change."),
399
407
  quest_id: questId.optional(),
400
408
  person_agreed: z.literal(true).describe("true only when you showed the person this exact text and they said yes to sending it.")
401
409
  });
410
+ var hasSeverity = (r) => r.kind === "workflow_change" || r.severity !== void 0;
411
+ var NEEDS_SEVERITY = {
412
+ path: ["severity"],
413
+ error: "a problem needs its severity: blocker, annoying or minor"
414
+ };
415
+ var reportIssueInput = reportFields.refine(hasSeverity, NEEDS_SEVERITY);
402
416
  var reportIssueOutput = z.object({
403
417
  report_id: z.uuid(),
404
418
  received_at: z.string()
405
419
  });
406
- var betaReportInput = reportIssueInput.extend({ agent_client: z.string().trim().min(1).max(200).nullable().optional() });
420
+ var betaReportInput = reportFields.extend({ agent_client: z.string().trim().min(1).max(200).nullable().optional() }).refine(hasSeverity, NEEDS_SEVERITY);
407
421
  var MCP_TOOLS = {
408
422
  "deck.post_draft": {
409
423
  input: postDraftInput,
@@ -470,10 +484,12 @@ var DECK_ERROR_CODES = [
470
484
  var isDeckErrorCode = (code) => DECK_ERROR_CODES.includes(code);
471
485
  var DeckError = class extends Error {
472
486
  code;
487
+ waitsOnPerson;
473
488
  constructor(code, message, options) {
474
489
  super(message ?? code, options);
475
490
  this.name = "DeckError";
476
491
  this.code = code;
492
+ this.waitsOnPerson = options?.waitsOnPerson === true;
477
493
  }
478
494
  };
479
495
  var toolCall = (name) => ({
@@ -843,7 +859,7 @@ async function stageInputs(tests) {
843
859
  const dir = await mkdtemp(path.join(tmpdir(), "deck-inputs-"));
844
860
  await Promise.all(tests.map(async (test, i) => {
845
861
  await mkdir(path.join(dir, String(i)));
846
- await copyFile(test.inputFile, path.join(dir, String(i), `input${path.extname(test.inputFile)}`));
862
+ await cp(test.inputFile, path.join(dir, String(i), `input${path.extname(test.inputFile)}`), { recursive: true });
847
863
  }));
848
864
  return dir;
849
865
  }
@@ -23002,6 +23018,1290 @@ async function scan(options) {
23002
23018
  summary
23003
23019
  };
23004
23020
  }
23021
+ // ../node_modules/.pnpm/pend@1.2.0/node_modules/pend/index.js
23022
+ var require_pend = /* @__PURE__ */ __commonJSMin(((exports, module) => {
23023
+ module.exports = Pend;
23024
+ function Pend() {
23025
+ this.pending = 0;
23026
+ this.max = Infinity;
23027
+ this.listeners = [];
23028
+ this.waiting = [];
23029
+ this.error = null;
23030
+ }
23031
+ Pend.prototype.go = function(fn) {
23032
+ if (this.pending < this.max) pendGo(this, fn);
23033
+ else this.waiting.push(fn);
23034
+ };
23035
+ Pend.prototype.wait = function(cb) {
23036
+ if (this.pending === 0) cb(this.error);
23037
+ else this.listeners.push(cb);
23038
+ };
23039
+ Pend.prototype.hold = function() {
23040
+ return pendHold(this);
23041
+ };
23042
+ function pendHold(self) {
23043
+ self.pending += 1;
23044
+ var called = false;
23045
+ return onCb;
23046
+ function onCb(err) {
23047
+ if (called) throw new Error("callback called twice");
23048
+ called = true;
23049
+ self.error = self.error || err;
23050
+ self.pending -= 1;
23051
+ if (self.waiting.length > 0 && self.pending < self.max) pendGo(self, self.waiting.shift());
23052
+ else if (self.pending === 0) {
23053
+ var listeners = self.listeners;
23054
+ self.listeners = [];
23055
+ listeners.forEach(cbListener);
23056
+ }
23057
+ }
23058
+ function cbListener(listener) {
23059
+ listener(self.error);
23060
+ }
23061
+ }
23062
+ function pendGo(self, fn) {
23063
+ fn(pendHold(self));
23064
+ }
23065
+ }));
23066
+ // ../node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/fd-slicer.js
23067
+ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
23068
+ var fs = __require("fs");
23069
+ var util = __require("util");
23070
+ var stream = __require("stream");
23071
+ var Readable = stream.Readable;
23072
+ var PassThrough = stream.PassThrough;
23073
+ var Pend = require_pend();
23074
+ var EventEmitter = __require("events").EventEmitter;
23075
+ exports.BufferSlicer = BufferSlicer;
23076
+ exports.FdSlicer = FdSlicer;
23077
+ util.inherits(FdSlicer, EventEmitter);
23078
+ function FdSlicer(fd) {
23079
+ EventEmitter.call(this);
23080
+ this.fd = fd;
23081
+ this.pend = new Pend();
23082
+ this.pend.max = 1;
23083
+ this.refCount = 0;
23084
+ }
23085
+ FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
23086
+ var self = this;
23087
+ self.pend.go(function(cb) {
23088
+ fs.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
23089
+ cb();
23090
+ callback(err, bytesRead, buffer);
23091
+ });
23092
+ });
23093
+ };
23094
+ FdSlicer.prototype.createReadStream = function(options) {
23095
+ return new ReadStream(this, options);
23096
+ };
23097
+ FdSlicer.prototype.ref = function() {
23098
+ this.refCount += 1;
23099
+ };
23100
+ FdSlicer.prototype.unref = function() {
23101
+ var self = this;
23102
+ self.refCount -= 1;
23103
+ if (self.refCount < 0) throw new Error("invalid unref");
23104
+ if (self.refCount > 0) return;
23105
+ fs.close(self.fd, onCloseDone);
23106
+ function onCloseDone(err) {
23107
+ if (err) self.emit("error", err);
23108
+ else self.emit("close");
23109
+ }
23110
+ };
23111
+ util.inherits(ReadStream, Readable);
23112
+ function ReadStream(context, options) {
23113
+ options = options || {};
23114
+ Readable.call(this, options);
23115
+ this.context = context;
23116
+ this.context.ref();
23117
+ this.start = options.start || 0;
23118
+ this.endOffset = options.end;
23119
+ this.pos = this.start;
23120
+ }
23121
+ ReadStream.prototype._read = function(n) {
23122
+ var self = this;
23123
+ var toRead = Math.min(self._readableState.highWaterMark, n);
23124
+ if (self.endOffset != null) toRead = Math.min(toRead, self.endOffset - self.pos);
23125
+ if (toRead <= 0) {
23126
+ self.push(null);
23127
+ this._cleanup();
23128
+ return;
23129
+ }
23130
+ self.context.pend.go(function(cb) {
23131
+ var buffer = Buffer.allocUnsafe(toRead);
23132
+ fs.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
23133
+ if (err) self.destroy(err);
23134
+ else if (bytesRead === 0) {
23135
+ self.push(null);
23136
+ self._cleanup();
23137
+ } else {
23138
+ self.pos += bytesRead;
23139
+ self.push(buffer.slice(0, bytesRead));
23140
+ }
23141
+ cb();
23142
+ });
23143
+ });
23144
+ };
23145
+ ReadStream.prototype._destroy = function(err, cb) {
23146
+ this._cleanup();
23147
+ cb(err);
23148
+ };
23149
+ ReadStream.prototype._cleanup = function() {
23150
+ if (this.context != null) {
23151
+ this.context.unref();
23152
+ this.context = null;
23153
+ }
23154
+ };
23155
+ util.inherits(BufferSlicer, EventEmitter);
23156
+ function BufferSlicer(buffer) {
23157
+ EventEmitter.call(this);
23158
+ this.refCount = 0;
23159
+ this.buffer = buffer;
23160
+ }
23161
+ BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
23162
+ if (!(0 <= offset && offset <= buffer.length)) throw new RangeError("offset outside buffer: 0 <= " + offset + " <= " + buffer.length);
23163
+ if (position < 0) throw new RangeError("position is negative: " + position);
23164
+ if (offset + length > buffer.length) length = buffer.length - offset;
23165
+ if (position + length > this.buffer.length) length = this.buffer.length - position;
23166
+ if (length <= 0) {
23167
+ setImmediate(function() {
23168
+ callback(null, 0);
23169
+ });
23170
+ return;
23171
+ }
23172
+ this.buffer.copy(buffer, offset, position, position + length);
23173
+ setImmediate(function() {
23174
+ callback(null, length);
23175
+ });
23176
+ };
23177
+ BufferSlicer.prototype.createReadStream = function(options) {
23178
+ options = options || {};
23179
+ var readStream = new PassThrough(options);
23180
+ readStream.start = options.start || 0;
23181
+ readStream.endOffset = options.end;
23182
+ readStream.pos = readStream.endOffset || this.buffer.length;
23183
+ var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
23184
+ var maxChunkSize = 65536;
23185
+ var offset = 0;
23186
+ while (true) {
23187
+ var nextOffset = offset + maxChunkSize;
23188
+ if (nextOffset >= entireSlice.length) {
23189
+ if (offset < entireSlice.length) readStream.write(entireSlice.slice(offset, entireSlice.length));
23190
+ break;
23191
+ }
23192
+ readStream.write(entireSlice.slice(offset, nextOffset));
23193
+ offset = nextOffset;
23194
+ }
23195
+ readStream.end();
23196
+ return readStream;
23197
+ };
23198
+ BufferSlicer.prototype.ref = function() {
23199
+ this.refCount += 1;
23200
+ };
23201
+ BufferSlicer.prototype.unref = function() {
23202
+ this.refCount -= 1;
23203
+ if (this.refCount < 0) throw new Error("invalid unref");
23204
+ };
23205
+ }));
23206
+ // ../node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/crc32.js
23207
+ var require_crc32 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
23208
+ var CRC_TABLE = new Int32Array([
23209
+ 0,
23210
+ 1996959894,
23211
+ 3993919788,
23212
+ 2567524794,
23213
+ 124634137,
23214
+ 1886057615,
23215
+ 3915621685,
23216
+ 2657392035,
23217
+ 249268274,
23218
+ 2044508324,
23219
+ 3772115230,
23220
+ 2547177864,
23221
+ 162941995,
23222
+ 2125561021,
23223
+ 3887607047,
23224
+ 2428444049,
23225
+ 498536548,
23226
+ 1789927666,
23227
+ 4089016648,
23228
+ 2227061214,
23229
+ 450548861,
23230
+ 1843258603,
23231
+ 4107580753,
23232
+ 2211677639,
23233
+ 325883990,
23234
+ 1684777152,
23235
+ 4251122042,
23236
+ 2321926636,
23237
+ 335633487,
23238
+ 1661365465,
23239
+ 4195302755,
23240
+ 2366115317,
23241
+ 997073096,
23242
+ 1281953886,
23243
+ 3579855332,
23244
+ 2724688242,
23245
+ 1006888145,
23246
+ 1258607687,
23247
+ 3524101629,
23248
+ 2768942443,
23249
+ 901097722,
23250
+ 1119000684,
23251
+ 3686517206,
23252
+ 2898065728,
23253
+ 853044451,
23254
+ 1172266101,
23255
+ 3705015759,
23256
+ 2882616665,
23257
+ 651767980,
23258
+ 1373503546,
23259
+ 3369554304,
23260
+ 3218104598,
23261
+ 565507253,
23262
+ 1454621731,
23263
+ 3485111705,
23264
+ 3099436303,
23265
+ 671266974,
23266
+ 1594198024,
23267
+ 3322730930,
23268
+ 2970347812,
23269
+ 795835527,
23270
+ 1483230225,
23271
+ 3244367275,
23272
+ 3060149565,
23273
+ 1994146192,
23274
+ 31158534,
23275
+ 2563907772,
23276
+ 4023717930,
23277
+ 1907459465,
23278
+ 112637215,
23279
+ 2680153253,
23280
+ 3904427059,
23281
+ 2013776290,
23282
+ 251722036,
23283
+ 2517215374,
23284
+ 3775830040,
23285
+ 2137656763,
23286
+ 141376813,
23287
+ 2439277719,
23288
+ 3865271297,
23289
+ 1802195444,
23290
+ 476864866,
23291
+ 2238001368,
23292
+ 4066508878,
23293
+ 1812370925,
23294
+ 453092731,
23295
+ 2181625025,
23296
+ 4111451223,
23297
+ 1706088902,
23298
+ 314042704,
23299
+ 2344532202,
23300
+ 4240017532,
23301
+ 1658658271,
23302
+ 366619977,
23303
+ 2362670323,
23304
+ 4224994405,
23305
+ 1303535960,
23306
+ 984961486,
23307
+ 2747007092,
23308
+ 3569037538,
23309
+ 1256170817,
23310
+ 1037604311,
23311
+ 2765210733,
23312
+ 3554079995,
23313
+ 1131014506,
23314
+ 879679996,
23315
+ 2909243462,
23316
+ 3663771856,
23317
+ 1141124467,
23318
+ 855842277,
23319
+ 2852801631,
23320
+ 3708648649,
23321
+ 1342533948,
23322
+ 654459306,
23323
+ 3188396048,
23324
+ 3373015174,
23325
+ 1466479909,
23326
+ 544179635,
23327
+ 3110523913,
23328
+ 3462522015,
23329
+ 1591671054,
23330
+ 702138776,
23331
+ 2966460450,
23332
+ 3352799412,
23333
+ 1504918807,
23334
+ 783551873,
23335
+ 3082640443,
23336
+ 3233442989,
23337
+ 3988292384,
23338
+ 2596254646,
23339
+ 62317068,
23340
+ 1957810842,
23341
+ 3939845945,
23342
+ 2647816111,
23343
+ 81470997,
23344
+ 1943803523,
23345
+ 3814918930,
23346
+ 2489596804,
23347
+ 225274430,
23348
+ 2053790376,
23349
+ 3826175755,
23350
+ 2466906013,
23351
+ 167816743,
23352
+ 2097651377,
23353
+ 4027552580,
23354
+ 2265490386,
23355
+ 503444072,
23356
+ 1762050814,
23357
+ 4150417245,
23358
+ 2154129355,
23359
+ 426522225,
23360
+ 1852507879,
23361
+ 4275313526,
23362
+ 2312317920,
23363
+ 282753626,
23364
+ 1742555852,
23365
+ 4189708143,
23366
+ 2394877945,
23367
+ 397917763,
23368
+ 1622183637,
23369
+ 3604390888,
23370
+ 2714866558,
23371
+ 953729732,
23372
+ 1340076626,
23373
+ 3518719985,
23374
+ 2797360999,
23375
+ 1068828381,
23376
+ 1219638859,
23377
+ 3624741850,
23378
+ 2936675148,
23379
+ 906185462,
23380
+ 1090812512,
23381
+ 3747672003,
23382
+ 2825379669,
23383
+ 829329135,
23384
+ 1181335161,
23385
+ 3412177804,
23386
+ 3160834842,
23387
+ 628085408,
23388
+ 1382605366,
23389
+ 3423369109,
23390
+ 3138078467,
23391
+ 570562233,
23392
+ 1426400815,
23393
+ 3317316542,
23394
+ 2998733608,
23395
+ 733239954,
23396
+ 1555261956,
23397
+ 3268935591,
23398
+ 3050360625,
23399
+ 752459403,
23400
+ 1541320221,
23401
+ 2607071920,
23402
+ 3965973030,
23403
+ 1969922972,
23404
+ 40735498,
23405
+ 2617837225,
23406
+ 3943577151,
23407
+ 1913087877,
23408
+ 83908371,
23409
+ 2512341634,
23410
+ 3803740692,
23411
+ 2075208622,
23412
+ 213261112,
23413
+ 2463272603,
23414
+ 3855990285,
23415
+ 2094854071,
23416
+ 198958881,
23417
+ 2262029012,
23418
+ 4057260610,
23419
+ 1759359992,
23420
+ 534414190,
23421
+ 2176718541,
23422
+ 4139329115,
23423
+ 1873836001,
23424
+ 414664567,
23425
+ 2282248934,
23426
+ 4279200368,
23427
+ 1711684554,
23428
+ 285281116,
23429
+ 2405801727,
23430
+ 4167216745,
23431
+ 1634467795,
23432
+ 376229701,
23433
+ 2685067896,
23434
+ 3608007406,
23435
+ 1308918612,
23436
+ 956543938,
23437
+ 2808555105,
23438
+ 3495958263,
23439
+ 1231636301,
23440
+ 1047427035,
23441
+ 2932959818,
23442
+ 3654703836,
23443
+ 1088359270,
23444
+ 936918e3,
23445
+ 2847714899,
23446
+ 3736837829,
23447
+ 1202900863,
23448
+ 817233897,
23449
+ 3183342108,
23450
+ 3401237130,
23451
+ 1404277552,
23452
+ 615818150,
23453
+ 3134207493,
23454
+ 3453421203,
23455
+ 1423857449,
23456
+ 601450431,
23457
+ 3009837614,
23458
+ 3294710456,
23459
+ 1567103746,
23460
+ 711928724,
23461
+ 3020668471,
23462
+ 3272380065,
23463
+ 1510334235,
23464
+ 755167117
23465
+ ]);
23466
+ function crc32(buf) {
23467
+ let crc = -1;
23468
+ for (let x of buf) crc = CRC_TABLE[(crc ^ x) & 255] ^ crc >>> 8;
23469
+ return (crc ^ -1) >>> 0;
23470
+ }
23471
+ module.exports = crc32;
23472
+ }));
23473
+ // ../runner/src/unpack.ts
23474
+ var import_yauzl = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
23475
+ var fs = __require("fs");
23476
+ var zlib = __require("zlib");
23477
+ var fd_slicer = require_fd_slicer();
23478
+ var util = __require("util");
23479
+ var EventEmitter = __require("events").EventEmitter;
23480
+ var Transform = __require("stream").Transform;
23481
+ var PassThrough = __require("stream").PassThrough;
23482
+ var Writable = __require("stream").Writable;
23483
+ var crc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : require_crc32();
23484
+ exports.open = open;
23485
+ function open(path, options, callback) {
23486
+ if (typeof options === "function") {
23487
+ callback = options;
23488
+ options = null;
23489
+ }
23490
+ if (options == null) options = {};
23491
+ if (options.autoClose == null) options.autoClose = true;
23492
+ if (options.lazyEntries == null) options.lazyEntries = false;
23493
+ if (options.decodeStrings == null) options.decodeStrings = true;
23494
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
23495
+ if (options.strictFileNames == null) options.strictFileNames = false;
23496
+ if (callback == null) callback = defaultCallback;
23497
+ fs.open(path, "r", function(err, fd) {
23498
+ if (err) return callback(err);
23499
+ fromFd(fd, options, function(err, zipfile) {
23500
+ if (err) fs.close(fd, defaultCallback);
23501
+ callback(err, zipfile);
23502
+ });
23503
+ });
23504
+ }
23505
+ function fromFd(fd, options, callback) {
23506
+ if (typeof options === "function") {
23507
+ callback = options;
23508
+ options = null;
23509
+ }
23510
+ if (options == null) options = {};
23511
+ if (options.autoClose == null) options.autoClose = false;
23512
+ if (options.lazyEntries == null) options.lazyEntries = false;
23513
+ if (options.decodeStrings == null) options.decodeStrings = true;
23514
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
23515
+ if (options.strictFileNames == null) options.strictFileNames = false;
23516
+ if (callback == null) callback = defaultCallback;
23517
+ fs.fstat(fd, function(err, stats) {
23518
+ if (err) return callback(err);
23519
+ fromRandomAccessReader(new fd_slicer.FdSlicer(fd), stats.size, options, callback);
23520
+ });
23521
+ }
23522
+ function fromRandomAccessReader(reader, totalSize, options, callback) {
23523
+ if (typeof options === "function") {
23524
+ callback = options;
23525
+ options = null;
23526
+ }
23527
+ if (options == null) options = {};
23528
+ if (options.autoClose == null) options.autoClose = true;
23529
+ if (options.lazyEntries == null) options.lazyEntries = false;
23530
+ if (options.decodeStrings == null) options.decodeStrings = true;
23531
+ var decodeStrings = !!options.decodeStrings;
23532
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
23533
+ if (options.strictFileNames == null) options.strictFileNames = false;
23534
+ if (callback == null) callback = defaultCallback;
23535
+ if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
23536
+ if (totalSize > Number.MAX_SAFE_INTEGER) throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
23537
+ reader.ref();
23538
+ var eocdrWithoutCommentSize = 22;
23539
+ var zip64EocdlSize = 20;
23540
+ var bufferSize = Math.min(zip64EocdlSize + eocdrWithoutCommentSize + 65535, totalSize);
23541
+ var buffer = newBuffer(bufferSize);
23542
+ readAndAssertNoEof(reader, buffer, 0, bufferSize, totalSize - buffer.length, function(err) {
23543
+ if (err) return callback(err);
23544
+ for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
23545
+ if (buffer.readUInt32LE(i) !== 101010256) continue;
23546
+ var eocdrBuffer = buffer.subarray(i);
23547
+ var diskNumber = eocdrBuffer.readUInt16LE(4);
23548
+ var entryCount = eocdrBuffer.readUInt16LE(10);
23549
+ var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
23550
+ var commentLength = eocdrBuffer.readUInt16LE(20);
23551
+ var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
23552
+ if (commentLength !== expectedCommentLength) return callback(/* @__PURE__ */ new Error("Invalid comment length. Expected: " + expectedCommentLength + ". Found: " + commentLength + ". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));
23553
+ var comment = decodeStrings ? decodeBuffer(eocdrBuffer.subarray(22), false) : eocdrBuffer.subarray(22);
23554
+ if (i - zip64EocdlSize >= 0 && buffer.readUInt32LE(i - zip64EocdlSize) === 117853008) {
23555
+ var zip64EocdrOffset = readUInt64LE(buffer.subarray(i - zip64EocdlSize, i - zip64EocdlSize + zip64EocdlSize), 8);
23556
+ var zip64EocdrBuffer = newBuffer(56);
23557
+ return readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
23558
+ if (err) return callback(err);
23559
+ if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) return callback(/* @__PURE__ */ new Error("invalid zip64 end of central directory record signature"));
23560
+ diskNumber = zip64EocdrBuffer.readUInt32LE(16);
23561
+ if (diskNumber !== 0) return callback(/* @__PURE__ */ new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
23562
+ entryCount = readUInt64LE(zip64EocdrBuffer, 32);
23563
+ centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
23564
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
23565
+ });
23566
+ }
23567
+ if (diskNumber !== 0) return callback(/* @__PURE__ */ new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
23568
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
23569
+ }
23570
+ callback(/* @__PURE__ */ new Error("End of central directory record signature not found. Either not a zip file, or file is truncated."));
23571
+ });
23572
+ }
23573
+ util.inherits(ZipFile, EventEmitter);
23574
+ function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
23575
+ var self = this;
23576
+ EventEmitter.call(self);
23577
+ self.reader = reader;
23578
+ self.reader.on("error", function(err) {
23579
+ emitError(self, err);
23580
+ });
23581
+ self.reader.once("close", function() {
23582
+ self.emit("close");
23583
+ });
23584
+ self.readEntryCursor = centralDirectoryOffset;
23585
+ self.fileSize = fileSize;
23586
+ self.entryCount = entryCount;
23587
+ self.comment = comment;
23588
+ self.entriesRead = 0;
23589
+ self.autoClose = !!autoClose;
23590
+ self.lazyEntries = !!lazyEntries;
23591
+ self.decodeStrings = !!decodeStrings;
23592
+ self.validateEntrySizes = !!validateEntrySizes;
23593
+ self.strictFileNames = !!strictFileNames;
23594
+ self.isOpen = true;
23595
+ self.emittedError = false;
23596
+ self.hasEachEntryBeenCalled = false;
23597
+ if (!self.lazyEntries) self._readEntry();
23598
+ }
23599
+ ZipFile.prototype.close = function() {
23600
+ if (!this.isOpen) return;
23601
+ this.isOpen = false;
23602
+ this.reader.unref();
23603
+ };
23604
+ function emitErrorAndAutoClose(self, err) {
23605
+ if (self.autoClose) self.close();
23606
+ emitError(self, err);
23607
+ }
23608
+ function emitError(self, err) {
23609
+ if (self.emittedError) return;
23610
+ self.emittedError = true;
23611
+ self.emit("error", err);
23612
+ }
23613
+ ZipFile.prototype.readEntry = function() {
23614
+ if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
23615
+ this._readEntry();
23616
+ };
23617
+ ZipFile.prototype._readEntry = function() {
23618
+ var self = this;
23619
+ if (self.entryCount === self.entriesRead) {
23620
+ setImmediate(function() {
23621
+ if (self.autoClose) self.close();
23622
+ if (self.emittedError) return;
23623
+ self.emit("end");
23624
+ });
23625
+ return;
23626
+ }
23627
+ if (self.emittedError) return;
23628
+ var buffer = newBuffer(46);
23629
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
23630
+ if (err) return emitErrorAndAutoClose(self, err);
23631
+ if (self.emittedError) return;
23632
+ var entry = new Entry();
23633
+ var signature = buffer.readUInt32LE(0);
23634
+ if (signature !== 33639248) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
23635
+ entry.versionMadeBy = buffer.readUInt16LE(4);
23636
+ entry.versionNeededToExtract = buffer.readUInt16LE(6);
23637
+ entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
23638
+ entry.compressionMethod = buffer.readUInt16LE(10);
23639
+ entry.lastModFileTime = buffer.readUInt16LE(12);
23640
+ entry.lastModFileDate = buffer.readUInt16LE(14);
23641
+ entry.crc32 = buffer.readUInt32LE(16);
23642
+ entry.compressedSize = buffer.readUInt32LE(20);
23643
+ entry.uncompressedSize = buffer.readUInt32LE(24);
23644
+ entry.fileNameLength = buffer.readUInt16LE(28);
23645
+ entry.extraFieldLength = buffer.readUInt16LE(30);
23646
+ entry.fileCommentLength = buffer.readUInt16LE(32);
23647
+ entry.internalFileAttributes = buffer.readUInt16LE(36);
23648
+ entry.externalFileAttributes = buffer.readUInt32LE(38);
23649
+ entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
23650
+ if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("strong encryption is not supported"));
23651
+ self.readEntryCursor += 46;
23652
+ buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
23653
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
23654
+ if (err) return emitErrorAndAutoClose(self, err);
23655
+ if (self.emittedError) return;
23656
+ entry.fileNameRaw = buffer.subarray(0, entry.fileNameLength);
23657
+ var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
23658
+ entry.extraFieldRaw = buffer.subarray(entry.fileNameLength, fileCommentStart);
23659
+ entry.fileCommentRaw = buffer.subarray(fileCommentStart, fileCommentStart + entry.fileCommentLength);
23660
+ try {
23661
+ entry.extraFields = parseExtraFields(entry.extraFieldRaw);
23662
+ } catch (err) {
23663
+ return emitErrorAndAutoClose(self, err);
23664
+ }
23665
+ if (self.decodeStrings) {
23666
+ var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0;
23667
+ entry.fileComment = decodeBuffer(entry.fileCommentRaw, isUtf8);
23668
+ entry.fileName = getFileNameLowLevel(entry.generalPurposeBitFlag, entry.fileNameRaw, entry.extraFields, self.strictFileNames);
23669
+ var errorMessage = validateFileName(entry.fileName);
23670
+ if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
23671
+ } else {
23672
+ entry.fileComment = entry.fileCommentRaw;
23673
+ entry.fileName = entry.fileNameRaw;
23674
+ }
23675
+ entry.comment = entry.fileComment;
23676
+ self.readEntryCursor += buffer.length;
23677
+ self.entriesRead += 1;
23678
+ for (var i = 0; i < entry.extraFields.length; i++) {
23679
+ var extraField = entry.extraFields[i];
23680
+ if (extraField.id !== 1) continue;
23681
+ var zip64EiefBuffer = extraField.data;
23682
+ var index = 0;
23683
+ if (entry.uncompressedSize === 4294967295) {
23684
+ if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include uncompressed size"));
23685
+ entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
23686
+ index += 8;
23687
+ }
23688
+ if (entry.compressedSize === 4294967295) {
23689
+ if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include compressed size"));
23690
+ entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
23691
+ index += 8;
23692
+ }
23693
+ if (entry.relativeOffsetOfLocalHeader === 4294967295) {
23694
+ if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include relative header offset"));
23695
+ entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
23696
+ index += 8;
23697
+ }
23698
+ break;
23699
+ }
23700
+ if (self.validateEntrySizes && entry.compressionMethod === 0) {
23701
+ var expectedCompressedSize = entry.uncompressedSize;
23702
+ if (entry.isEncrypted()) expectedCompressedSize += 12;
23703
+ if (entry.compressedSize !== expectedCompressedSize) {
23704
+ var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
23705
+ return emitErrorAndAutoClose(self, new Error(msg));
23706
+ }
23707
+ }
23708
+ self.emit("entry", entry);
23709
+ if (!self.lazyEntries) self._readEntry();
23710
+ });
23711
+ });
23712
+ };
23713
+ ZipFile.prototype.eachEntry = function() {
23714
+ const self = this;
23715
+ if (!self.lazyEntries) throw new Error("eachEntry() requires lazyEntries: true");
23716
+ if (self.hasEachEntryBeenCalled) throw new Error("eachEntry() must only be called once per ZipFile");
23717
+ self.hasEachEntryBeenCalled = true;
23718
+ let pendingResolveReject = null;
23719
+ self.on("entry", onEntry);
23720
+ self.on("end", onEnd);
23721
+ self.on("error", onError);
23722
+ function cleanup() {
23723
+ self.removeListener("entry", onEntry);
23724
+ self.removeListener("end", onEnd);
23725
+ self.removeListener("error", onError);
23726
+ if (self.autoClose) self.close();
23727
+ }
23728
+ function onEntry(entry) {
23729
+ let { resolve } = pendingResolveReject;
23730
+ pendingResolveReject = null;
23731
+ resolve({ value: entry });
23732
+ }
23733
+ function onEnd() {
23734
+ let { resolve } = pendingResolveReject;
23735
+ pendingResolveReject = null;
23736
+ cleanup();
23737
+ resolve({ done: true });
23738
+ }
23739
+ function onError(err) {
23740
+ let { reject } = pendingResolveReject;
23741
+ pendingResolveReject = null;
23742
+ cleanup();
23743
+ reject(err);
23744
+ }
23745
+ return {
23746
+ [Symbol.asyncIterator]() {
23747
+ return this;
23748
+ },
23749
+ next() {
23750
+ const promise = new Promise((resolve, reject) => {
23751
+ if (pendingResolveReject != null) throw new Error("next() called before previous Promise was resolved.");
23752
+ pendingResolveReject = {
23753
+ resolve,
23754
+ reject
23755
+ };
23756
+ });
23757
+ self.readEntry();
23758
+ return promise;
23759
+ },
23760
+ return(value) {
23761
+ cleanup();
23762
+ return Promise.resolve({
23763
+ done: true,
23764
+ value
23765
+ });
23766
+ },
23767
+ throw(value) {
23768
+ cleanup();
23769
+ return Promise.reject(value);
23770
+ }
23771
+ };
23772
+ };
23773
+ ZipFile.prototype.openReadStream = function(entry, options, callback) {
23774
+ var self = this;
23775
+ var relativeStart = 0;
23776
+ var relativeEnd = entry.compressedSize;
23777
+ if (callback == null) {
23778
+ callback = options;
23779
+ options = null;
23780
+ }
23781
+ if (options == null) options = {};
23782
+ else {
23783
+ if (options.decodeFileData === false) {
23784
+ if (options.decrypt != null) throw new Error("cannot use options.decrypt when options.decodeFileData === false");
23785
+ if (options.decompress != null) throw new Error("cannot use options.decompress when options.decodeFileData === false");
23786
+ } else {
23787
+ if (options.decrypt != null) {
23788
+ if (!entry.isEncrypted()) throw new Error("options.decrypt can only be specified for encrypted entries. See also option decodeFileData.");
23789
+ if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
23790
+ if (entry.isCompressed()) {
23791
+ if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.");
23792
+ }
23793
+ }
23794
+ if (options.decompress != null) {
23795
+ if (!entry.isCompressed()) throw new Error("options.decompress can only be specified for compressed entries. See also option decodeFileData.");
23796
+ if (!(options.decompress === false || options.decompress === true)) throw new Error("invalid options.decompress value: " + options.decompress);
23797
+ decompress = options.decompress;
23798
+ }
23799
+ }
23800
+ if (options.start != null) {
23801
+ relativeStart = options.start;
23802
+ if (relativeStart < 0) throw new Error("options.start < 0");
23803
+ if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
23804
+ }
23805
+ if (options.end != null) {
23806
+ relativeEnd = options.end;
23807
+ if (relativeEnd < 0) throw new Error("options.end < 0");
23808
+ if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
23809
+ if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
23810
+ }
23811
+ }
23812
+ var rawMode = options.decodeFileData === false || (entry.compressionMethod === 0 || entry.compressionMethod === 8 && options.decompress === false) && (!entry.isEncrypted() || options.decrypt === false);
23813
+ if (options.start != null || options.end != null) {
23814
+ if (!rawMode) throw new Error("start/end range require options.decodeFileData === false for non-trivial encoded entries.");
23815
+ }
23816
+ if (!self.isOpen) return callback(/* @__PURE__ */ new Error("closed"));
23817
+ if (entry.isEncrypted() && !rawMode) {
23818
+ if (options.decrypt !== false) return callback(/* @__PURE__ */ new Error("entry is encrypted, and options.decodeFileData !== false"));
23819
+ }
23820
+ var decompress;
23821
+ if (rawMode) decompress = false;
23822
+ else if (entry.compressionMethod === 8) decompress = options.decodeFileData !== true;
23823
+ else return callback(/* @__PURE__ */ new Error("unsupported compression method: " + entry.compressionMethod));
23824
+ self.readLocalFileHeader(entry, { minimal: true }, function(err, localFileHeader) {
23825
+ if (err) return callback(err);
23826
+ self.openReadStreamLowLevel(localFileHeader.fileDataStart, entry.compressedSize, relativeStart, relativeEnd, decompress, entry.uncompressedSize, callback);
23827
+ });
23828
+ };
23829
+ ZipFile.prototype.openReadStreamLowLevel = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) {
23830
+ var self = this;
23831
+ fileDataStart + compressedSize;
23832
+ var readStream = self.reader.createReadStream({
23833
+ start: fileDataStart + relativeStart,
23834
+ end: fileDataStart + relativeEnd
23835
+ });
23836
+ var endpointStream = readStream;
23837
+ if (decompress) {
23838
+ var destroyed = false;
23839
+ var inflateFilter = zlib.createInflateRaw();
23840
+ readStream.on("error", function(err) {
23841
+ setImmediate(function() {
23842
+ if (!destroyed) inflateFilter.emit("error", err);
23843
+ });
23844
+ });
23845
+ readStream.pipe(inflateFilter);
23846
+ if (self.validateEntrySizes) {
23847
+ endpointStream = new AssertByteCountStream(uncompressedSize);
23848
+ inflateFilter.on("error", function(err) {
23849
+ setImmediate(function() {
23850
+ if (!destroyed) endpointStream.emit("error", err);
23851
+ });
23852
+ });
23853
+ inflateFilter.pipe(endpointStream);
23854
+ } else endpointStream = inflateFilter;
23855
+ installDestroyFn(endpointStream, function() {
23856
+ destroyed = true;
23857
+ if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
23858
+ readStream.unpipe(inflateFilter);
23859
+ readStream.destroy();
23860
+ });
23861
+ }
23862
+ callback(null, endpointStream);
23863
+ };
23864
+ ZipFile.prototype.readLocalFileHeader = function(entry, options, callback) {
23865
+ var self = this;
23866
+ if (callback == null) {
23867
+ callback = options;
23868
+ options = null;
23869
+ }
23870
+ if (options == null) options = {};
23871
+ self.reader.ref();
23872
+ var buffer = newBuffer(30);
23873
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
23874
+ try {
23875
+ if (err) return callback(err);
23876
+ var signature = buffer.readUInt32LE(0);
23877
+ if (signature !== 67324752) return callback(/* @__PURE__ */ new Error("invalid local file header signature: 0x" + signature.toString(16)));
23878
+ var fileNameLength = buffer.readUInt16LE(26);
23879
+ var extraFieldLength = buffer.readUInt16LE(28);
23880
+ var fileDataStart = entry.relativeOffsetOfLocalHeader + 30 + fileNameLength + extraFieldLength;
23881
+ if (fileDataStart + entry.compressedSize > self.fileSize) return callback(/* @__PURE__ */ new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
23882
+ if (options.minimal) return callback(null, { fileDataStart });
23883
+ var localFileHeader = new LocalFileHeader();
23884
+ localFileHeader.fileDataStart = fileDataStart;
23885
+ localFileHeader.versionNeededToExtract = buffer.readUInt16LE(4);
23886
+ localFileHeader.generalPurposeBitFlag = buffer.readUInt16LE(6);
23887
+ localFileHeader.compressionMethod = buffer.readUInt16LE(8);
23888
+ localFileHeader.lastModFileTime = buffer.readUInt16LE(10);
23889
+ localFileHeader.lastModFileDate = buffer.readUInt16LE(12);
23890
+ localFileHeader.crc32 = buffer.readUInt32LE(14);
23891
+ localFileHeader.compressedSize = buffer.readUInt32LE(18);
23892
+ localFileHeader.uncompressedSize = buffer.readUInt32LE(22);
23893
+ localFileHeader.fileNameLength = fileNameLength;
23894
+ localFileHeader.extraFieldLength = extraFieldLength;
23895
+ buffer = newBuffer(fileNameLength + extraFieldLength);
23896
+ self.reader.ref();
23897
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader + 30, function(err) {
23898
+ try {
23899
+ if (err) return callback(err);
23900
+ localFileHeader.fileName = buffer.subarray(0, fileNameLength);
23901
+ localFileHeader.extraField = buffer.subarray(fileNameLength);
23902
+ return callback(null, localFileHeader);
23903
+ } finally {
23904
+ self.reader.unref();
23905
+ }
23906
+ });
23907
+ } finally {
23908
+ self.reader.unref();
23909
+ }
23910
+ });
23911
+ };
23912
+ ZipFile.prototype.openReadStreamPromise = function(entry, options) {
23913
+ return new Promise((resolve, reject) => {
23914
+ this.openReadStream(entry, options, function(err, readStream) {
23915
+ if (err) return reject(err);
23916
+ resolve(readStream);
23917
+ });
23918
+ });
23919
+ };
23920
+ ZipFile.prototype.openReadStreamLowLevelPromise = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize) {
23921
+ return new Promise((resolve, reject) => {
23922
+ this.openReadStream(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, function(err, readStream) {
23923
+ if (err) return reject(err);
23924
+ resolve(readStream);
23925
+ });
23926
+ });
23927
+ };
23928
+ ZipFile.prototype.readLocalFileHeaderPromise = function(entry, options) {
23929
+ return new Promise((resolve, reject) => {
23930
+ this.readLocalFileHeader(entry, options, function(err, localFileHeader) {
23931
+ if (err) return reject(err);
23932
+ resolve(localFileHeader);
23933
+ });
23934
+ });
23935
+ };
23936
+ function Entry() {}
23937
+ Entry.prototype.getLastModDate = function(options) {
23938
+ if (options == null) options = {};
23939
+ if (!options.forceDosFormat) for (var i = 0; i < this.extraFields.length; i++) {
23940
+ var extraField = this.extraFields[i];
23941
+ if (extraField.id === 21589) {
23942
+ var data = extraField.data;
23943
+ if (data.length < 5) continue;
23944
+ if (!(data[0] & 1)) continue;
23945
+ var posixTimestamp = data.readInt32LE(1);
23946
+ return /* @__PURE__ */ new Date(posixTimestamp * 1e3);
23947
+ } else if (extraField.id === 10) {
23948
+ var data = extraField.data;
23949
+ if (data.length !== 32) continue;
23950
+ if (data.readUInt16LE(4) !== 1) continue;
23951
+ if (data.readUInt16LE(6) !== 24) continue;
23952
+ var millisecondsSince1970 = (data.readUInt32LE(8) + 4294967296 * data.readInt32LE(12)) / 1e4 - 0xa9730b66800;
23953
+ return new Date(millisecondsSince1970);
23954
+ }
23955
+ }
23956
+ return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime, options.timezone);
23957
+ };
23958
+ Entry.prototype.canDecodeFileData = function() {
23959
+ return !this.isEncrypted() && (this.compressionMethod === 0 || this.compressionMethod === 8);
23960
+ };
23961
+ Entry.prototype.isEncrypted = function() {
23962
+ return (this.generalPurposeBitFlag & 1) !== 0;
23963
+ };
23964
+ Entry.prototype.isCompressed = function() {
23965
+ return this.compressionMethod === 8;
23966
+ };
23967
+ function LocalFileHeader() {}
23968
+ function dosDateTimeToDate(date, time, timezone) {
23969
+ var day = date & 31;
23970
+ var month = (date >> 5 & 15) - 1;
23971
+ var year = (date >> 9 & 127) + 1980;
23972
+ var millisecond = 0;
23973
+ var second = (time & 31) * 2;
23974
+ var minute = time >> 5 & 63;
23975
+ var hour = time >> 11 & 31;
23976
+ if (timezone == null || timezone === "local") return new Date(year, month, day, hour, minute, second, millisecond);
23977
+ else if (timezone === "UTC") return new Date(Date.UTC(year, month, day, hour, minute, second, millisecond));
23978
+ else throw new Error("unrecognized options.timezone: " + options.timezone);
23979
+ }
23980
+ function getFileNameLowLevel(generalPurposeBitFlag, fileNameBuffer, extraFields, strictFileNames) {
23981
+ var fileName = null;
23982
+ for (var i = 0; i < extraFields.length; i++) {
23983
+ var extraField = extraFields[i];
23984
+ if (extraField.id === 28789) {
23985
+ if (extraField.data.length < 6) continue;
23986
+ if (extraField.data.readUInt8(0) !== 1) continue;
23987
+ var oldNameCrc32 = extraField.data.readUInt32LE(1);
23988
+ if (crc32(fileNameBuffer) !== oldNameCrc32) continue;
23989
+ fileName = decodeBuffer(extraField.data.subarray(5), true);
23990
+ break;
23991
+ }
23992
+ }
23993
+ if (fileName == null) fileName = decodeBuffer(fileNameBuffer, (generalPurposeBitFlag & 2048) !== 0);
23994
+ if (!strictFileNames) fileName = fileName.replace(/\\/g, "/");
23995
+ return fileName;
23996
+ }
23997
+ function validateFileName(fileName) {
23998
+ if (fileName.indexOf("\\") !== -1) return "invalid characters in fileName: " + fileName;
23999
+ if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) return "absolute path: " + fileName;
24000
+ if (fileName.split("/").indexOf("..") !== -1) return "invalid relative path: " + fileName;
24001
+ return null;
24002
+ }
24003
+ function parseExtraFields(extraFieldBuffer) {
24004
+ var extraFields = [];
24005
+ var i = 0;
24006
+ while (i < extraFieldBuffer.length - 3) {
24007
+ var headerId = extraFieldBuffer.readUInt16LE(i + 0);
24008
+ var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
24009
+ var dataStart = i + 4;
24010
+ var dataEnd = dataStart + dataSize;
24011
+ if (dataEnd > extraFieldBuffer.length) throw new Error("extra field length exceeds extra field buffer size");
24012
+ var dataBuffer = extraFieldBuffer.subarray(dataStart, dataEnd);
24013
+ extraFields.push({
24014
+ id: headerId,
24015
+ data: dataBuffer
24016
+ });
24017
+ i = dataEnd;
24018
+ }
24019
+ return extraFields;
24020
+ }
24021
+ function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
24022
+ if (length === 0) return setImmediate(function() {
24023
+ callback(null, newBuffer(0));
24024
+ });
24025
+ reader.read(buffer, offset, length, position, function(err, bytesRead) {
24026
+ if (err) return callback(err);
24027
+ if (bytesRead < length) return callback(/* @__PURE__ */ new Error("unexpected EOF"));
24028
+ callback();
24029
+ });
24030
+ }
24031
+ util.inherits(AssertByteCountStream, Transform);
24032
+ function AssertByteCountStream(byteCount) {
24033
+ Transform.call(this);
24034
+ this.actualByteCount = 0;
24035
+ this.expectedByteCount = byteCount;
24036
+ }
24037
+ AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
24038
+ this.actualByteCount += chunk.length;
24039
+ if (this.actualByteCount > this.expectedByteCount) {
24040
+ var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
24041
+ return cb(new Error(msg));
24042
+ }
24043
+ cb(null, chunk);
24044
+ };
24045
+ AssertByteCountStream.prototype._flush = function(cb) {
24046
+ if (this.actualByteCount < this.expectedByteCount) {
24047
+ var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
24048
+ return cb(new Error(msg));
24049
+ }
24050
+ cb();
24051
+ };
24052
+ util.inherits(RandomAccessReader, EventEmitter);
24053
+ function RandomAccessReader() {
24054
+ EventEmitter.call(this);
24055
+ this.refCount = 0;
24056
+ }
24057
+ RandomAccessReader.prototype.ref = function() {
24058
+ this.refCount += 1;
24059
+ };
24060
+ RandomAccessReader.prototype.unref = function() {
24061
+ var self = this;
24062
+ self.refCount -= 1;
24063
+ if (self.refCount > 0) return;
24064
+ if (self.refCount < 0) throw new Error("invalid unref");
24065
+ self.close(onCloseDone);
24066
+ function onCloseDone(err) {
24067
+ if (err) return self.emit("error", err);
24068
+ self.emit("close");
24069
+ }
24070
+ };
24071
+ RandomAccessReader.prototype.createReadStream = function(options) {
24072
+ if (options == null) options = {};
24073
+ var start = options.start;
24074
+ var end = options.end;
24075
+ if (start === end) {
24076
+ var emptyStream = new PassThrough();
24077
+ setImmediate(function() {
24078
+ emptyStream.end();
24079
+ });
24080
+ return emptyStream;
24081
+ }
24082
+ var stream = this._readStreamForRange(start, end);
24083
+ var destroyed = false;
24084
+ var refUnrefFilter = new RefUnrefFilter(this);
24085
+ stream.on("error", function(err) {
24086
+ setImmediate(function() {
24087
+ if (!destroyed) refUnrefFilter.emit("error", err);
24088
+ });
24089
+ });
24090
+ installDestroyFn(refUnrefFilter, function() {
24091
+ stream.unpipe(refUnrefFilter);
24092
+ refUnrefFilter.unref();
24093
+ stream.destroy();
24094
+ });
24095
+ var byteCounter = new AssertByteCountStream(end - start);
24096
+ refUnrefFilter.on("error", function(err) {
24097
+ setImmediate(function() {
24098
+ if (!destroyed) byteCounter.emit("error", err);
24099
+ });
24100
+ });
24101
+ installDestroyFn(byteCounter, function() {
24102
+ destroyed = true;
24103
+ refUnrefFilter.unpipe(byteCounter);
24104
+ refUnrefFilter.destroy();
24105
+ });
24106
+ return stream.pipe(refUnrefFilter).pipe(byteCounter);
24107
+ };
24108
+ RandomAccessReader.prototype._readStreamForRange = function(start, end) {
24109
+ throw new Error("not implemented");
24110
+ };
24111
+ RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
24112
+ var readStream = this.createReadStream({
24113
+ start: position,
24114
+ end: position + length
24115
+ });
24116
+ var writeStream = new Writable();
24117
+ var written = 0;
24118
+ writeStream._write = function(chunk, encoding, cb) {
24119
+ chunk.copy(buffer, offset + written, 0, chunk.length);
24120
+ written += chunk.length;
24121
+ cb();
24122
+ };
24123
+ writeStream.on("finish", callback);
24124
+ readStream.on("error", function(error) {
24125
+ callback(error);
24126
+ });
24127
+ readStream.pipe(writeStream);
24128
+ };
24129
+ RandomAccessReader.prototype.close = function(callback) {
24130
+ setImmediate(callback);
24131
+ };
24132
+ util.inherits(RefUnrefFilter, PassThrough);
24133
+ function RefUnrefFilter(context) {
24134
+ PassThrough.call(this);
24135
+ this.context = context;
24136
+ this.context.ref();
24137
+ this.unreffedYet = false;
24138
+ }
24139
+ RefUnrefFilter.prototype._flush = function(cb) {
24140
+ this.unref();
24141
+ cb();
24142
+ };
24143
+ RefUnrefFilter.prototype.unref = function(cb) {
24144
+ if (this.unreffedYet) return;
24145
+ this.unreffedYet = true;
24146
+ this.context.unref();
24147
+ };
24148
+ var cp437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
24149
+ function decodeBuffer(buffer, isUtf8) {
24150
+ if (isUtf8) return buffer.toString("utf8");
24151
+ else {
24152
+ var result = "";
24153
+ for (var i = 0; i < buffer.length; i++) result += cp437[buffer[i]];
24154
+ return result;
24155
+ }
24156
+ }
24157
+ function readUInt64LE(buffer, offset) {
24158
+ var lower32 = buffer.readUInt32LE(offset);
24159
+ return buffer.readUInt32LE(offset + 4) * 4294967296 + lower32;
24160
+ }
24161
+ var newBuffer;
24162
+ if (typeof Buffer.allocUnsafe === "function") newBuffer = function(len) {
24163
+ return Buffer.allocUnsafe(len);
24164
+ };
24165
+ else newBuffer = function(len) {
24166
+ return new Buffer(len);
24167
+ };
24168
+ function installDestroyFn(stream, fn) {
24169
+ if (typeof stream.destroy === "function") stream._destroy = function(err, cb) {
24170
+ fn();
24171
+ if (cb != null) cb(err);
24172
+ };
24173
+ else stream.destroy = fn;
24174
+ }
24175
+ function defaultCallback(err) {
24176
+ if (err) throw err;
24177
+ }
24178
+ })))(), 1);
24179
+ var UNPACK_LIMITS = {
24180
+ maxFiles: 2e4,
24181
+ maxBytes: 536870912,
24182
+ maxRatio: 200
24183
+ };
24184
+ var RATIO_FLOOR_BYTES = 1048576;
24185
+ var S_IFMT = 61440;
24186
+ var S_IFREG = 32768;
24187
+ var S_IFDIR = 16384;
24188
+ var S_IFLNK = 40960;
24189
+ var UnpackError = class extends Error {
24190
+ code;
24191
+ constructor(code, message, options) {
24192
+ super(message, options);
24193
+ this.name = "UnpackError";
24194
+ this.code = code;
24195
+ }
24196
+ };
24197
+ function openZip(file) {
24198
+ return new Promise((resolve, reject) => {
24199
+ import_yauzl.open(file, {
24200
+ lazyEntries: true,
24201
+ decodeStrings: false,
24202
+ validateEntrySizes: true,
24203
+ autoClose: false
24204
+ }, (err, zip) => {
24205
+ if (err) reject(new UnpackError("BAD_ZIP", "The file is not a readable zip", { cause: err }));
24206
+ else resolve(zip);
24207
+ });
24208
+ });
24209
+ }
24210
+ function readEntries(zip) {
24211
+ return new Promise((resolve, reject) => {
24212
+ const entries = [];
24213
+ zip.on("entry", (entry) => {
24214
+ entries.push(entry);
24215
+ zip.readEntry();
24216
+ });
24217
+ zip.on("end", () => resolve(entries));
24218
+ zip.on("error", (err) => reject(new UnpackError("BAD_ZIP", "The zip is damaged", { cause: err })));
24219
+ zip.readEntry();
24220
+ });
24221
+ }
24222
+ function safeRelativePath(raw) {
24223
+ if (raw.includes("\\") || raw.includes("\0") || raw.startsWith("/") || /^[A-Za-z]:/.test(raw)) throw new UnpackError("PATH_ESCAPE", `Refused a path that leaves the entry folder: ${raw}`);
24224
+ const parts = raw.split("/").filter((p) => p !== "" && p !== ".");
24225
+ if (parts.length === 0 || parts.includes("..")) throw new UnpackError("PATH_ESCAPE", `Refused a path that leaves the entry folder: ${raw}`);
24226
+ return parts.join("/");
24227
+ }
24228
+ function describe(entry, limits) {
24229
+ const name = safeRelativePath(entry.fileName.toString("utf8"));
24230
+ const mode = entry.versionMadeBy >> 8 === 3 ? entry.externalFileAttributes >>> 16 : 0;
24231
+ const type = mode & S_IFMT;
24232
+ if (type === S_IFLNK) throw new UnpackError("LINK", `Refused a link: ${name}`);
24233
+ if (type !== 0 && type !== S_IFREG && type !== S_IFDIR) throw new UnpackError("BAD_ZIP", `Refused a special file: ${name}`);
24234
+ const dir = type === S_IFDIR || entry.fileName.at(-1) === 47;
24235
+ if (!dir && entry.uncompressedSize > RATIO_FLOOR_BYTES && entry.uncompressedSize > Math.max(entry.compressedSize, 1) * limits.maxRatio) throw new UnpackError("BOMB", `Refused ${name}: it expands more than ${limits.maxRatio} times`);
24236
+ return {
24237
+ name,
24238
+ dir,
24239
+ executable: (mode & 73) !== 0,
24240
+ entry
24241
+ };
24242
+ }
24243
+ function plan(entries, limits) {
24244
+ const items = entries.map((e) => describe(e, limits));
24245
+ const files = items.filter((i) => !i.dir);
24246
+ if (new Set(files.map((i) => i.name.toLowerCase())).size !== files.length) throw new UnpackError("BAD_ZIP", "The zip holds the same file name twice");
24247
+ if (files.length > limits.maxFiles) throw new UnpackError("TOO_MANY_FILES", `The zip holds ${files.length} files; the limit is ${limits.maxFiles}`);
24248
+ const declared = files.reduce((sum, i) => sum + i.entry.uncompressedSize, 0);
24249
+ if (declared > limits.maxBytes) throw new UnpackError("TOO_LARGE", `The zip unpacks to ${declared} bytes; the limit is ${limits.maxBytes}`);
24250
+ return items;
24251
+ }
24252
+ function openStream(zip, entry) {
24253
+ return new Promise((resolve, reject) => {
24254
+ zip.openReadStream(entry, (err, stream) => {
24255
+ if (err) reject(new UnpackError("BAD_ZIP", "Could not read a file in the zip", { cause: err }));
24256
+ else resolve(stream);
24257
+ });
24258
+ });
24259
+ }
24260
+ async function extract(zip, items, destDir) {
24261
+ const root = path.resolve(destDir);
24262
+ let bytes = 0;
24263
+ for (const item of items) {
24264
+ const target = path.resolve(root, ...item.name.split("/"));
24265
+ if (!target.startsWith(root + path.sep)) throw new UnpackError("PATH_ESCAPE", `Refused ${item.name}`);
24266
+ if (item.dir) {
24267
+ await mkdir(target, { recursive: true });
24268
+ continue;
24269
+ }
24270
+ await mkdir(path.dirname(target), { recursive: true });
24271
+ const stream = await openStream(zip, item.entry);
24272
+ try {
24273
+ await pipeline(stream, createWriteStream(target, {
24274
+ flags: "wx",
24275
+ mode: item.executable ? 493 : 420
24276
+ }));
24277
+ } catch (err) {
24278
+ if (err instanceof UnpackError) throw err;
24279
+ throw new UnpackError("BOMB", `Refused ${item.name}: it inflates past its declared size`, { cause: err });
24280
+ }
24281
+ bytes += item.entry.uncompressedSize;
24282
+ }
24283
+ return bytes;
24284
+ }
24285
+ async function unpack(zipPath, destDir, limits = UNPACK_LIMITS) {
24286
+ const zip = await openZip(zipPath);
24287
+ try {
24288
+ const items = plan(await readEntries(zip), limits);
24289
+ await mkdir(destDir, { recursive: true });
24290
+ const bytes = await extract(zip, items, destDir);
24291
+ return {
24292
+ files: items.filter((i) => !i.dir).length,
24293
+ bytes
24294
+ };
24295
+ } catch (err) {
24296
+ await rm(destDir, {
24297
+ recursive: true,
24298
+ force: true
24299
+ });
24300
+ throw err;
24301
+ } finally {
24302
+ zip.close();
24303
+ }
24304
+ }
23005
24305
  // src/local/precheck.ts
23006
24306
  var RUN_LIMIT_MS = 6e5;
23007
24307
  var noStep = () => void 0;
@@ -23018,9 +24318,11 @@ async function stageKit(kit, dir) {
23018
24318
  for (const [i, test] of kit.tests.entries()) {
23019
24319
  const slot = path.join(dir, String(i));
23020
24320
  await mkdir(slot, { recursive: true });
23021
- const inputFile = path.join(slot, `input-${safeName(test.input_file)}`);
24321
+ const given = path.join(slot, `input-${safeName(test.input_file)}`);
23022
24322
  const expectedFile = path.join(slot, `expected-${safeName(test.expected_file)}`);
23023
- await writeFile(inputFile, Buffer.from(test.input, "base64"));
24323
+ await writeFile(given, Buffer.from(test.input, "base64"));
24324
+ const inputFile = test.input_folder ? path.join(slot, "input") : given;
24325
+ if (test.input_folder) await unpack(given, inputFile);
23024
24326
  await writeFile(expectedFile, Buffer.from(test.expected, "base64"));
23025
24327
  tests.push({
23026
24328
  kind: "sample",
@@ -23093,7 +24395,7 @@ async function precheckLocally(kit, entryDir, openBox = openSandbox) {
23093
24395
  var runPrecheck = {
23094
24396
  name: "deck.run_precheck",
23095
24397
  title: "Run the pre-check",
23096
- description: "For builders, on this computer. Runs a quest’s sample tests and the security scan on your entry folder in a local sandbox (Docker), then tells The Deck the result. The hidden tests are never sent; it costs nothing. The folder needs a deck.json naming the command, like {\"run\": [\"python\", \"main.py\", \"{input}\"]}.",
24398
+ description: "For builders, on this computer. Runs a quest’s sample tests and the security scan on your entry folder in a local sandbox (Docker), then tells The Deck the result. The hidden tests are never sent; it costs nothing. The folder needs a deck.json naming the command, like {\"run\": [\"python\", \"main.py\", \"{input}\"]}. When a test’s input is several files, {input} is a folder holding them.",
23097
24399
  async run(backend, args) {
23098
24400
  const result = await precheckLocally(await backend.getPrecheckKit({ quest_id: args.quest_id }), args.entry_dir);
23099
24401
  await backend.reportPrecheck({