@donezone/cli 0.1.40 → 0.1.43

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/index.js CHANGED
@@ -8618,6 +8618,10 @@ var require_bn = __commonJS((exports, module) => {
8618
8618
  var mask = 67108863 ^ 67108863 >>> r << r;
8619
8619
  this.words[this.length - 1] &= mask;
8620
8620
  }
8621
+ if (this.length === 0) {
8622
+ this.words[0] = 0;
8623
+ this.length = 1;
8624
+ }
8621
8625
  return this.strip();
8622
8626
  };
8623
8627
  BN.prototype.maskn = function maskn(bits) {
@@ -16952,12 +16956,18 @@ var require_immutable = __commonJS((exports, module) => {
16952
16956
  function get(collection, key, notSetValue) {
16953
16957
  return isImmutable(collection) ? collection.get(key, notSetValue) : !has(collection, key) ? notSetValue : typeof collection.get === "function" ? collection.get(key) : collection[key];
16954
16958
  }
16959
+ function isProtoKey(key) {
16960
+ return typeof key === "string" && (key === "__proto__" || key === "constructor");
16961
+ }
16955
16962
  function shallowCopy(from) {
16956
16963
  if (Array.isArray(from)) {
16957
16964
  return arrCopy(from);
16958
16965
  }
16959
16966
  var to = {};
16960
16967
  for (var key in from) {
16968
+ if (isProtoKey(key)) {
16969
+ continue;
16970
+ }
16961
16971
  if (hasOwnProperty.call(from, key)) {
16962
16972
  to[key] = from[key];
16963
16973
  }
@@ -16986,6 +16996,9 @@ var require_immutable = __commonJS((exports, module) => {
16986
16996
  return collectionCopy;
16987
16997
  }
16988
16998
  function set(collection, key, value) {
16999
+ if (isProtoKey(key)) {
17000
+ return collection;
17001
+ }
16989
17002
  if (!isDataStructure(collection)) {
16990
17003
  throw new TypeError("Cannot update non-data-structure value: " + collection);
16991
17004
  }
@@ -17135,6 +17148,9 @@ var require_immutable = __commonJS((exports, module) => {
17135
17148
  }
17136
17149
  merged.push(value);
17137
17150
  } : function(value, key) {
17151
+ if (isProtoKey(key)) {
17152
+ return;
17153
+ }
17138
17154
  var hasVal = hasOwnProperty.call(merged, key);
17139
17155
  var nextVal = hasVal && merger ? merger(merged[key], value, key) : value;
17140
17156
  if (!hasVal || nextVal !== merged[key]) {
@@ -18687,6 +18703,9 @@ var require_immutable = __commonJS((exports, module) => {
18687
18703
  if (isKeyed(value)) {
18688
18704
  var result$1 = {};
18689
18705
  value.__iterate(function(v, k) {
18706
+ if (isProtoKey(k)) {
18707
+ return;
18708
+ }
18690
18709
  result$1[k] = toJS(v);
18691
18710
  });
18692
18711
  return result$1;
@@ -19019,6 +19038,9 @@ var require_immutable = __commonJS((exports, module) => {
19019
19038
  assertNotInfinite(this.size);
19020
19039
  var object = {};
19021
19040
  this.__iterate(function(v, k) {
19041
+ if (isProtoKey(k)) {
19042
+ return;
19043
+ }
19022
19044
  object[k] = v;
19023
19045
  });
19024
19046
  return object;
@@ -19858,7 +19880,7 @@ var require_immutable = __commonJS((exports, module) => {
19858
19880
  function defaultConverter(k, v) {
19859
19881
  return isIndexed(v) ? v.toList() : isKeyed(v) ? v.toMap() : v.toSet();
19860
19882
  }
19861
- var version = "4.3.7";
19883
+ var version = "4.3.8";
19862
19884
  var Immutable = {
19863
19885
  version,
19864
19886
  Collection,
@@ -22545,52 +22567,135 @@ function textDecode(bytes2, encoding = "utf-8") {
22545
22567
  throw new RangeError(`Encoding '${encoding}' not supported`);
22546
22568
  }
22547
22569
  }
22570
+ function flushChunk(parts, chunk) {
22571
+ if (chunk.length === 0)
22572
+ return;
22573
+ parts.push(String.fromCharCode.apply(null, chunk));
22574
+ chunk.length = 0;
22575
+ }
22576
+ function pushCodeUnit(parts, chunk, codeUnit) {
22577
+ chunk.push(codeUnit);
22578
+ if (chunk.length >= CHUNK)
22579
+ flushChunk(parts, chunk);
22580
+ }
22581
+ function pushCodePoint(parts, chunk, cp) {
22582
+ if (cp <= 65535) {
22583
+ pushCodeUnit(parts, chunk, cp);
22584
+ return;
22585
+ }
22586
+ cp -= 65536;
22587
+ pushCodeUnit(parts, chunk, 55296 + (cp >> 10));
22588
+ pushCodeUnit(parts, chunk, 56320 + (cp & 1023));
22589
+ }
22548
22590
  function decodeUTF8(bytes2) {
22549
22591
  const parts = [];
22550
- let out = "";
22592
+ const chunk = [];
22551
22593
  let i = 0;
22594
+ if (bytes2.length >= 3 && bytes2[0] === 239 && bytes2[1] === 187 && bytes2[2] === 191) {
22595
+ i = 3;
22596
+ }
22552
22597
  while (i < bytes2.length) {
22553
- const b1 = bytes2[i++];
22554
- if (b1 < 128) {
22555
- out += String.fromCharCode(b1);
22556
- } else if (b1 < 224) {
22557
- const b2 = bytes2[i++] & 63;
22558
- out += String.fromCharCode((b1 & 31) << 6 | b2);
22559
- } else if (b1 < 240) {
22560
- const b2 = bytes2[i++] & 63;
22561
- const b3 = bytes2[i++] & 63;
22562
- out += String.fromCharCode((b1 & 15) << 12 | b2 << 6 | b3);
22563
- } else {
22564
- const b2 = bytes2[i++] & 63;
22565
- const b3 = bytes2[i++] & 63;
22566
- const b4 = bytes2[i++] & 63;
22567
- let cp = (b1 & 7) << 18 | b2 << 12 | b3 << 6 | b4;
22568
- cp -= 65536;
22569
- out += String.fromCharCode(55296 + (cp >> 10 & 1023), 56320 + (cp & 1023));
22598
+ const b1 = bytes2[i];
22599
+ if (b1 <= 127) {
22600
+ pushCodeUnit(parts, chunk, b1);
22601
+ i++;
22602
+ continue;
22570
22603
  }
22571
- if (out.length >= CHUNK) {
22572
- parts.push(out);
22573
- out = "";
22604
+ if (b1 < 194 || b1 > 244) {
22605
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22606
+ i++;
22607
+ continue;
22574
22608
  }
22609
+ if (b1 <= 223) {
22610
+ if (i + 1 >= bytes2.length) {
22611
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22612
+ i++;
22613
+ continue;
22614
+ }
22615
+ const b22 = bytes2[i + 1];
22616
+ if ((b22 & 192) !== 128) {
22617
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22618
+ i++;
22619
+ continue;
22620
+ }
22621
+ const cp2 = (b1 & 31) << 6 | b22 & 63;
22622
+ pushCodeUnit(parts, chunk, cp2);
22623
+ i += 2;
22624
+ continue;
22625
+ }
22626
+ if (b1 <= 239) {
22627
+ if (i + 2 >= bytes2.length) {
22628
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22629
+ i++;
22630
+ continue;
22631
+ }
22632
+ const b22 = bytes2[i + 1];
22633
+ const b32 = bytes2[i + 2];
22634
+ const valid2 = (b22 & 192) === 128 && (b32 & 192) === 128 && !(b1 === 224 && b22 < 160) && !(b1 === 237 && b22 >= 160);
22635
+ if (!valid2) {
22636
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22637
+ i++;
22638
+ continue;
22639
+ }
22640
+ const cp2 = (b1 & 15) << 12 | (b22 & 63) << 6 | b32 & 63;
22641
+ pushCodeUnit(parts, chunk, cp2);
22642
+ i += 3;
22643
+ continue;
22644
+ }
22645
+ if (i + 3 >= bytes2.length) {
22646
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22647
+ i++;
22648
+ continue;
22649
+ }
22650
+ const b2 = bytes2[i + 1];
22651
+ const b3 = bytes2[i + 2];
22652
+ const b4 = bytes2[i + 3];
22653
+ const valid = (b2 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128 && !(b1 === 240 && b2 < 144) && !(b1 === 244 && b2 > 143);
22654
+ if (!valid) {
22655
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22656
+ i++;
22657
+ continue;
22658
+ }
22659
+ const cp = (b1 & 7) << 18 | (b2 & 63) << 12 | (b3 & 63) << 6 | b4 & 63;
22660
+ pushCodePoint(parts, chunk, cp);
22661
+ i += 4;
22575
22662
  }
22576
- if (out)
22577
- parts.push(out);
22663
+ flushChunk(parts, chunk);
22578
22664
  return parts.join("");
22579
22665
  }
22580
22666
  function decodeUTF16LE(bytes2) {
22581
- const len = bytes2.length & ~1;
22582
- if (len === 0)
22583
- return "";
22584
22667
  const parts = [];
22585
- const maxUnits = CHUNK;
22586
- for (let i = 0;i < len; ) {
22587
- const unitsThis = Math.min(maxUnits, len - i >> 1);
22588
- const units = new Array(unitsThis);
22589
- for (let j = 0;j < unitsThis; j++, i += 2) {
22590
- units[j] = bytes2[i] | bytes2[i + 1] << 8;
22668
+ const chunk = [];
22669
+ const len = bytes2.length;
22670
+ let i = 0;
22671
+ while (i + 1 < len) {
22672
+ const u1 = bytes2[i] | bytes2[i + 1] << 8;
22673
+ i += 2;
22674
+ if (u1 >= 55296 && u1 <= 56319) {
22675
+ if (i + 1 < len) {
22676
+ const u2 = bytes2[i] | bytes2[i + 1] << 8;
22677
+ if (u2 >= 56320 && u2 <= 57343) {
22678
+ pushCodeUnit(parts, chunk, u1);
22679
+ pushCodeUnit(parts, chunk, u2);
22680
+ i += 2;
22681
+ } else {
22682
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22683
+ }
22684
+ } else {
22685
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22686
+ }
22687
+ continue;
22688
+ }
22689
+ if (u1 >= 56320 && u1 <= 57343) {
22690
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22691
+ continue;
22591
22692
  }
22592
- parts.push(String.fromCharCode.apply(null, units));
22693
+ pushCodeUnit(parts, chunk, u1);
22694
+ }
22695
+ if (i < len) {
22696
+ pushCodeUnit(parts, chunk, REPLACEMENT);
22593
22697
  }
22698
+ flushChunk(parts, chunk);
22594
22699
  return parts.join("");
22595
22700
  }
22596
22701
  function decodeASCII(bytes2) {
@@ -22633,7 +22738,7 @@ function decodeWindows1252(bytes2) {
22633
22738
  parts.push(out);
22634
22739
  return parts.join("");
22635
22740
  }
22636
- var WINDOWS_1252_EXTRA, WINDOWS_1252_REVERSE, _utf8Decoder, CHUNK;
22741
+ var WINDOWS_1252_EXTRA, WINDOWS_1252_REVERSE, _utf8Decoder, CHUNK, REPLACEMENT = 65533;
22637
22742
  var init_lib2 = __esm(() => {
22638
22743
  WINDOWS_1252_EXTRA = {
22639
22744
  128: "\u20AC",
@@ -24143,6 +24248,188 @@ var init_supported = __esm(() => {
24143
24248
  });
24144
24249
 
24145
24250
  // ../../node_modules/file-type/core.js
24251
+ function getSafeBound(value, maximum, reason) {
24252
+ if (!Number.isFinite(value) || value < 0 || value > maximum) {
24253
+ throw new ParserHardLimitError(`${reason} has invalid size ${value} (maximum ${maximum} bytes)`);
24254
+ }
24255
+ return value;
24256
+ }
24257
+ async function safeIgnore(tokenizer, length, { maximumLength = maximumUntrustedSkipSizeInBytes, reason = "skip" } = {}) {
24258
+ const safeLength = getSafeBound(length, maximumLength, reason);
24259
+ await tokenizer.ignore(safeLength);
24260
+ }
24261
+ async function safeReadBuffer(tokenizer, buffer, options, { maximumLength = buffer.length, reason = "read" } = {}) {
24262
+ const length = options?.length ?? buffer.length;
24263
+ const safeLength = getSafeBound(length, maximumLength, reason);
24264
+ return tokenizer.readBuffer(buffer, {
24265
+ ...options,
24266
+ length: safeLength
24267
+ });
24268
+ }
24269
+ async function decompressDeflateRawWithLimit(data, { maximumLength = maximumZipEntrySizeInBytes } = {}) {
24270
+ const input = new ReadableStream({
24271
+ start(controller) {
24272
+ controller.enqueue(data);
24273
+ controller.close();
24274
+ }
24275
+ });
24276
+ const output2 = input.pipeThrough(new DecompressionStream("deflate-raw"));
24277
+ const reader = output2.getReader();
24278
+ const chunks = [];
24279
+ let totalLength = 0;
24280
+ try {
24281
+ for (;; ) {
24282
+ const { done, value } = await reader.read();
24283
+ if (done) {
24284
+ break;
24285
+ }
24286
+ totalLength += value.length;
24287
+ if (totalLength > maximumLength) {
24288
+ await reader.cancel();
24289
+ throw new Error(`ZIP entry decompressed data exceeds ${maximumLength} bytes`);
24290
+ }
24291
+ chunks.push(value);
24292
+ }
24293
+ } finally {
24294
+ reader.releaseLock();
24295
+ }
24296
+ const uncompressedData = new Uint8Array(totalLength);
24297
+ let offset = 0;
24298
+ for (const chunk of chunks) {
24299
+ uncompressedData.set(chunk, offset);
24300
+ offset += chunk.length;
24301
+ }
24302
+ return uncompressedData;
24303
+ }
24304
+ function findZipDataDescriptorOffset(buffer, bytesConsumed) {
24305
+ if (buffer.length < zipDataDescriptorLengthInBytes) {
24306
+ return -1;
24307
+ }
24308
+ const lastPossibleDescriptorOffset = buffer.length - zipDataDescriptorLengthInBytes;
24309
+ for (let index = 0;index <= lastPossibleDescriptorOffset; index++) {
24310
+ if (UINT32_LE.get(buffer, index) === zipDataDescriptorSignature && UINT32_LE.get(buffer, index + 8) === bytesConsumed + index) {
24311
+ return index;
24312
+ }
24313
+ }
24314
+ return -1;
24315
+ }
24316
+ function isPngAncillaryChunk(type) {
24317
+ return (type.codePointAt(0) & 32) !== 0;
24318
+ }
24319
+ function mergeByteChunks(chunks, totalLength) {
24320
+ const merged = new Uint8Array(totalLength);
24321
+ let offset = 0;
24322
+ for (const chunk of chunks) {
24323
+ merged.set(chunk, offset);
24324
+ offset += chunk.length;
24325
+ }
24326
+ return merged;
24327
+ }
24328
+ async function readZipDataDescriptorEntryWithLimit(zipHandler, { shouldBuffer, maximumLength = maximumZipEntrySizeInBytes } = {}) {
24329
+ const { syncBuffer } = zipHandler;
24330
+ const { length: syncBufferLength } = syncBuffer;
24331
+ const chunks = [];
24332
+ let bytesConsumed = 0;
24333
+ for (;; ) {
24334
+ const length = await zipHandler.tokenizer.peekBuffer(syncBuffer, { mayBeLess: true });
24335
+ const dataDescriptorOffset = findZipDataDescriptorOffset(syncBuffer.subarray(0, length), bytesConsumed);
24336
+ const retainedLength = dataDescriptorOffset >= 0 ? 0 : length === syncBufferLength ? Math.min(zipDataDescriptorOverlapLengthInBytes, length - 1) : 0;
24337
+ const chunkLength = dataDescriptorOffset >= 0 ? dataDescriptorOffset : length - retainedLength;
24338
+ if (chunkLength === 0) {
24339
+ break;
24340
+ }
24341
+ bytesConsumed += chunkLength;
24342
+ if (bytesConsumed > maximumLength) {
24343
+ throw new Error(`ZIP entry compressed data exceeds ${maximumLength} bytes`);
24344
+ }
24345
+ if (shouldBuffer) {
24346
+ const data = new Uint8Array(chunkLength);
24347
+ await zipHandler.tokenizer.readBuffer(data);
24348
+ chunks.push(data);
24349
+ } else {
24350
+ await zipHandler.tokenizer.ignore(chunkLength);
24351
+ }
24352
+ if (dataDescriptorOffset >= 0) {
24353
+ break;
24354
+ }
24355
+ }
24356
+ if (!hasUnknownFileSize(zipHandler.tokenizer)) {
24357
+ zipHandler.knownSizeDescriptorScannedBytes += bytesConsumed;
24358
+ }
24359
+ if (!shouldBuffer) {
24360
+ return;
24361
+ }
24362
+ return mergeByteChunks(chunks, bytesConsumed);
24363
+ }
24364
+ function getRemainingZipScanBudget(zipHandler, startOffset) {
24365
+ if (hasUnknownFileSize(zipHandler.tokenizer)) {
24366
+ return Math.max(0, maximumUntrustedSkipSizeInBytes - (zipHandler.tokenizer.position - startOffset));
24367
+ }
24368
+ return Math.max(0, maximumZipEntrySizeInBytes - zipHandler.knownSizeDescriptorScannedBytes);
24369
+ }
24370
+ async function readZipEntryData(zipHandler, zipHeader, { shouldBuffer, maximumDescriptorLength = maximumZipEntrySizeInBytes } = {}) {
24371
+ if (zipHeader.dataDescriptor && zipHeader.compressedSize === 0) {
24372
+ return readZipDataDescriptorEntryWithLimit(zipHandler, {
24373
+ shouldBuffer,
24374
+ maximumLength: maximumDescriptorLength
24375
+ });
24376
+ }
24377
+ if (!shouldBuffer) {
24378
+ await safeIgnore(zipHandler.tokenizer, zipHeader.compressedSize, {
24379
+ maximumLength: hasUnknownFileSize(zipHandler.tokenizer) ? maximumZipEntrySizeInBytes : zipHandler.tokenizer.fileInfo.size,
24380
+ reason: "ZIP entry compressed data"
24381
+ });
24382
+ return;
24383
+ }
24384
+ const maximumLength = getMaximumZipBufferedReadLength(zipHandler.tokenizer);
24385
+ if (!Number.isFinite(zipHeader.compressedSize) || zipHeader.compressedSize < 0 || zipHeader.compressedSize > maximumLength) {
24386
+ throw new Error(`ZIP entry compressed data exceeds ${maximumLength} bytes`);
24387
+ }
24388
+ const fileData = new Uint8Array(zipHeader.compressedSize);
24389
+ await zipHandler.tokenizer.readBuffer(fileData);
24390
+ return fileData;
24391
+ }
24392
+ function createByteLimitedReadableStream(stream, maximumBytes) {
24393
+ const reader = stream.getReader();
24394
+ let emittedBytes = 0;
24395
+ let sourceDone = false;
24396
+ let sourceCanceled = false;
24397
+ const cancelSource = async (reason) => {
24398
+ if (sourceDone || sourceCanceled) {
24399
+ return;
24400
+ }
24401
+ sourceCanceled = true;
24402
+ await reader.cancel(reason);
24403
+ };
24404
+ return new ReadableStream({
24405
+ async pull(controller) {
24406
+ if (emittedBytes >= maximumBytes) {
24407
+ controller.close();
24408
+ await cancelSource();
24409
+ return;
24410
+ }
24411
+ const { done, value } = await reader.read();
24412
+ if (done || !value) {
24413
+ sourceDone = true;
24414
+ controller.close();
24415
+ return;
24416
+ }
24417
+ const remainingBytes = maximumBytes - emittedBytes;
24418
+ if (value.length > remainingBytes) {
24419
+ controller.enqueue(value.subarray(0, remainingBytes));
24420
+ emittedBytes += remainingBytes;
24421
+ controller.close();
24422
+ await cancelSource();
24423
+ return;
24424
+ }
24425
+ controller.enqueue(value);
24426
+ emittedBytes += value.length;
24427
+ },
24428
+ async cancel(reason) {
24429
+ await cancelSource(reason);
24430
+ }
24431
+ });
24432
+ }
24146
24433
  async function fileTypeFromBuffer(input, options) {
24147
24434
  return new FileTypeParser(options).fromBuffer(input);
24148
24435
  }
@@ -24296,29 +24583,178 @@ function _check(buffer, headers, options) {
24296
24583
  }
24297
24584
  return true;
24298
24585
  }
24586
+ function normalizeSampleSize(sampleSize) {
24587
+ if (!Number.isFinite(sampleSize)) {
24588
+ return reasonableDetectionSizeInBytes;
24589
+ }
24590
+ return Math.max(1, Math.trunc(sampleSize));
24591
+ }
24592
+ function normalizeMpegOffsetTolerance(mpegOffsetTolerance) {
24593
+ if (!Number.isFinite(mpegOffsetTolerance)) {
24594
+ return 0;
24595
+ }
24596
+ return Math.max(0, Math.min(maximumMpegOffsetTolerance, Math.trunc(mpegOffsetTolerance)));
24597
+ }
24598
+ function getKnownFileSizeOrMaximum(fileSize) {
24599
+ if (!Number.isFinite(fileSize)) {
24600
+ return Number.MAX_SAFE_INTEGER;
24601
+ }
24602
+ return Math.max(0, fileSize);
24603
+ }
24604
+ function hasUnknownFileSize(tokenizer) {
24605
+ const fileSize = tokenizer.fileInfo.size;
24606
+ return !Number.isFinite(fileSize) || fileSize === Number.MAX_SAFE_INTEGER;
24607
+ }
24608
+ function hasExceededUnknownSizeScanBudget(tokenizer, startOffset, maximumBytes) {
24609
+ return hasUnknownFileSize(tokenizer) && tokenizer.position - startOffset > maximumBytes;
24610
+ }
24611
+ function getMaximumZipBufferedReadLength(tokenizer) {
24612
+ const fileSize = tokenizer.fileInfo.size;
24613
+ const remainingBytes = Number.isFinite(fileSize) ? Math.max(0, fileSize - tokenizer.position) : Number.MAX_SAFE_INTEGER;
24614
+ return Math.min(remainingBytes, maximumZipBufferedReadSizeInBytes);
24615
+ }
24616
+ function isRecoverableZipError(error) {
24617
+ if (error instanceof EndOfStreamError) {
24618
+ return true;
24619
+ }
24620
+ if (error instanceof ParserHardLimitError) {
24621
+ return true;
24622
+ }
24623
+ if (!(error instanceof Error)) {
24624
+ return false;
24625
+ }
24626
+ if (recoverableZipErrorMessages.has(error.message)) {
24627
+ return true;
24628
+ }
24629
+ if (recoverableZipErrorCodes.has(error.code)) {
24630
+ return true;
24631
+ }
24632
+ for (const prefix of recoverableZipErrorMessagePrefixes) {
24633
+ if (error.message.startsWith(prefix)) {
24634
+ return true;
24635
+ }
24636
+ }
24637
+ return false;
24638
+ }
24639
+ function canReadZipEntryForDetection(zipHeader, maximumSize = maximumZipEntrySizeInBytes) {
24640
+ const sizes = [zipHeader.compressedSize, zipHeader.uncompressedSize];
24641
+ for (const size of sizes) {
24642
+ if (!Number.isFinite(size) || size < 0 || size > maximumSize) {
24643
+ return false;
24644
+ }
24645
+ }
24646
+ return true;
24647
+ }
24648
+ function createOpenXmlZipDetectionState() {
24649
+ return {
24650
+ hasContentTypesEntry: false,
24651
+ hasParsedContentTypesEntry: false,
24652
+ isParsingContentTypes: false,
24653
+ hasUnparseableContentTypes: false,
24654
+ hasWordDirectory: false,
24655
+ hasPresentationDirectory: false,
24656
+ hasSpreadsheetDirectory: false,
24657
+ hasThreeDimensionalModelEntry: false
24658
+ };
24659
+ }
24660
+ function updateOpenXmlZipDetectionStateFromFilename(openXmlState, filename) {
24661
+ if (filename.startsWith("word/")) {
24662
+ openXmlState.hasWordDirectory = true;
24663
+ }
24664
+ if (filename.startsWith("ppt/")) {
24665
+ openXmlState.hasPresentationDirectory = true;
24666
+ }
24667
+ if (filename.startsWith("xl/")) {
24668
+ openXmlState.hasSpreadsheetDirectory = true;
24669
+ }
24670
+ if (filename.startsWith("3D/") && filename.endsWith(".model")) {
24671
+ openXmlState.hasThreeDimensionalModelEntry = true;
24672
+ }
24673
+ }
24674
+ function getOpenXmlFileTypeFromZipEntries(openXmlState) {
24675
+ if (!openXmlState.hasContentTypesEntry || openXmlState.hasUnparseableContentTypes || openXmlState.isParsingContentTypes || openXmlState.hasParsedContentTypesEntry) {
24676
+ return;
24677
+ }
24678
+ if (openXmlState.hasWordDirectory) {
24679
+ return {
24680
+ ext: "docx",
24681
+ mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
24682
+ };
24683
+ }
24684
+ if (openXmlState.hasPresentationDirectory) {
24685
+ return {
24686
+ ext: "pptx",
24687
+ mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
24688
+ };
24689
+ }
24690
+ if (openXmlState.hasSpreadsheetDirectory) {
24691
+ return {
24692
+ ext: "xlsx",
24693
+ mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
24694
+ };
24695
+ }
24696
+ if (openXmlState.hasThreeDimensionalModelEntry) {
24697
+ return {
24698
+ ext: "3mf",
24699
+ mime: "model/3mf"
24700
+ };
24701
+ }
24702
+ }
24703
+ function getOpenXmlMimeTypeFromContentTypesXml(xmlContent) {
24704
+ const endPosition = xmlContent.indexOf('.main+xml"');
24705
+ if (endPosition === -1) {
24706
+ const mimeType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml";
24707
+ if (xmlContent.includes(`ContentType="${mimeType}"`)) {
24708
+ return mimeType;
24709
+ }
24710
+ return;
24711
+ }
24712
+ const truncatedContent = xmlContent.slice(0, endPosition);
24713
+ const firstQuotePosition = truncatedContent.lastIndexOf('"');
24714
+ return truncatedContent.slice(firstQuotePosition + 1);
24715
+ }
24299
24716
  async function fileTypeFromTokenizer(tokenizer, options) {
24300
24717
  return new FileTypeParser(options).fromTokenizer(tokenizer);
24301
24718
  }
24302
24719
 
24303
24720
  class FileTypeParser {
24304
24721
  constructor(options) {
24722
+ const normalizedMpegOffsetTolerance = normalizeMpegOffsetTolerance(options?.mpegOffsetTolerance);
24305
24723
  this.options = {
24306
- mpegOffsetTolerance: 0,
24307
- ...options
24724
+ ...options,
24725
+ mpegOffsetTolerance: normalizedMpegOffsetTolerance
24308
24726
  };
24309
24727
  this.detectors = [
24310
- ...options?.customDetectors ?? [],
24728
+ ...this.options.customDetectors ?? [],
24311
24729
  { id: "core", detect: this.detectConfident },
24312
24730
  { id: "core.imprecise", detect: this.detectImprecise }
24313
24731
  ];
24314
24732
  this.tokenizerOptions = {
24315
- abortSignal: options?.signal
24733
+ abortSignal: this.options.signal
24316
24734
  };
24735
+ this.gzipProbeDepth = 0;
24317
24736
  }
24318
- async fromTokenizer(tokenizer) {
24737
+ getTokenizerOptions() {
24738
+ return {
24739
+ ...this.tokenizerOptions
24740
+ };
24741
+ }
24742
+ async fromTokenizer(tokenizer, detectionReentryCount = 0) {
24743
+ this.detectionReentryCount = detectionReentryCount;
24319
24744
  const initialPosition = tokenizer.position;
24320
24745
  for (const detector of this.detectors) {
24321
- const fileType = await detector.detect(tokenizer);
24746
+ let fileType;
24747
+ try {
24748
+ fileType = await detector.detect(tokenizer);
24749
+ } catch (error) {
24750
+ if (error instanceof EndOfStreamError) {
24751
+ return;
24752
+ }
24753
+ if (error instanceof ParserHardLimitError) {
24754
+ return;
24755
+ }
24756
+ throw error;
24757
+ }
24322
24758
  if (fileType) {
24323
24759
  return fileType;
24324
24760
  }
@@ -24335,10 +24771,10 @@ class FileTypeParser {
24335
24771
  if (!(buffer?.length > 1)) {
24336
24772
  return;
24337
24773
  }
24338
- return this.fromTokenizer(fromBuffer(buffer, this.tokenizerOptions));
24774
+ return this.fromTokenizer(fromBuffer(buffer, this.getTokenizerOptions()));
24339
24775
  }
24340
24776
  async fromBlob(blob) {
24341
- const tokenizer = fromBlob(blob, this.tokenizerOptions);
24777
+ const tokenizer = fromBlob(blob, this.getTokenizerOptions());
24342
24778
  try {
24343
24779
  return await this.fromTokenizer(tokenizer);
24344
24780
  } finally {
@@ -24346,7 +24782,7 @@ class FileTypeParser {
24346
24782
  }
24347
24783
  }
24348
24784
  async fromStream(stream) {
24349
- const tokenizer = fromWebStream(stream, this.tokenizerOptions);
24785
+ const tokenizer = fromWebStream(stream, this.getTokenizerOptions());
24350
24786
  try {
24351
24787
  return await this.fromTokenizer(tokenizer);
24352
24788
  } finally {
@@ -24354,7 +24790,7 @@ class FileTypeParser {
24354
24790
  }
24355
24791
  }
24356
24792
  async toDetectionStream(stream, options) {
24357
- const { sampleSize = reasonableDetectionSizeInBytes } = options;
24793
+ const sampleSize = normalizeSampleSize(options?.sampleSize ?? reasonableDetectionSizeInBytes);
24358
24794
  let detectedFileType;
24359
24795
  let firstChunk;
24360
24796
  const reader = stream.getReader({ mode: "byob" });
@@ -24456,7 +24892,11 @@ class FileTypeParser {
24456
24892
  };
24457
24893
  }
24458
24894
  if (this.check([239, 187, 191])) {
24459
- this.tokenizer.ignore(3);
24895
+ if (this.detectionReentryCount >= maximumDetectionReentryCount) {
24896
+ return;
24897
+ }
24898
+ this.detectionReentryCount++;
24899
+ await this.tokenizer.ignore(3);
24460
24900
  return this.detectConfident(tokenizer);
24461
24901
  }
24462
24902
  if (this.check([71, 73, 70])) {
@@ -24472,26 +24912,30 @@ class FileTypeParser {
24472
24912
  };
24473
24913
  }
24474
24914
  if (this.check([31, 139, 8])) {
24915
+ if (this.gzipProbeDepth >= maximumNestedGzipProbeDepth) {
24916
+ return {
24917
+ ext: "gz",
24918
+ mime: "application/gzip"
24919
+ };
24920
+ }
24475
24921
  const gzipHandler = new GzipHandler(tokenizer);
24476
- const stream = gzipHandler.inflate();
24477
- let shouldCancelStream = true;
24922
+ const limitedInflatedStream = createByteLimitedReadableStream(gzipHandler.inflate(), maximumNestedGzipDetectionSizeInBytes);
24923
+ let compressedFileType;
24478
24924
  try {
24479
- let compressedFileType;
24480
- try {
24481
- compressedFileType = await this.fromStream(stream);
24482
- } catch {
24483
- shouldCancelStream = false;
24484
- }
24485
- if (compressedFileType && compressedFileType.ext === "tar") {
24486
- return {
24487
- ext: "tar.gz",
24488
- mime: "application/gzip"
24489
- };
24925
+ this.gzipProbeDepth++;
24926
+ compressedFileType = await this.fromStream(limitedInflatedStream);
24927
+ } catch (error) {
24928
+ if (error?.name === "AbortError") {
24929
+ throw error;
24490
24930
  }
24491
24931
  } finally {
24492
- if (shouldCancelStream) {
24493
- await stream.cancel();
24494
- }
24932
+ this.gzipProbeDepth--;
24933
+ }
24934
+ if (compressedFileType?.ext === "tar") {
24935
+ return {
24936
+ ext: "tar.gz",
24937
+ mime: "application/gzip"
24938
+ };
24495
24939
  }
24496
24940
  return {
24497
24941
  ext: "gz",
@@ -24505,16 +24949,40 @@ class FileTypeParser {
24505
24949
  };
24506
24950
  }
24507
24951
  if (this.checkString("ID3")) {
24508
- await tokenizer.ignore(6);
24952
+ await safeIgnore(tokenizer, 6, {
24953
+ maximumLength: 6,
24954
+ reason: "ID3 header prefix"
24955
+ });
24509
24956
  const id3HeaderLength = await tokenizer.readToken(uint32SyncSafeToken);
24957
+ const isUnknownFileSize = hasUnknownFileSize(tokenizer);
24958
+ if (!Number.isFinite(id3HeaderLength) || id3HeaderLength < 0 || isUnknownFileSize && (id3HeaderLength > maximumId3HeaderSizeInBytes || tokenizer.position + id3HeaderLength > maximumId3HeaderSizeInBytes)) {
24959
+ return;
24960
+ }
24510
24961
  if (tokenizer.position + id3HeaderLength > tokenizer.fileInfo.size) {
24962
+ if (isUnknownFileSize) {
24963
+ return;
24964
+ }
24511
24965
  return {
24512
24966
  ext: "mp3",
24513
24967
  mime: "audio/mpeg"
24514
24968
  };
24515
24969
  }
24516
- await tokenizer.ignore(id3HeaderLength);
24517
- return this.fromTokenizer(tokenizer);
24970
+ try {
24971
+ await safeIgnore(tokenizer, id3HeaderLength, {
24972
+ maximumLength: isUnknownFileSize ? maximumId3HeaderSizeInBytes : tokenizer.fileInfo.size,
24973
+ reason: "ID3 payload"
24974
+ });
24975
+ } catch (error) {
24976
+ if (error instanceof EndOfStreamError) {
24977
+ return;
24978
+ }
24979
+ throw error;
24980
+ }
24981
+ if (this.detectionReentryCount >= maximumDetectionReentryCount) {
24982
+ return;
24983
+ }
24984
+ this.detectionReentryCount++;
24985
+ return this.fromTokenizer(tokenizer, this.detectionReentryCount);
24518
24986
  }
24519
24987
  if (this.checkString("MP+")) {
24520
24988
  return {
@@ -24578,67 +25046,87 @@ class FileTypeParser {
24578
25046
  }
24579
25047
  if (this.check([80, 75, 3, 4])) {
24580
25048
  let fileType;
24581
- await new ZipHandler(tokenizer).unzip((zipHeader) => {
24582
- switch (zipHeader.filename) {
24583
- case "META-INF/mozilla.rsa":
24584
- fileType = {
24585
- ext: "xpi",
24586
- mime: "application/x-xpinstall"
24587
- };
24588
- return {
24589
- stop: true
24590
- };
24591
- case "META-INF/MANIFEST.MF":
24592
- fileType = {
24593
- ext: "jar",
24594
- mime: "application/java-archive"
24595
- };
24596
- return {
24597
- stop: true
24598
- };
24599
- case "mimetype":
25049
+ const openXmlState = createOpenXmlZipDetectionState();
25050
+ try {
25051
+ await new ZipHandler(tokenizer).unzip((zipHeader) => {
25052
+ updateOpenXmlZipDetectionStateFromFilename(openXmlState, zipHeader.filename);
25053
+ const isOpenXmlContentTypesEntry = zipHeader.filename === "[Content_Types].xml";
25054
+ const openXmlFileTypeFromEntries = getOpenXmlFileTypeFromZipEntries(openXmlState);
25055
+ if (!isOpenXmlContentTypesEntry && openXmlFileTypeFromEntries) {
25056
+ fileType = openXmlFileTypeFromEntries;
24600
25057
  return {
24601
- async handler(fileData) {
24602
- const mimeType = new TextDecoder("utf-8").decode(fileData).trim();
24603
- fileType = getFileTypeFromMimeType(mimeType);
24604
- },
24605
25058
  stop: true
24606
25059
  };
24607
- case "[Content_Types].xml":
24608
- return {
24609
- async handler(fileData) {
24610
- let xmlContent = new TextDecoder("utf-8").decode(fileData);
24611
- const endPos = xmlContent.indexOf('.main+xml"');
24612
- if (endPos === -1) {
24613
- const mimeType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml";
24614
- if (xmlContent.includes(`ContentType="${mimeType}"`)) {
25060
+ }
25061
+ switch (zipHeader.filename) {
25062
+ case "META-INF/mozilla.rsa":
25063
+ fileType = {
25064
+ ext: "xpi",
25065
+ mime: "application/x-xpinstall"
25066
+ };
25067
+ return {
25068
+ stop: true
25069
+ };
25070
+ case "META-INF/MANIFEST.MF":
25071
+ fileType = {
25072
+ ext: "jar",
25073
+ mime: "application/java-archive"
25074
+ };
25075
+ return {
25076
+ stop: true
25077
+ };
25078
+ case "mimetype":
25079
+ if (!canReadZipEntryForDetection(zipHeader, maximumZipTextEntrySizeInBytes)) {
25080
+ return {};
25081
+ }
25082
+ return {
25083
+ async handler(fileData) {
25084
+ const mimeType = new TextDecoder("utf-8").decode(fileData).trim();
25085
+ fileType = getFileTypeFromMimeType(mimeType);
25086
+ },
25087
+ stop: true
25088
+ };
25089
+ case "[Content_Types].xml": {
25090
+ openXmlState.hasContentTypesEntry = true;
25091
+ if (!canReadZipEntryForDetection(zipHeader, maximumZipTextEntrySizeInBytes)) {
25092
+ openXmlState.hasUnparseableContentTypes = true;
25093
+ return {};
25094
+ }
25095
+ openXmlState.isParsingContentTypes = true;
25096
+ return {
25097
+ async handler(fileData) {
25098
+ const xmlContent = new TextDecoder("utf-8").decode(fileData);
25099
+ const mimeType = getOpenXmlMimeTypeFromContentTypesXml(xmlContent);
25100
+ if (mimeType) {
24615
25101
  fileType = getFileTypeFromMimeType(mimeType);
24616
25102
  }
24617
- } else {
24618
- xmlContent = xmlContent.slice(0, Math.max(0, endPos));
24619
- const firstPos = xmlContent.lastIndexOf('"');
24620
- const mimeType = xmlContent.slice(Math.max(0, firstPos + 1));
24621
- fileType = getFileTypeFromMimeType(mimeType);
24622
- }
24623
- },
24624
- stop: true
24625
- };
24626
- default:
24627
- if (/classes\d*\.dex/.test(zipHeader.filename)) {
24628
- fileType = {
24629
- ext: "apk",
24630
- mime: "application/vnd.android.package-archive"
25103
+ openXmlState.hasParsedContentTypesEntry = true;
25104
+ openXmlState.isParsingContentTypes = false;
25105
+ },
25106
+ stop: true
24631
25107
  };
24632
- return { stop: true };
24633
25108
  }
24634
- return {};
24635
- }
24636
- }).catch((error) => {
24637
- if (!(error instanceof EndOfStreamError)) {
25109
+ default:
25110
+ if (/classes\d*\.dex/.test(zipHeader.filename)) {
25111
+ fileType = {
25112
+ ext: "apk",
25113
+ mime: "application/vnd.android.package-archive"
25114
+ };
25115
+ return { stop: true };
25116
+ }
25117
+ return {};
25118
+ }
25119
+ });
25120
+ } catch (error) {
25121
+ if (!isRecoverableZipError(error)) {
24638
25122
  throw error;
24639
25123
  }
24640
- });
24641
- return fileType ?? {
25124
+ if (openXmlState.isParsingContentTypes) {
25125
+ openXmlState.isParsingContentTypes = false;
25126
+ openXmlState.hasUnparseableContentTypes = true;
25127
+ }
25128
+ }
25129
+ return fileType ?? getOpenXmlFileTypeFromZipEntries(openXmlState) ?? {
24642
25130
  ext: "zip",
24643
25131
  mime: "application/zip"
24644
25132
  };
@@ -24788,7 +25276,10 @@ class FileTypeParser {
24788
25276
  mask >>= 1;
24789
25277
  }
24790
25278
  const id = new Uint8Array(ic + 1);
24791
- await tokenizer.readBuffer(id);
25279
+ await safeReadBuffer(tokenizer, id, undefined, {
25280
+ maximumLength: id.length,
25281
+ reason: "EBML field"
25282
+ });
24792
25283
  return id;
24793
25284
  }
24794
25285
  async function readElement() {
@@ -24804,18 +25295,41 @@ class FileTypeParser {
24804
25295
  };
24805
25296
  }
24806
25297
  async function readChildren(children) {
25298
+ let ebmlElementCount = 0;
24807
25299
  while (children > 0) {
25300
+ ebmlElementCount++;
25301
+ if (ebmlElementCount > maximumEbmlElementCount) {
25302
+ return;
25303
+ }
25304
+ if (hasExceededUnknownSizeScanBudget(tokenizer, ebmlScanStart, maximumUntrustedSkipSizeInBytes)) {
25305
+ return;
25306
+ }
25307
+ const previousPosition = tokenizer.position;
24808
25308
  const element = await readElement();
24809
25309
  if (element.id === 17026) {
24810
- const rawValue = await tokenizer.readToken(new StringType2(element.len));
25310
+ if (element.len > maximumEbmlDocumentTypeSizeInBytes) {
25311
+ return;
25312
+ }
25313
+ const documentTypeLength = getSafeBound(element.len, maximumEbmlDocumentTypeSizeInBytes, "EBML DocType");
25314
+ const rawValue = await tokenizer.readToken(new StringType2(documentTypeLength));
24811
25315
  return rawValue.replaceAll(/\00.*$/g, "");
24812
25316
  }
24813
- await tokenizer.ignore(element.len);
25317
+ if (hasUnknownFileSize(tokenizer) && (!Number.isFinite(element.len) || element.len < 0 || element.len > maximumEbmlElementPayloadSizeInBytes)) {
25318
+ return;
25319
+ }
25320
+ await safeIgnore(tokenizer, element.len, {
25321
+ maximumLength: hasUnknownFileSize(tokenizer) ? maximumEbmlElementPayloadSizeInBytes : tokenizer.fileInfo.size,
25322
+ reason: "EBML payload"
25323
+ });
24814
25324
  --children;
25325
+ if (tokenizer.position <= previousPosition) {
25326
+ return;
25327
+ }
24815
25328
  }
24816
25329
  }
24817
- const re = await readElement();
24818
- const documentType = await readChildren(re.len);
25330
+ const rootElement = await readElement();
25331
+ const ebmlScanStart = tokenizer.position;
25332
+ const documentType = await readChildren(rootElement.len);
24819
25333
  switch (documentType) {
24820
25334
  case "webm":
24821
25335
  return {
@@ -25077,6 +25591,14 @@ class FileTypeParser {
25077
25591
  };
25078
25592
  }
25079
25593
  if (this.check([137, 80, 78, 71, 13, 10, 26, 10])) {
25594
+ const pngFileType = {
25595
+ ext: "png",
25596
+ mime: "image/png"
25597
+ };
25598
+ const apngFileType = {
25599
+ ext: "apng",
25600
+ mime: "image/apng"
25601
+ };
25080
25602
  await tokenizer.ignore(8);
25081
25603
  async function readChunkHeader() {
25082
25604
  return {
@@ -25084,30 +25606,58 @@ class FileTypeParser {
25084
25606
  type: await tokenizer.readToken(new StringType2(4, "latin1"))
25085
25607
  };
25086
25608
  }
25609
+ const isUnknownPngStream = hasUnknownFileSize(tokenizer);
25610
+ const pngScanStart = tokenizer.position;
25611
+ let pngChunkCount = 0;
25612
+ let hasSeenImageHeader = false;
25087
25613
  do {
25614
+ pngChunkCount++;
25615
+ if (pngChunkCount > maximumPngChunkCount) {
25616
+ break;
25617
+ }
25618
+ if (hasExceededUnknownSizeScanBudget(tokenizer, pngScanStart, maximumPngStreamScanBudgetInBytes)) {
25619
+ break;
25620
+ }
25621
+ const previousPosition = tokenizer.position;
25088
25622
  const chunk = await readChunkHeader();
25089
25623
  if (chunk.length < 0) {
25090
25624
  return;
25091
25625
  }
25626
+ if (chunk.type === "IHDR") {
25627
+ if (chunk.length !== 13) {
25628
+ return;
25629
+ }
25630
+ hasSeenImageHeader = true;
25631
+ }
25092
25632
  switch (chunk.type) {
25093
25633
  case "IDAT":
25094
- return {
25095
- ext: "png",
25096
- mime: "image/png"
25097
- };
25634
+ return pngFileType;
25098
25635
  case "acTL":
25099
- return {
25100
- ext: "apng",
25101
- mime: "image/apng"
25102
- };
25636
+ return apngFileType;
25103
25637
  default:
25104
- await tokenizer.ignore(chunk.length + 4);
25638
+ if (!hasSeenImageHeader && chunk.type !== "CgBI") {
25639
+ return;
25640
+ }
25641
+ if (isUnknownPngStream && chunk.length > maximumPngChunkSizeInBytes) {
25642
+ return hasSeenImageHeader && isPngAncillaryChunk(chunk.type) ? pngFileType : undefined;
25643
+ }
25644
+ try {
25645
+ await safeIgnore(tokenizer, chunk.length + 4, {
25646
+ maximumLength: isUnknownPngStream ? maximumPngChunkSizeInBytes + 4 : tokenizer.fileInfo.size,
25647
+ reason: "PNG chunk payload"
25648
+ });
25649
+ } catch (error) {
25650
+ if (!isUnknownPngStream && (error instanceof ParserHardLimitError || error instanceof EndOfStreamError)) {
25651
+ return pngFileType;
25652
+ }
25653
+ throw error;
25654
+ }
25655
+ }
25656
+ if (tokenizer.position <= previousPosition) {
25657
+ break;
25105
25658
  }
25106
25659
  } while (tokenizer.position + 8 < tokenizer.fileInfo.size);
25107
- return {
25108
- ext: "png",
25109
- mime: "image/png"
25110
- };
25660
+ return pngFileType;
25111
25661
  }
25112
25662
  if (this.check([65, 82, 82, 79, 87, 49, 0, 0])) {
25113
25663
  return {
@@ -25226,36 +25776,85 @@ class FileTypeParser {
25226
25776
  };
25227
25777
  }
25228
25778
  if (this.check([48, 38, 178, 117, 142, 102, 207, 17, 166, 217])) {
25229
- async function readHeader() {
25230
- const guid = new Uint8Array(16);
25231
- await tokenizer.readBuffer(guid);
25232
- return {
25233
- id: guid,
25234
- size: Number(await tokenizer.readToken(UINT64_LE))
25235
- };
25236
- }
25237
- await tokenizer.ignore(30);
25238
- while (tokenizer.position + 24 < tokenizer.fileInfo.size) {
25239
- const header = await readHeader();
25240
- let payload = header.size - 24;
25241
- if (_check(header.id, [145, 7, 220, 183, 183, 169, 207, 17, 142, 230, 0, 192, 12, 32, 83, 101])) {
25242
- const typeId = new Uint8Array(16);
25243
- payload -= await tokenizer.readBuffer(typeId);
25244
- if (_check(typeId, [64, 158, 105, 248, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
25245
- return {
25246
- ext: "asf",
25247
- mime: "audio/x-ms-asf"
25248
- };
25779
+ let isMalformedAsf = false;
25780
+ try {
25781
+ async function readHeader() {
25782
+ const guid = new Uint8Array(16);
25783
+ await safeReadBuffer(tokenizer, guid, undefined, {
25784
+ maximumLength: guid.length,
25785
+ reason: "ASF header GUID"
25786
+ });
25787
+ return {
25788
+ id: guid,
25789
+ size: Number(await tokenizer.readToken(UINT64_LE))
25790
+ };
25791
+ }
25792
+ await safeIgnore(tokenizer, 30, {
25793
+ maximumLength: 30,
25794
+ reason: "ASF header prelude"
25795
+ });
25796
+ const isUnknownFileSize = hasUnknownFileSize(tokenizer);
25797
+ const asfHeaderScanStart = tokenizer.position;
25798
+ let asfHeaderObjectCount = 0;
25799
+ while (tokenizer.position + 24 < tokenizer.fileInfo.size) {
25800
+ asfHeaderObjectCount++;
25801
+ if (asfHeaderObjectCount > maximumAsfHeaderObjectCount) {
25802
+ break;
25249
25803
  }
25250
- if (_check(typeId, [192, 239, 25, 188, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
25251
- return {
25252
- ext: "asf",
25253
- mime: "video/x-ms-asf"
25254
- };
25804
+ if (hasExceededUnknownSizeScanBudget(tokenizer, asfHeaderScanStart, maximumUntrustedSkipSizeInBytes)) {
25805
+ break;
25806
+ }
25807
+ const previousPosition = tokenizer.position;
25808
+ const header = await readHeader();
25809
+ let payload = header.size - 24;
25810
+ if (!Number.isFinite(payload) || payload < 0) {
25811
+ isMalformedAsf = true;
25812
+ break;
25813
+ }
25814
+ if (_check(header.id, [145, 7, 220, 183, 183, 169, 207, 17, 142, 230, 0, 192, 12, 32, 83, 101])) {
25815
+ const typeId = new Uint8Array(16);
25816
+ payload -= await safeReadBuffer(tokenizer, typeId, undefined, {
25817
+ maximumLength: typeId.length,
25818
+ reason: "ASF stream type GUID"
25819
+ });
25820
+ if (_check(typeId, [64, 158, 105, 248, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
25821
+ return {
25822
+ ext: "asf",
25823
+ mime: "audio/x-ms-asf"
25824
+ };
25825
+ }
25826
+ if (_check(typeId, [192, 239, 25, 188, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) {
25827
+ return {
25828
+ ext: "asf",
25829
+ mime: "video/x-ms-asf"
25830
+ };
25831
+ }
25832
+ break;
25833
+ }
25834
+ if (isUnknownFileSize && payload > maximumAsfHeaderPayloadSizeInBytes) {
25835
+ isMalformedAsf = true;
25836
+ break;
25837
+ }
25838
+ await safeIgnore(tokenizer, payload, {
25839
+ maximumLength: isUnknownFileSize ? maximumAsfHeaderPayloadSizeInBytes : tokenizer.fileInfo.size,
25840
+ reason: "ASF header payload"
25841
+ });
25842
+ if (tokenizer.position <= previousPosition) {
25843
+ isMalformedAsf = true;
25844
+ break;
25255
25845
  }
25256
- break;
25257
25846
  }
25258
- await tokenizer.ignore(payload);
25847
+ } catch (error) {
25848
+ if (error instanceof EndOfStreamError || error instanceof ParserHardLimitError) {
25849
+ if (hasUnknownFileSize(tokenizer)) {
25850
+ isMalformedAsf = true;
25851
+ }
25852
+ } else {
25853
+ throw error;
25854
+ }
25855
+ }
25856
+ if (isMalformedAsf) {
25857
+ return;
25259
25858
  }
25260
25859
  return {
25261
25860
  ext: "asf",
@@ -25506,7 +26105,8 @@ class FileTypeParser {
25506
26105
  };
25507
26106
  detectImprecise = async (tokenizer) => {
25508
26107
  this.buffer = new Uint8Array(reasonableDetectionSizeInBytes);
25509
- await tokenizer.peekBuffer(this.buffer, { length: Math.min(8, tokenizer.fileInfo.size), mayBeLess: true });
26108
+ const fileSize = getKnownFileSizeOrMaximum(tokenizer.fileInfo.size);
26109
+ await tokenizer.peekBuffer(this.buffer, { length: Math.min(8, fileSize), mayBeLess: true });
25510
26110
  if (this.check([0, 0, 1, 186]) || this.check([0, 0, 1, 179])) {
25511
26111
  return {
25512
26112
  ext: "mpg",
@@ -25531,7 +26131,7 @@ class FileTypeParser {
25531
26131
  mime: "image/x-icon"
25532
26132
  };
25533
26133
  }
25534
- await tokenizer.peekBuffer(this.buffer, { length: Math.min(2 + this.options.mpegOffsetTolerance, tokenizer.fileInfo.size), mayBeLess: true });
26134
+ await tokenizer.peekBuffer(this.buffer, { length: Math.min(2 + this.options.mpegOffsetTolerance, fileSize), mayBeLess: true });
25535
26135
  if (this.buffer.length >= 2 + this.options.mpegOffsetTolerance) {
25536
26136
  for (let depth = 0;depth <= this.options.mpegOffsetTolerance; ++depth) {
25537
26137
  const type = this.scanMpeg(depth);
@@ -25543,7 +26143,7 @@ class FileTypeParser {
25543
26143
  };
25544
26144
  async readTiffTag(bigEndian) {
25545
26145
  const tagId = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
25546
- this.tokenizer.ignore(10);
26146
+ await this.tokenizer.ignore(10);
25547
26147
  switch (tagId) {
25548
26148
  case 50341:
25549
26149
  return {
@@ -25560,6 +26160,12 @@ class FileTypeParser {
25560
26160
  }
25561
26161
  async readTiffIFD(bigEndian) {
25562
26162
  const numberOfTags = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE);
26163
+ if (numberOfTags > maximumTiffTagCount) {
26164
+ return;
26165
+ }
26166
+ if (hasUnknownFileSize(this.tokenizer) && 2 + numberOfTags * 12 > maximumTiffIfdOffsetInBytes) {
26167
+ return;
26168
+ }
25563
26169
  for (let n = 0;n < numberOfTags; ++n) {
25564
26170
  const fileType = await this.readTiffTag(bigEndian);
25565
26171
  if (fileType) {
@@ -25568,6 +26174,10 @@ class FileTypeParser {
25568
26174
  }
25569
26175
  }
25570
26176
  async readTiffHeader(bigEndian) {
26177
+ const tiffFileType = {
26178
+ ext: "tif",
26179
+ mime: "image/tiff"
26180
+ };
25571
26181
  const version = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 2);
25572
26182
  const ifdOffset = (bigEndian ? UINT32_BE : UINT32_LE).get(this.buffer, 4);
25573
26183
  if (version === 42) {
@@ -25589,18 +26199,34 @@ class FileTypeParser {
25589
26199
  }
25590
26200
  }
25591
26201
  }
25592
- await this.tokenizer.ignore(ifdOffset);
25593
- const fileType = await this.readTiffIFD(bigEndian);
25594
- return fileType ?? {
25595
- ext: "tif",
25596
- mime: "image/tiff"
25597
- };
26202
+ if (hasUnknownFileSize(this.tokenizer) && ifdOffset > maximumTiffStreamIfdOffsetInBytes) {
26203
+ return tiffFileType;
26204
+ }
26205
+ const maximumTiffOffset = hasUnknownFileSize(this.tokenizer) ? maximumTiffIfdOffsetInBytes : this.tokenizer.fileInfo.size;
26206
+ try {
26207
+ await safeIgnore(this.tokenizer, ifdOffset, {
26208
+ maximumLength: maximumTiffOffset,
26209
+ reason: "TIFF IFD offset"
26210
+ });
26211
+ } catch (error) {
26212
+ if (error instanceof EndOfStreamError) {
26213
+ return;
26214
+ }
26215
+ throw error;
26216
+ }
26217
+ let fileType;
26218
+ try {
26219
+ fileType = await this.readTiffIFD(bigEndian);
26220
+ } catch (error) {
26221
+ if (error instanceof EndOfStreamError) {
26222
+ return;
26223
+ }
26224
+ throw error;
26225
+ }
26226
+ return fileType ?? tiffFileType;
25598
26227
  }
25599
26228
  if (version === 43) {
25600
- return {
25601
- ext: "tif",
25602
- mime: "image/tiff"
25603
- };
26229
+ return tiffFileType;
25604
26230
  }
25605
26231
  }
25606
26232
  scanMpeg(offset) {
@@ -25638,7 +26264,7 @@ class FileTypeParser {
25638
26264
  }
25639
26265
  }
25640
26266
  }
25641
- var reasonableDetectionSizeInBytes = 4100, supportedExtensions, supportedMimeTypes;
26267
+ var reasonableDetectionSizeInBytes = 4100, maximumMpegOffsetTolerance, maximumZipEntrySizeInBytes, maximumZipEntryCount = 1024, maximumZipBufferedReadSizeInBytes, maximumUntrustedSkipSizeInBytes, maximumUnknownSizePayloadProbeSizeInBytes, maximumZipTextEntrySizeInBytes, maximumNestedGzipDetectionSizeInBytes, maximumNestedGzipProbeDepth = 1, maximumId3HeaderSizeInBytes, maximumEbmlDocumentTypeSizeInBytes = 64, maximumEbmlElementPayloadSizeInBytes, maximumEbmlElementCount = 256, maximumPngChunkCount = 512, maximumPngStreamScanBudgetInBytes, maximumAsfHeaderObjectCount = 512, maximumTiffTagCount = 512, maximumDetectionReentryCount = 256, maximumPngChunkSizeInBytes, maximumAsfHeaderPayloadSizeInBytes, maximumTiffStreamIfdOffsetInBytes, maximumTiffIfdOffsetInBytes, recoverableZipErrorMessages, recoverableZipErrorMessagePrefixes, recoverableZipErrorCodes, ParserHardLimitError, zipDataDescriptorSignature = 134695760, zipDataDescriptorLengthInBytes = 16, zipDataDescriptorOverlapLengthInBytes, supportedExtensions, supportedMimeTypes;
25642
26268
  var init_core2 = __esm(() => {
25643
26269
  init_lib3();
25644
26270
  init_core();
@@ -25646,6 +26272,88 @@ var init_core2 = __esm(() => {
25646
26272
  init_uint8array_extras();
25647
26273
  init_util();
25648
26274
  init_supported();
26275
+ maximumMpegOffsetTolerance = reasonableDetectionSizeInBytes - 2;
26276
+ maximumZipEntrySizeInBytes = 1024 * 1024;
26277
+ maximumZipBufferedReadSizeInBytes = 2 ** 31 - 1;
26278
+ maximumUntrustedSkipSizeInBytes = 16 * 1024 * 1024;
26279
+ maximumUnknownSizePayloadProbeSizeInBytes = maximumZipEntrySizeInBytes;
26280
+ maximumZipTextEntrySizeInBytes = maximumZipEntrySizeInBytes;
26281
+ maximumNestedGzipDetectionSizeInBytes = maximumUntrustedSkipSizeInBytes;
26282
+ maximumId3HeaderSizeInBytes = maximumUntrustedSkipSizeInBytes;
26283
+ maximumEbmlElementPayloadSizeInBytes = maximumUnknownSizePayloadProbeSizeInBytes;
26284
+ maximumPngStreamScanBudgetInBytes = maximumUntrustedSkipSizeInBytes;
26285
+ maximumPngChunkSizeInBytes = maximumUnknownSizePayloadProbeSizeInBytes;
26286
+ maximumAsfHeaderPayloadSizeInBytes = maximumUnknownSizePayloadProbeSizeInBytes;
26287
+ maximumTiffStreamIfdOffsetInBytes = maximumUnknownSizePayloadProbeSizeInBytes;
26288
+ maximumTiffIfdOffsetInBytes = maximumUntrustedSkipSizeInBytes;
26289
+ recoverableZipErrorMessages = new Set([
26290
+ "Unexpected signature",
26291
+ "Encrypted ZIP",
26292
+ "Expected Central-File-Header signature"
26293
+ ]);
26294
+ recoverableZipErrorMessagePrefixes = [
26295
+ "ZIP entry count exceeds ",
26296
+ "Unsupported ZIP compression method:",
26297
+ "ZIP entry compressed data exceeds ",
26298
+ "ZIP entry decompressed data exceeds "
26299
+ ];
26300
+ recoverableZipErrorCodes = new Set([
26301
+ "Z_BUF_ERROR",
26302
+ "Z_DATA_ERROR",
26303
+ "ERR_INVALID_STATE"
26304
+ ]);
26305
+ ParserHardLimitError = class ParserHardLimitError extends Error {
26306
+ };
26307
+ zipDataDescriptorOverlapLengthInBytes = zipDataDescriptorLengthInBytes - 1;
26308
+ ZipHandler.prototype.inflate = async function(zipHeader, fileData, callback) {
26309
+ if (zipHeader.compressedMethod === 0) {
26310
+ return callback(fileData);
26311
+ }
26312
+ if (zipHeader.compressedMethod !== 8) {
26313
+ throw new Error(`Unsupported ZIP compression method: ${zipHeader.compressedMethod}`);
26314
+ }
26315
+ const uncompressedData = await decompressDeflateRawWithLimit(fileData, { maximumLength: maximumZipEntrySizeInBytes });
26316
+ return callback(uncompressedData);
26317
+ };
26318
+ ZipHandler.prototype.unzip = async function(fileCallback) {
26319
+ let stop = false;
26320
+ let zipEntryCount = 0;
26321
+ const zipScanStart = this.tokenizer.position;
26322
+ this.knownSizeDescriptorScannedBytes = 0;
26323
+ do {
26324
+ if (hasExceededUnknownSizeScanBudget(this.tokenizer, zipScanStart, maximumUntrustedSkipSizeInBytes)) {
26325
+ throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);
26326
+ }
26327
+ const zipHeader = await this.readLocalFileHeader();
26328
+ if (!zipHeader) {
26329
+ break;
26330
+ }
26331
+ zipEntryCount++;
26332
+ if (zipEntryCount > maximumZipEntryCount) {
26333
+ throw new Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);
26334
+ }
26335
+ const next = fileCallback(zipHeader);
26336
+ stop = Boolean(next.stop);
26337
+ await this.tokenizer.ignore(zipHeader.extraFieldLength);
26338
+ const fileData = await readZipEntryData(this, zipHeader, {
26339
+ shouldBuffer: Boolean(next.handler),
26340
+ maximumDescriptorLength: Math.min(maximumZipEntrySizeInBytes, getRemainingZipScanBudget(this, zipScanStart))
26341
+ });
26342
+ if (next.handler) {
26343
+ await this.inflate(zipHeader, fileData, next.handler);
26344
+ }
26345
+ if (zipHeader.dataDescriptor) {
26346
+ const dataDescriptor = new Uint8Array(zipDataDescriptorLengthInBytes);
26347
+ await this.tokenizer.readBuffer(dataDescriptor);
26348
+ if (UINT32_LE.get(dataDescriptor, 0) !== zipDataDescriptorSignature) {
26349
+ throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position - dataDescriptor.length}`);
26350
+ }
26351
+ }
26352
+ if (hasExceededUnknownSizeScanBudget(this.tokenizer, zipScanStart, maximumUntrustedSkipSizeInBytes)) {
26353
+ throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);
26354
+ }
26355
+ } while (!stop);
26356
+ };
25649
26357
  supportedExtensions = new Set(extensions);
25650
26358
  supportedMimeTypes = new Set(mimeTypes);
25651
26359
  });
@@ -25665,6 +26373,14 @@ __export(exports_file_type, {
25665
26373
  });
25666
26374
  import { ReadableStream as WebReadableStream } from "node:stream/web";
25667
26375
  import { pipeline, PassThrough, Readable } from "node:stream";
26376
+ import fs from "node:fs/promises";
26377
+ import { constants as fileSystemConstants } from "node:fs";
26378
+ function isTokenizerStreamBoundsError(error) {
26379
+ if (!(error instanceof RangeError) || error.message !== "offset is out of bounds" || typeof error.stack !== "string") {
26380
+ return false;
26381
+ }
26382
+ return /strtok3[/\\]lib[/\\]stream[/\\]/.test(error.stack);
26383
+ }
25668
26384
  async function fileTypeFromFile(path, options) {
25669
26385
  return new FileTypeParser2(options).fromFile(path, options);
25670
26386
  }
@@ -25681,15 +26397,32 @@ var init_file_type = __esm(() => {
25681
26397
  init_core2();
25682
26398
  FileTypeParser2 = class FileTypeParser2 extends FileTypeParser {
25683
26399
  async fromStream(stream) {
25684
- const tokenizer = await (stream instanceof WebReadableStream ? fromWebStream(stream, this.tokenizerOptions) : fromStream2(stream, this.tokenizerOptions));
26400
+ const tokenizer = await (stream instanceof WebReadableStream ? fromWebStream(stream, this.getTokenizerOptions()) : fromStream2(stream, this.getTokenizerOptions()));
25685
26401
  try {
25686
26402
  return await super.fromTokenizer(tokenizer);
26403
+ } catch (error) {
26404
+ if (isTokenizerStreamBoundsError(error)) {
26405
+ return;
26406
+ }
26407
+ throw error;
25687
26408
  } finally {
25688
26409
  await tokenizer.close();
25689
26410
  }
25690
26411
  }
25691
26412
  async fromFile(path) {
25692
- const tokenizer = await fromFile(path);
26413
+ const fileHandle = await fs.open(path, fileSystemConstants.O_RDONLY | fileSystemConstants.O_NONBLOCK);
26414
+ const fileStat = await fileHandle.stat();
26415
+ if (!fileStat.isFile()) {
26416
+ await fileHandle.close();
26417
+ return;
26418
+ }
26419
+ const tokenizer = new FileTokenizer(fileHandle, {
26420
+ ...this.getTokenizerOptions(),
26421
+ fileInfo: {
26422
+ path,
26423
+ size: fileStat.size
26424
+ }
26425
+ });
25693
26426
  try {
25694
26427
  return await super.fromTokenizer(tokenizer);
25695
26428
  } finally {
@@ -25700,7 +26433,7 @@ var init_file_type = __esm(() => {
25700
26433
  if (!(readableStream instanceof Readable)) {
25701
26434
  return super.toDetectionStream(readableStream, options);
25702
26435
  }
25703
- const { sampleSize = reasonableDetectionSizeInBytes } = options;
26436
+ const sampleSize = normalizeSampleSize(options.sampleSize ?? reasonableDetectionSizeInBytes);
25704
26437
  return new Promise((resolve3, reject) => {
25705
26438
  readableStream.on("error", reject);
25706
26439
  readableStream.once("readable", () => {
@@ -25980,9 +26713,10 @@ var require_dist3 = __commonJS((exports) => {
25980
26713
  var import_chokidar = __toESM(require_chokidar(), 1);
25981
26714
  var import_picocolors = __toESM(require_picocolors(), 1);
25982
26715
  import { spawn, spawnSync } from "node:child_process";
25983
- import { existsSync as existsSync2 } from "node:fs";
25984
- import * as fs from "node:fs/promises";
26716
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
26717
+ import * as fs2 from "node:fs/promises";
25985
26718
  import path from "node:path";
26719
+ import { TextDecoder as TextDecoder2 } from "node:util";
25986
26720
 
25987
26721
  // ../../node_modules/commander/esm.mjs
25988
26722
  var import__ = __toESM(require_commander(), 1);
@@ -27488,6 +28222,21 @@ class DoneLocalChain {
27488
28222
  const result = this.runContract(record, "execute", env, info, msg);
27489
28223
  return { address, result };
27490
28224
  }
28225
+ dumpStorage(address) {
28226
+ const record = this.contracts.get(address);
28227
+ if (!record) {
28228
+ throw new Error(`contract ${address} not found`);
28229
+ }
28230
+ const storage = record.backend.storage;
28231
+ if (!(storage instanceof import_backend.BasicKVIterStorage)) {
28232
+ return [];
28233
+ }
28234
+ const entries = [];
28235
+ storage.dict.forEach((value, key) => {
28236
+ entries.push({ key, value: value ?? "" });
28237
+ });
28238
+ return entries.sort((a, b) => a.key.localeCompare(b.key));
28239
+ }
27491
28240
  query(address, msg, options = {}) {
27492
28241
  const record = this.contracts.get(address);
27493
28242
  if (!record) {
@@ -34541,6 +35290,15 @@ var TypeCompiler;
34541
35290
  })(TypeCompiler || (TypeCompiler = {}));
34542
35291
 
34543
35292
  // ../../node_modules/elysia/dist/universal/utils.mjs
35293
+ function isCloudflareWorker() {
35294
+ try {
35295
+ if (typeof caches < "u" && typeof caches.default < "u" || typeof WebSocketPair < "u")
35296
+ return true;
35297
+ } catch {
35298
+ return false;
35299
+ }
35300
+ return false;
35301
+ }
34544
35302
  var isBun = typeof Bun < "u";
34545
35303
  var isDeno = typeof Deno < "u";
34546
35304
 
@@ -34691,7 +35449,6 @@ async function getResponseLength(response) {
34691
35449
  }
34692
35450
  return length;
34693
35451
  }
34694
- var hasHeaderShorthand = "toJSON" in new Headers;
34695
35452
  var replaceUrlPath = (url, pathname) => {
34696
35453
  const pathStartIndex = url.indexOf("/", 11), queryIndex = url.indexOf("?", pathStartIndex);
34697
35454
  return queryIndex === -1 ? `${url.slice(0, pathStartIndex)}${pathname.charCodeAt(0) === 47 ? "" : "/"}${pathname}` : `${url.slice(0, pathStartIndex)}${pathname.charCodeAt(0) === 47 ? "" : "/"}${pathname}${url.slice(queryIndex)}`;
@@ -34825,8 +35582,7 @@ var lifeCycleToArray = (a) => {
34825
35582
  let beforeHandle = [];
34826
35583
  return a.resolve && (beforeHandle = fnToContainer(Array.isArray(a.resolve) ? a.resolve : [a.resolve], "resolve"), delete a.resolve), a.beforeHandle && (beforeHandle.length ? beforeHandle = beforeHandle.concat(Array.isArray(a.beforeHandle) ? a.beforeHandle : [a.beforeHandle]) : beforeHandle = Array.isArray(a.beforeHandle) ? a.beforeHandle : [a.beforeHandle]), beforeHandle.length && (a.beforeHandle = beforeHandle), a;
34827
35584
  };
34828
- var isBun2 = typeof Bun < "u";
34829
- var hasBunHash = isBun2 && typeof Bun.hash == "function";
35585
+ var hasHeaderShorthand = isBun ? "toJSON" in new Headers : false;
34830
35586
  var hasSetImmediate = typeof setImmediate == "function";
34831
35587
  var checksum = (s) => {
34832
35588
  let h = 9;
@@ -34970,8 +35726,8 @@ var StatusMap = {
34970
35726
  var InvertedStatusMap = Object.fromEntries(Object.entries(StatusMap).map(([k, v]) => [v, k]));
34971
35727
  var encoder = new TextEncoder;
34972
35728
  var signCookie = async (val, secret) => {
34973
- if (typeof val == "object" ? val = JSON.stringify(val) : typeof val != "string" && (val = val + ""), secret === null)
34974
- throw new TypeError("Secret key must be provided.");
35729
+ if (typeof val == "object" ? val = JSON.stringify(val) : typeof val != "string" && (val = val + ""), secret == null)
35730
+ throw new TypeError("Secret key must be provided");
34975
35731
  const secretKey = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]), hmacBuffer = await crypto.subtle.sign("HMAC", secretKey, encoder.encode(val));
34976
35732
  return val + "." + removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"));
34977
35733
  };
@@ -34982,11 +35738,9 @@ var constantTimeEqual = typeof crypto?.timingSafeEqual == "function" ? (a, b) =>
34982
35738
  var unsignCookie = async (input, secret) => {
34983
35739
  if (typeof input != "string")
34984
35740
  throw new TypeError("Signed cookie string must be provided.");
34985
- if (secret === null)
34986
- throw new TypeError("Secret key must be provided.");
34987
35741
  const dot = input.lastIndexOf(".");
34988
- if (dot <= 0)
34989
- return false;
35742
+ if (dot === -1)
35743
+ return secret === null ? input : false;
34990
35744
  const tentativeValue = input.slice(0, dot), expectedInput = await signCookie(tentativeValue, secret);
34991
35745
  return constantTimeEqual(expectedInput, input) ? tentativeValue : false;
34992
35746
  };
@@ -35099,11 +35853,11 @@ var form = (items) => {
35099
35853
  }
35100
35854
  return formData;
35101
35855
  };
35102
- var randomId = typeof crypto > "u" ? () => {
35856
+ var randomId = typeof crypto > "u" || isCloudflareWorker() ? () => {
35103
35857
  let result = "";
35104
- const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", charactersLength = characters.length;
35858
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
35105
35859
  for (let i = 0;i < 16; i++)
35106
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
35860
+ result += characters.charAt(Math.floor(Math.random() * 62));
35107
35861
  return result;
35108
35862
  } : () => {
35109
35863
  const uuid = crypto.randomUUID();
@@ -35316,7 +36070,7 @@ class ValidationError extends Error {
35316
36070
  value,
35317
36071
  property: accessor,
35318
36072
  message: error?.message,
35319
- summary: mapValueError(error).summary,
36073
+ summary: mapValueError(error)?.summary,
35320
36074
  found: value,
35321
36075
  expected,
35322
36076
  errors: "Errors" in validator ? [
@@ -35333,7 +36087,7 @@ class ValidationError extends Error {
35333
36087
  on: type,
35334
36088
  property: accessor,
35335
36089
  message: error?.message,
35336
- summary: mapValueError(error).summary,
36090
+ summary: mapValueError(error)?.summary,
35337
36091
  expected,
35338
36092
  found: value,
35339
36093
  errors: "Errors" in validator ? [...validator.Errors(value)].map(mapValueError) : [...exports_value2.Errors(validator, value)].map(mapValueError)
@@ -35357,7 +36111,7 @@ class ValidationError extends Error {
35357
36111
  path: issue.path?.join(".") || "root",
35358
36112
  message: issue.message,
35359
36113
  value: this.value
35360
- })) || [] : ("Errors" in this.validator) ? [...this.validator.Errors(this.value)].map(mapValueError) : [...exports_value2.Errors(this.validator, this.value)].map(mapValueError);
36114
+ })) || [] : ("Errors" in this.validator) ? [...this.validator.Errors(this.value)].filter((x) => x).map((x) => mapValueError(x)) : [...exports_value2.Errors(this.validator, this.value)].map(mapValueError);
35361
36115
  }
35362
36116
  static simplifyModel(validator) {
35363
36117
  const model = "schema" in validator ? validator.schema : validator;
@@ -35393,7 +36147,7 @@ class ValidationError extends Error {
35393
36147
  on: this.type,
35394
36148
  property: this.valueError?.path || "root",
35395
36149
  message,
35396
- summary: this.valueError ? mapValueError(this.valueError).summary : undefined,
36150
+ summary: mapValueError(this.valueError)?.summary,
35397
36151
  found: value,
35398
36152
  expected,
35399
36153
  errors
@@ -35549,7 +36303,7 @@ var fullFormats = {
35549
36303
  uri,
35550
36304
  "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
35551
36305
  "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
35552
- url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
36306
+ url: /^(?:https?|ftp):\/\/(?:[^\s:@]+(?::[^\s@]*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
35553
36307
  email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
35554
36308
  hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
35555
36309
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
@@ -35945,6 +36699,270 @@ t.BooleanString = ElysiaType.BooleanString, t.ObjectString = ElysiaType.ObjectSt
35945
36699
  }
35946
36700
  })), t.Nullable = ElysiaType.Nullable, t.MaybeEmpty = ElysiaType.MaybeEmpty, t.Cookie = ElysiaType.Cookie, t.Date = ElysiaType.Date, t.UnionEnum = ElysiaType.UnionEnum, t.NoValidate = ElysiaType.NoValidate, t.Form = ElysiaType.Form, t.ArrayBuffer = ElysiaType.ArrayBuffer, t.Uint8Array = ElysiaType.Uint8Array;
35947
36701
 
36702
+ // ../../node_modules/elysia/dist/sucrose.mjs
36703
+ var separateFunction = (code) => {
36704
+ code.startsWith("async") && (code = code.slice(5)), code = code.trimStart();
36705
+ let index = -1;
36706
+ if (code.charCodeAt(0) === 40 && (index = code.indexOf("=>", code.indexOf(")")), index !== -1)) {
36707
+ let bracketEndIndex = index;
36708
+ for (;bracketEndIndex > 0 && code.charCodeAt(--bracketEndIndex) !== 41; )
36709
+ ;
36710
+ let body = code.slice(index + 2);
36711
+ return body.charCodeAt(0) === 32 && (body = body.trimStart()), [
36712
+ code.slice(1, bracketEndIndex),
36713
+ body,
36714
+ {
36715
+ isArrowReturn: body.charCodeAt(0) !== 123
36716
+ }
36717
+ ];
36718
+ }
36719
+ if (/^(\w+)=>/g.test(code) && (index = code.indexOf("=>"), index !== -1)) {
36720
+ let body = code.slice(index + 2);
36721
+ return body.charCodeAt(0) === 32 && (body = body.trimStart()), [
36722
+ code.slice(0, index),
36723
+ body,
36724
+ {
36725
+ isArrowReturn: body.charCodeAt(0) !== 123
36726
+ }
36727
+ ];
36728
+ }
36729
+ if (code.startsWith("function")) {
36730
+ index = code.indexOf("(");
36731
+ const end = code.indexOf(")");
36732
+ return [
36733
+ code.slice(index + 1, end),
36734
+ code.slice(end + 2),
36735
+ {
36736
+ isArrowReturn: false
36737
+ }
36738
+ ];
36739
+ }
36740
+ const start = code.indexOf("(");
36741
+ if (start !== -1) {
36742
+ const sep = code.indexOf(`
36743
+ `, 2), parameter = code.slice(0, sep), end = parameter.lastIndexOf(")") + 1, body = code.slice(sep + 1);
36744
+ return [
36745
+ parameter.slice(start, end),
36746
+ "{" + body,
36747
+ {
36748
+ isArrowReturn: false
36749
+ }
36750
+ ];
36751
+ }
36752
+ const x = code.split(`
36753
+ `, 2);
36754
+ return [x[0], x[1], { isArrowReturn: false }];
36755
+ };
36756
+ var bracketPairRange = (parameter) => {
36757
+ const start = parameter.indexOf("{");
36758
+ if (start === -1)
36759
+ return [-1, 0];
36760
+ let end = start + 1, deep = 1;
36761
+ for (;end < parameter.length; end++) {
36762
+ const char = parameter.charCodeAt(end);
36763
+ if (char === 123 ? deep++ : char === 125 && deep--, deep === 0)
36764
+ break;
36765
+ }
36766
+ return deep !== 0 ? [0, parameter.length] : [start, end + 1];
36767
+ };
36768
+ var bracketPairRangeReverse = (parameter) => {
36769
+ const end = parameter.lastIndexOf("}");
36770
+ if (end === -1)
36771
+ return [-1, 0];
36772
+ let start = end - 1, deep = 1;
36773
+ for (;start >= 0; start--) {
36774
+ const char = parameter.charCodeAt(start);
36775
+ if (char === 125 ? deep++ : char === 123 && deep--, deep === 0)
36776
+ break;
36777
+ }
36778
+ return deep !== 0 ? [-1, 0] : [start, end + 1];
36779
+ };
36780
+ var removeColonAlias = (parameter) => {
36781
+ for (;; ) {
36782
+ const start = parameter.indexOf(":");
36783
+ if (start === -1)
36784
+ break;
36785
+ let end = parameter.indexOf(",", start);
36786
+ end === -1 && (end = parameter.indexOf("}", start) - 1), end === -2 && (end = parameter.length), parameter = parameter.slice(0, start) + parameter.slice(end);
36787
+ }
36788
+ return parameter;
36789
+ };
36790
+ var retrieveRootparameters = (parameter) => {
36791
+ let hasParenthesis = false;
36792
+ parameter.charCodeAt(0) === 40 && (parameter = parameter.slice(1, -1)), parameter.charCodeAt(0) === 123 && (hasParenthesis = true, parameter = parameter.slice(1, -1)), parameter = parameter.replace(/( |\t|\n)/g, "").trim();
36793
+ let parameters = [];
36794
+ for (;; ) {
36795
+ let [start, end] = bracketPairRange(parameter);
36796
+ if (start === -1)
36797
+ break;
36798
+ parameters.push(parameter.slice(0, start - 1)), parameter.charCodeAt(end) === 44 && end++, parameter = parameter.slice(end);
36799
+ }
36800
+ parameter = removeColonAlias(parameter), parameter && (parameters = parameters.concat(parameter.split(",")));
36801
+ const parameterMap = /* @__PURE__ */ Object.create(null);
36802
+ for (const p of parameters) {
36803
+ if (p.indexOf(",") === -1) {
36804
+ parameterMap[p] = true;
36805
+ continue;
36806
+ }
36807
+ for (const q of p.split(","))
36808
+ parameterMap[q.trim()] = true;
36809
+ }
36810
+ return {
36811
+ hasParenthesis,
36812
+ parameters: parameterMap
36813
+ };
36814
+ };
36815
+ var findParameterReference = (parameter, inference) => {
36816
+ const { parameters, hasParenthesis } = retrieveRootparameters(parameter);
36817
+ return parameters.query && (inference.query = true), parameters.headers && (inference.headers = true), parameters.body && (inference.body = true), parameters.cookie && (inference.cookie = true), parameters.set && (inference.set = true), parameters.server && (inference.server = true), parameters.route && (inference.route = true), parameters.url && (inference.url = true), parameters.path && (inference.path = true), hasParenthesis ? `{ ${Object.keys(parameters).join(", ")} }` : Object.keys(parameters).join(", ");
36818
+ };
36819
+ var findEndIndex = (type, content, index) => {
36820
+ const regex2 = new RegExp(`${type.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\n\\t,; ]`);
36821
+ index !== undefined && (regex2.lastIndex = index);
36822
+ const match = regex2.exec(content);
36823
+ return match ? match.index : -1;
36824
+ };
36825
+ var findAlias = (type, body, depth = 0) => {
36826
+ if (depth > 5)
36827
+ return [];
36828
+ const aliases = [];
36829
+ let content = body;
36830
+ for (;; ) {
36831
+ let index = findEndIndex(" = " + type, content);
36832
+ if (index === -1 && (index = findEndIndex("=" + type, content)), index === -1) {
36833
+ let lastIndex = content.indexOf(" = " + type);
36834
+ if (lastIndex === -1 && (lastIndex = content.indexOf("=" + type)), lastIndex + 3 + type.length !== content.length)
36835
+ break;
36836
+ index = lastIndex;
36837
+ }
36838
+ const part = content.slice(0, index), lastPart = part.lastIndexOf(" ");
36839
+ let variable = part.slice(lastPart !== -1 ? lastPart + 1 : -1);
36840
+ if (variable === "}") {
36841
+ const [start, end] = bracketPairRangeReverse(part);
36842
+ aliases.push(removeColonAlias(content.slice(start, end))), content = content.slice(index + 3 + type.length);
36843
+ continue;
36844
+ }
36845
+ for (;variable.charCodeAt(0) === 44; )
36846
+ variable = variable.slice(1);
36847
+ for (;variable.charCodeAt(0) === 9; )
36848
+ variable = variable.slice(1);
36849
+ variable.includes("(") || aliases.push(variable), content = content.slice(index + 3 + type.length);
36850
+ }
36851
+ for (const alias of aliases) {
36852
+ if (alias.charCodeAt(0) === 123)
36853
+ continue;
36854
+ const deepAlias = findAlias(alias, body);
36855
+ deepAlias.length > 0 && aliases.push(...deepAlias);
36856
+ }
36857
+ return aliases;
36858
+ };
36859
+ var extractMainParameter = (parameter) => {
36860
+ if (!parameter)
36861
+ return;
36862
+ if (parameter.charCodeAt(0) !== 123)
36863
+ return parameter;
36864
+ if (parameter = parameter.slice(2, -2), !parameter.includes(","))
36865
+ return parameter.indexOf("...") !== -1 ? parameter.slice(parameter.indexOf("...") + 3) : undefined;
36866
+ const spreadIndex = parameter.indexOf("...");
36867
+ if (spreadIndex !== -1)
36868
+ return parameter.slice(spreadIndex + 3).trimEnd();
36869
+ };
36870
+ var inferBodyReference = (code, aliases, inference) => {
36871
+ const access = (type, alias) => new RegExp(`${alias}\\.(${type})|${alias}\\["${type}"\\]|${alias}\\['${type}'\\]`).test(code);
36872
+ for (const alias of aliases)
36873
+ if (alias) {
36874
+ if (alias.charCodeAt(0) === 123) {
36875
+ const parameters = retrieveRootparameters(alias).parameters;
36876
+ parameters.query && (inference.query = true), parameters.headers && (inference.headers = true), parameters.body && (inference.body = true), parameters.cookie && (inference.cookie = true), parameters.set && (inference.set = true), parameters.server && (inference.server = true), parameters.url && (inference.url = true), parameters.route && (inference.route = true), parameters.path && (inference.path = true);
36877
+ continue;
36878
+ }
36879
+ if (!inference.query && (access("query", alias) || code.includes("return " + alias) || code.includes("return " + alias + ".query")) && (inference.query = true), !inference.headers && access("headers", alias) && (inference.headers = true), !inference.body && access("body", alias) && (inference.body = true), !inference.cookie && access("cookie", alias) && (inference.cookie = true), !inference.set && access("set", alias) && (inference.set = true), !inference.server && access("server", alias) && (inference.server = true), !inference.route && access("route", alias) && (inference.route = true), !inference.url && access("url", alias) && (inference.url = true), !inference.path && access("path", alias) && (inference.path = true), inference.query && inference.headers && inference.body && inference.cookie && inference.set && inference.server && inference.route && inference.url && inference.path)
36880
+ break;
36881
+ }
36882
+ return aliases;
36883
+ };
36884
+ var isContextPassToFunction = (context, body, inference) => {
36885
+ try {
36886
+ const captureFunction = new RegExp(`\\w\\((?:.*?)?${context}(?:.*?)?\\)`, "gs"), exactParameter = new RegExp(`${context}(,|\\))`, "gs"), length = body.length;
36887
+ let fn;
36888
+ for (fn = captureFunction.exec(body) + "";captureFunction.lastIndex !== 0 && captureFunction.lastIndex < length + (fn ? fn.length : 0); ) {
36889
+ if (fn && exactParameter.test(fn))
36890
+ return inference.query = true, inference.headers = true, inference.body = true, inference.cookie = true, inference.set = true, inference.server = true, inference.url = true, inference.route = true, inference.path = true, true;
36891
+ fn = captureFunction.exec(body) + "";
36892
+ }
36893
+ const nextChar = body.charCodeAt(captureFunction.lastIndex);
36894
+ return nextChar === 41 || nextChar === 44 ? (inference.query = true, inference.headers = true, inference.body = true, inference.cookie = true, inference.set = true, inference.server = true, inference.url = true, inference.route = true, inference.path = true, true) : false;
36895
+ } catch {
36896
+ return console.log("[Sucrose] warning: unexpected isContextPassToFunction error, you may continue development as usual but please report the following to maintainers:"), console.log("--- body ---"), console.log(body), console.log("--- context ---"), console.log(context), true;
36897
+ }
36898
+ };
36899
+ var pendingGC;
36900
+ var caches2 = {};
36901
+ var clearSucroseCache = (delay) => {
36902
+ delay === null || isCloudflareWorker() || (delay === undefined && (delay = 4 * 60 * 1000 + 55 * 1000), pendingGC && clearTimeout(pendingGC), pendingGC = setTimeout(() => {
36903
+ caches2 = {}, pendingGC = undefined, isBun && Bun.gc(false);
36904
+ }, delay), pendingGC.unref?.());
36905
+ };
36906
+ var mergeInference = (a, b) => ({
36907
+ body: a.body || b.body,
36908
+ cookie: a.cookie || b.cookie,
36909
+ headers: a.headers || b.headers,
36910
+ query: a.query || b.query,
36911
+ set: a.set || b.set,
36912
+ server: a.server || b.server,
36913
+ url: a.url || b.url,
36914
+ route: a.route || b.route,
36915
+ path: a.path || b.path
36916
+ });
36917
+ var sucrose = (lifeCycle, inference = {
36918
+ query: false,
36919
+ headers: false,
36920
+ body: false,
36921
+ cookie: false,
36922
+ set: false,
36923
+ server: false,
36924
+ url: false,
36925
+ route: false,
36926
+ path: false
36927
+ }, settings = {}) => {
36928
+ const events = [];
36929
+ lifeCycle.request?.length && events.push(...lifeCycle.request), lifeCycle.beforeHandle?.length && events.push(...lifeCycle.beforeHandle), lifeCycle.parse?.length && events.push(...lifeCycle.parse), lifeCycle.error?.length && events.push(...lifeCycle.error), lifeCycle.transform?.length && events.push(...lifeCycle.transform), lifeCycle.afterHandle?.length && events.push(...lifeCycle.afterHandle), lifeCycle.mapResponse?.length && events.push(...lifeCycle.mapResponse), lifeCycle.afterResponse?.length && events.push(...lifeCycle.afterResponse), lifeCycle.handler && typeof lifeCycle.handler == "function" && events.push(lifeCycle.handler);
36930
+ for (let i = 0;i < events.length; i++) {
36931
+ const e = events[i];
36932
+ if (!e)
36933
+ continue;
36934
+ const event = typeof e == "object" ? e.fn : e;
36935
+ if (typeof event != "function")
36936
+ continue;
36937
+ const content = event.toString(), key = checksum(content), cachedInference = caches2[key];
36938
+ if (cachedInference) {
36939
+ inference = mergeInference(inference, cachedInference);
36940
+ continue;
36941
+ }
36942
+ clearSucroseCache(settings.gcTime);
36943
+ const fnInference = {
36944
+ query: false,
36945
+ headers: false,
36946
+ body: false,
36947
+ cookie: false,
36948
+ set: false,
36949
+ server: false,
36950
+ url: false,
36951
+ route: false,
36952
+ path: false
36953
+ }, [parameter, body] = separateFunction(content), rootParameters = findParameterReference(parameter, fnInference), mainParameter = extractMainParameter(rootParameters);
36954
+ if (mainParameter) {
36955
+ const aliases = findAlias(mainParameter, body.slice(1, -1));
36956
+ aliases.splice(0, -1, mainParameter);
36957
+ let code = body;
36958
+ code.charCodeAt(0) === 123 && code.charCodeAt(body.length - 1) === 125 && (code = code.slice(1, -1).trim()), isContextPassToFunction(mainParameter, code, fnInference) || inferBodyReference(code, aliases, fnInference), !fnInference.query && code.includes("return " + mainParameter + ".query") && (fnInference.query = true);
36959
+ }
36960
+ if (caches2[key] || (caches2[key] = fnInference), inference = mergeInference(inference, fnInference), inference.query && inference.headers && inference.body && inference.cookie && inference.set && inference.server && inference.url && inference.route && inference.path)
36961
+ break;
36962
+ }
36963
+ return inference;
36964
+ };
36965
+
35948
36966
  // ../../node_modules/elysia/dist/cookies.mjs
35949
36967
  var import_cookie = __toESM(require_dist3(), 1);
35950
36968
  var import_fast_decode_uri_component = __toESM(require_fast_decode_uri_component(), 1);
@@ -35957,7 +36975,7 @@ var hashString = (str) => {
35957
36975
  };
35958
36976
 
35959
36977
  class Cookie {
35960
- constructor(name, jar, initial = {}) {
36978
+ constructor(name, jar, initial = /* @__PURE__ */ Object.create(null)) {
35961
36979
  this.name = name;
35962
36980
  this.jar = jar;
35963
36981
  this.initial = initial;
@@ -36078,7 +37096,7 @@ class Cookie {
36078
37096
  return typeof this.value == "object" ? JSON.stringify(this.value) : this.value?.toString() ?? "";
36079
37097
  }
36080
37098
  }
36081
- var createCookieJar = (set, store, initial) => (set.cookie || (set.cookie = {}), new Proxy(store, {
37099
+ var createCookieJar = (set, store, initial) => (set.cookie || (set.cookie = /* @__PURE__ */ Object.create(null)), new Proxy(store, {
36082
37100
  get(_, key) {
36083
37101
  return key in store ? new Cookie(key, set.cookie, Object.assign({}, initial ?? {}, store[key])) : new Cookie(key, set.cookie, Object.assign({}, initial));
36084
37102
  }
@@ -36087,24 +37105,16 @@ var parseCookie = async (set, cookieString, {
36087
37105
  secrets,
36088
37106
  sign,
36089
37107
  ...initial
36090
- } = {}) => {
37108
+ } = /* @__PURE__ */ Object.create(null)) => {
36091
37109
  if (!cookieString)
36092
- return createCookieJar(set, {}, initial);
37110
+ return createCookieJar(set, /* @__PURE__ */ Object.create(null), initial);
36093
37111
  const isStringKey = typeof secrets == "string";
36094
37112
  sign && sign !== true && !Array.isArray(sign) && (sign = [sign]);
36095
- const jar = {}, cookies = import_cookie.parse(cookieString);
37113
+ const jar = /* @__PURE__ */ Object.create(null), cookies = import_cookie.parse(cookieString);
36096
37114
  for (const [name, v] of Object.entries(cookies)) {
36097
- if (v === undefined)
37115
+ if (v === undefined || name === "__proto__" || name === "constructor" || name === "prototype")
36098
37116
  continue;
36099
37117
  let value = import_fast_decode_uri_component.default(v);
36100
- if (value) {
36101
- const starts = value.charCodeAt(0), ends = value.charCodeAt(value.length - 1);
36102
- if (starts === 123 && ends === 125 || starts === 91 && ends === 93)
36103
- try {
36104
- value = JSON.parse(value);
36105
- } catch {
36106
- }
36107
- }
36108
37118
  if (sign === true || sign?.includes(name)) {
36109
37119
  if (!secrets)
36110
37120
  throw new Error("No secret is provided to cookie plugin");
@@ -36130,9 +37140,15 @@ var parseCookie = async (set, cookieString, {
36130
37140
  throw new InvalidCookieSignature(name);
36131
37141
  }
36132
37142
  }
36133
- jar[name] = {
36134
- value
36135
- };
37143
+ if (value) {
37144
+ const starts = value.charCodeAt(0), ends = value.charCodeAt(value.length - 1);
37145
+ if (starts === 123 && ends === 125 || starts === 91 && ends === 93)
37146
+ try {
37147
+ value = JSON.parse(value);
37148
+ } catch {
37149
+ }
37150
+ }
37151
+ jar[name] = /* @__PURE__ */ Object.create(null), jar[name].value = value;
36136
37152
  }
36137
37153
  return createCookieJar(set, jar, initial);
36138
37154
  };
@@ -36150,9 +37166,6 @@ var serializeCookie = (cookies) => {
36150
37166
  return set.length === 1 ? set[0] : set;
36151
37167
  };
36152
37168
 
36153
- // ../../node_modules/elysia/dist/universal/env.mjs
36154
- var env2 = isBun ? Bun.env : typeof process < "u" && process?.env ? process.env : {};
36155
-
36156
37169
  // ../../node_modules/elysia/dist/adapter/utils.mjs
36157
37170
  async function* streamResponse(response) {
36158
37171
  const body = response.body;
@@ -36170,6 +37183,25 @@ async function* streamResponse(response) {
36170
37183
  reader.releaseLock();
36171
37184
  }
36172
37185
  }
37186
+ function mergeHeaders(responseHeaders, setHeaders) {
37187
+ const headers = new Headers(responseHeaders);
37188
+ if (setHeaders instanceof Headers)
37189
+ for (const key of setHeaders.keys())
37190
+ if (key === "set-cookie") {
37191
+ if (headers.has("set-cookie"))
37192
+ continue;
37193
+ for (const cookie of setHeaders.getSetCookie())
37194
+ headers.append("set-cookie", cookie);
37195
+ } else
37196
+ responseHeaders.has(key) || headers.set(key, setHeaders?.get(key) ?? "");
37197
+ else
37198
+ for (const key in setHeaders)
37199
+ key === "set-cookie" ? headers.append(key, setHeaders[key]) : responseHeaders.has(key) || headers.set(key, setHeaders[key]);
37200
+ return headers;
37201
+ }
37202
+ function mergeStatus(responseStatus, setStatus) {
37203
+ return typeof setStatus == "string" && (setStatus = StatusMap[setStatus]), responseStatus === 200 ? setStatus : responseStatus;
37204
+ }
36173
37205
  async function tee(source, branches = 2) {
36174
37206
  const buffer = [];
36175
37207
  let done = false, waiting = [];
@@ -36191,10 +37223,41 @@ async function tee(source, branches = 2) {
36191
37223
  }
36192
37224
  return Array.from({ length: branches }, makeIterator);
36193
37225
  }
36194
- var handleFile = (response, set) => {
37226
+ var handleFile = (response, set, request) => {
36195
37227
  if (!isBun && response instanceof Promise)
36196
- return response.then((res) => handleFile(res, set));
36197
- const size = response.size, immutable = set && (set.status === 206 || set.status === 304 || set.status === 412 || set.status === 416), defaultHeader = immutable ? {} : {
37228
+ return response.then((res) => handleFile(res, set, request));
37229
+ const size = response.size, rangeHeader = request?.headers.get("range");
37230
+ if (rangeHeader) {
37231
+ const match = /bytes=(\d*)-(\d*)/.exec(rangeHeader);
37232
+ if (match) {
37233
+ if (!match[1] && !match[2])
37234
+ return new Response(null, {
37235
+ status: 416,
37236
+ headers: mergeHeaders(new Headers({ "content-range": `bytes */${size}` }), set?.headers ?? {})
37237
+ });
37238
+ let start, end;
37239
+ if (!match[1] && match[2]) {
37240
+ const suffix = parseInt(match[2]);
37241
+ start = Math.max(0, size - suffix), end = size - 1;
37242
+ } else
37243
+ start = match[1] ? parseInt(match[1]) : 0, end = match[2] ? Math.min(parseInt(match[2]), size - 1) : size - 1;
37244
+ if (start >= size || start > end)
37245
+ return new Response(null, {
37246
+ status: 416,
37247
+ headers: mergeHeaders(new Headers({ "content-range": `bytes */${size}` }), set?.headers ?? {})
37248
+ });
37249
+ const contentLength = end - start + 1, rangeHeaders = new Headers({
37250
+ "accept-ranges": "bytes",
37251
+ "content-range": `bytes ${start}-${end}/${size}`,
37252
+ "content-length": String(contentLength)
37253
+ });
37254
+ return new Response(response.slice(start, end + 1, response.type), {
37255
+ status: 206,
37256
+ headers: mergeHeaders(rangeHeaders, set?.headers ?? {})
37257
+ });
37258
+ }
37259
+ }
37260
+ const immutable = set && (set.status === 206 || set.status === 304 || set.status === 412 || set.status === 416), defaultHeader = immutable ? {} : {
36198
37261
  "accept-ranges": "bytes",
36199
37262
  "content-range": size ? `bytes 0-${size - 1}/${size}` : undefined
36200
37263
  };
@@ -36255,7 +37318,7 @@ var responseToSetHeaders = (response, set) => {
36255
37318
  key !== "content-encoding" && key in set.headers && (set.headers[key] = value);
36256
37319
  return set;
36257
37320
  };
36258
- var allowRapidStream = env2.ELYSIA_RAPID_STREAM === "true";
37321
+ var enqueueBinaryChunk = (controller, chunk) => chunk instanceof Blob ? chunk.arrayBuffer().then((buffer) => (controller.enqueue(new Uint8Array(buffer)), true)) : chunk instanceof Uint8Array ? (controller.enqueue(chunk), true) : chunk instanceof ArrayBuffer ? (controller.enqueue(new Uint8Array(chunk)), true) : ArrayBuffer.isView(chunk) ? (controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)), true) : false;
36259
37322
  var createStreamHandler = ({ mapResponse, mapCompactResponse }) => async (generator, set, request, skipFormat) => {
36260
37323
  let init = generator.next?.();
36261
37324
  if (set && handleSet(set), init instanceof Promise && (init = await init), init?.value instanceof ReadableStream)
@@ -36274,21 +37337,23 @@ var createStreamHandler = ({ mapResponse, mapCompactResponse }) => async (genera
36274
37337
  connection: "keep-alive"
36275
37338
  }
36276
37339
  };
36277
- const isBrowser = request?.headers.has("Origin");
37340
+ const iterator = typeof generator.next == "function" ? generator : generator[Symbol.asyncIterator]();
37341
+ let end = false;
36278
37342
  return new Response(new ReadableStream({
36279
- async start(controller) {
36280
- let end = false;
37343
+ start(controller) {
36281
37344
  if (request?.signal?.addEventListener("abort", () => {
36282
- end = true;
37345
+ end = true, iterator.return?.();
36283
37346
  try {
36284
37347
  controller.close();
36285
37348
  } catch {
36286
37349
  }
36287
- }), !(!init || init.value instanceof ReadableStream)) {
36288
- if (init.value !== undefined && init.value !== null)
36289
- if (init.value.toSSE)
36290
- controller.enqueue(init.value.toSSE());
36291
- else if (typeof init.value == "object")
37350
+ }), !(!init || init.value instanceof ReadableStream || init.value === undefined || init.value === null))
37351
+ if (init.value.toSSE)
37352
+ controller.enqueue(init.value.toSSE());
37353
+ else {
37354
+ if (enqueueBinaryChunk(controller, init.value))
37355
+ return;
37356
+ if (typeof init.value == "object")
36292
37357
  try {
36293
37358
  controller.enqueue(format(JSON.stringify(init.value)));
36294
37359
  } catch {
@@ -36296,33 +37361,51 @@ var createStreamHandler = ({ mapResponse, mapCompactResponse }) => async (genera
36296
37361
  }
36297
37362
  else
36298
37363
  controller.enqueue(format(init.value.toString()));
37364
+ }
37365
+ },
37366
+ async pull(controller) {
37367
+ if (end) {
37368
+ try {
37369
+ controller.close();
37370
+ } catch {
37371
+ }
37372
+ return;
36299
37373
  }
36300
37374
  try {
36301
- for await (const chunk of generator) {
36302
- if (end)
36303
- break;
36304
- if (chunk != null)
36305
- if (chunk.toSSE)
36306
- controller.enqueue(chunk.toSSE());
36307
- else {
36308
- if (typeof chunk == "object")
36309
- try {
36310
- controller.enqueue(format(JSON.stringify(chunk)));
36311
- } catch {
36312
- controller.enqueue(format(chunk.toString()));
36313
- }
36314
- else
36315
- controller.enqueue(format(chunk.toString()));
36316
- !allowRapidStream && isBrowser && !isSSE && await new Promise((resolve3) => setTimeout(() => resolve3(), 0));
37375
+ const { value: chunk, done } = await iterator.next();
37376
+ if (done || end) {
37377
+ try {
37378
+ controller.close();
37379
+ } catch {
37380
+ }
37381
+ return;
37382
+ }
37383
+ if (chunk == null)
37384
+ return;
37385
+ if (chunk.toSSE)
37386
+ controller.enqueue(chunk.toSSE());
37387
+ else {
37388
+ if (enqueueBinaryChunk(controller, chunk))
37389
+ return;
37390
+ if (typeof chunk == "object")
37391
+ try {
37392
+ controller.enqueue(format(JSON.stringify(chunk)));
37393
+ } catch {
37394
+ controller.enqueue(format(chunk.toString()));
36317
37395
  }
37396
+ else
37397
+ controller.enqueue(format(chunk.toString()));
36318
37398
  }
36319
37399
  } catch (error) {
36320
37400
  console.warn(error);
37401
+ try {
37402
+ controller.close();
37403
+ } catch {
37404
+ }
36321
37405
  }
36322
- try {
36323
- controller.close();
36324
- } catch {
36325
- }
37406
+ },
37407
+ cancel() {
37408
+ end = true, iterator.return?.();
36326
37409
  }
36327
37410
  }), set);
36328
37411
  };
@@ -36336,56 +37419,38 @@ var handleSet = (set) => {
36336
37419
  var createResponseHandler = (handler) => {
36337
37420
  const handleStream = createStreamHandler(handler);
36338
37421
  return (response, set, request) => {
36339
- let isCookieSet = false;
36340
- if (set.headers instanceof Headers)
36341
- for (const key of set.headers.keys())
36342
- if (key === "set-cookie") {
36343
- if (isCookieSet)
36344
- continue;
36345
- isCookieSet = true;
36346
- for (const cookie of set.headers.getSetCookie())
36347
- response.headers.append("set-cookie", cookie);
36348
- } else
36349
- response.headers.has(key) || response.headers.set(key, set.headers?.get(key) ?? "");
36350
- else
36351
- for (const key in set.headers)
36352
- key === "set-cookie" ? response.headers.append(key, set.headers[key]) : response.headers.has(key) || response.headers.set(key, set.headers[key]);
36353
- const status2 = set.status ?? 200;
36354
- if (response.status !== status2 && status2 !== 200 && (response.status <= 300 || response.status > 400)) {
36355
- const newResponse = new Response(response.body, {
36356
- headers: response.headers,
36357
- status: set.status
36358
- });
36359
- return !newResponse.headers.has("content-length") && newResponse.headers.get("transfer-encoding") === "chunked" ? handleStream(streamResponse(newResponse), responseToSetHeaders(newResponse, set), request, true) : newResponse;
36360
- }
36361
- return !response.headers.has("content-length") && response.headers.get("transfer-encoding") === "chunked" ? handleStream(streamResponse(response), responseToSetHeaders(response, set), request, true) : response;
37422
+ const newResponse = new Response(response.body, {
37423
+ headers: mergeHeaders(response.headers, set.headers),
37424
+ status: mergeStatus(response.status, set.status)
37425
+ });
37426
+ return !newResponse.headers.has("content-length") && newResponse.headers.get("transfer-encoding") === "chunked" ? handleStream(streamResponse(newResponse), responseToSetHeaders(newResponse, set), request, true) : newResponse;
36362
37427
  };
36363
37428
  };
36364
37429
 
36365
37430
  // ../../node_modules/elysia/dist/adapter/web-standard/handler.mjs
36366
- var handleElysiaFile = (file2, set = {
37431
+ var handleElysiaFile = (file, set = {
36367
37432
  headers: {}
36368
- }) => {
36369
- const path = file2.path, contentType = mime[path.slice(path.lastIndexOf(".") + 1)];
36370
- return contentType && (set.headers["content-type"] = contentType), file2.stats && set.status !== 206 && set.status !== 304 && set.status !== 412 && set.status !== 416 ? file2.stats.then((stat2) => {
37433
+ }, request) => {
37434
+ const path = file.path, contentType = mime[path.slice(path.lastIndexOf(".") + 1)];
37435
+ return contentType && (set.headers["content-type"] = contentType), file.stats && set.status !== 206 && set.status !== 304 && set.status !== 412 && set.status !== 416 ? file.stats.then((stat2) => {
36371
37436
  const size = stat2.size;
36372
- return size !== undefined && (set.headers["content-range"] = `bytes 0-${size - 1}/${size}`, set.headers["content-length"] = size), handleFile(file2.value, set);
36373
- }) : handleFile(file2.value, set);
37437
+ return size !== undefined && (set.headers["content-range"] = `bytes 0-${size - 1}/${size}`, set.headers["content-length"] = size), handleFile(file.value, set, request);
37438
+ }) : handleFile(file.value, set, request);
36374
37439
  };
36375
37440
  var mapResponse = (response, set, request) => {
36376
37441
  if (isNotEmpty(set.headers) || set.status !== 200 || set.cookie)
36377
37442
  switch (handleSet(set), response?.constructor?.name) {
36378
37443
  case "String":
36379
- return set.headers["content-type"] = "text/plain", new Response(response, set);
37444
+ return set.headers["content-type"] || (set.headers["content-type"] = "text/plain"), new Response(response, set);
36380
37445
  case "Array":
36381
37446
  case "Object":
36382
- return set.headers["content-type"] = "application/json", new Response(JSON.stringify(response), set);
37447
+ return set.headers["content-type"] || (set.headers["content-type"] = "application/json"), new Response(JSON.stringify(response), set);
36383
37448
  case "ElysiaFile":
36384
- return handleElysiaFile(response, set);
37449
+ return handleElysiaFile(response, set, request);
36385
37450
  case "File":
36386
- return handleFile(response, set);
37451
+ return handleFile(response, set, request);
36387
37452
  case "Blob":
36388
- return handleFile(response, set);
37453
+ return handleFile(response, set, request);
36389
37454
  case "ElysiaCustomStatusResponse":
36390
37455
  return set.status = response.code, mapResponse(response.response, set, request);
36391
37456
  case undefined:
@@ -36418,6 +37483,12 @@ var mapResponse = (response, set, request) => {
36418
37483
  return handleStream(response, set, request);
36419
37484
  if (typeof response?.then == "function")
36420
37485
  return response.then((x) => mapResponse(x, set));
37486
+ if (Array.isArray(response))
37487
+ return new Response(JSON.stringify(response), {
37488
+ headers: {
37489
+ "Content-Type": "application/json"
37490
+ }
37491
+ });
36421
37492
  if (typeof response?.toResponse == "function")
36422
37493
  return mapResponse(response.toResponse(), set);
36423
37494
  if ("charCodeAt" in response) {
@@ -36434,16 +37505,16 @@ var mapEarlyResponse = (response, set, request) => {
36434
37505
  if (isNotEmpty(set.headers) || set.status !== 200 || set.cookie)
36435
37506
  switch (handleSet(set), response?.constructor?.name) {
36436
37507
  case "String":
36437
- return set.headers["content-type"] = "text/plain", new Response(response, set);
37508
+ return set.headers["content-type"] || (set.headers["content-type"] = "text/plain"), new Response(response, set);
36438
37509
  case "Array":
36439
37510
  case "Object":
36440
- return set.headers["content-type"] = "application/json", new Response(JSON.stringify(response), set);
37511
+ return set.headers["content-type"] || (set.headers["content-type"] = "application/json"), new Response(JSON.stringify(response), set);
36441
37512
  case "ElysiaFile":
36442
- return handleElysiaFile(response, set);
37513
+ return handleElysiaFile(response, set, request);
36443
37514
  case "File":
36444
- return handleFile(response, set);
37515
+ return handleFile(response, set, request);
36445
37516
  case "Blob":
36446
- return handleFile(response, set);
37517
+ return handleFile(response, set, request);
36447
37518
  case "ElysiaCustomStatusResponse":
36448
37519
  return set.status = response.code, mapEarlyResponse(response.response, set, request);
36449
37520
  case undefined:
@@ -36478,6 +37549,12 @@ var mapEarlyResponse = (response, set, request) => {
36478
37549
  return response.then((x) => mapEarlyResponse(x, set));
36479
37550
  if (typeof response?.toResponse == "function")
36480
37551
  return mapEarlyResponse(response.toResponse(), set);
37552
+ if (Array.isArray(response))
37553
+ return new Response(JSON.stringify(response), {
37554
+ headers: {
37555
+ "Content-Type": "application/json"
37556
+ }
37557
+ });
36481
37558
  if ("charCodeAt" in response) {
36482
37559
  const code = response.charCodeAt(0);
36483
37560
  if (code === 123 || code === 91)
@@ -36488,16 +37565,16 @@ var mapEarlyResponse = (response, set, request) => {
36488
37565
  else
36489
37566
  switch (response?.constructor?.name) {
36490
37567
  case "String":
36491
- return set.headers["content-type"] = "text/plain", new Response(response);
37568
+ return set.headers["content-type"] || (set.headers["content-type"] = "text/plain"), new Response(response);
36492
37569
  case "Array":
36493
37570
  case "Object":
36494
- return set.headers["content-type"] = "application/json", new Response(JSON.stringify(response), set);
37571
+ return set.headers["content-type"] || (set.headers["content-type"] = "application/json"), new Response(JSON.stringify(response), set);
36495
37572
  case "ElysiaFile":
36496
- return handleElysiaFile(response, set);
37573
+ return handleElysiaFile(response, set, request);
36497
37574
  case "File":
36498
- return handleFile(response, set);
37575
+ return handleFile(response, set, request);
36499
37576
  case "Blob":
36500
- return handleFile(response, set);
37577
+ return handleFile(response, set, request);
36501
37578
  case "ElysiaCustomStatusResponse":
36502
37579
  return set.status = response.code, mapEarlyResponse(response.response, set, request);
36503
37580
  case undefined:
@@ -36540,6 +37617,12 @@ var mapEarlyResponse = (response, set, request) => {
36540
37617
  return response.then((x) => mapEarlyResponse(x, set));
36541
37618
  if (typeof response?.toResponse == "function")
36542
37619
  return mapEarlyResponse(response.toResponse(), set);
37620
+ if (Array.isArray(response))
37621
+ return new Response(JSON.stringify(response), {
37622
+ headers: {
37623
+ "Content-Type": "application/json"
37624
+ }
37625
+ });
36543
37626
  if ("charCodeAt" in response) {
36544
37627
  const code = response.charCodeAt(0);
36545
37628
  if (code === 123 || code === 91)
@@ -36564,11 +37647,11 @@ var mapCompactResponse = (response, request) => {
36564
37647
  }
36565
37648
  });
36566
37649
  case "ElysiaFile":
36567
- return handleElysiaFile(response);
37650
+ return handleElysiaFile(response, undefined, request);
36568
37651
  case "File":
36569
- return handleFile(response);
37652
+ return handleFile(response, undefined, request);
36570
37653
  case "Blob":
36571
- return handleFile(response);
37654
+ return handleFile(response, undefined, request);
36572
37655
  case "ElysiaCustomStatusResponse":
36573
37656
  return mapResponse(response.response, {
36574
37657
  status: response.code,
@@ -36611,6 +37694,12 @@ var mapCompactResponse = (response, request) => {
36611
37694
  return response.then((x) => mapCompactResponse(x, request));
36612
37695
  if (typeof response?.toResponse == "function")
36613
37696
  return mapCompactResponse(response.toResponse());
37697
+ if (Array.isArray(response))
37698
+ return new Response(JSON.stringify(response), {
37699
+ headers: {
37700
+ "Content-Type": "application/json"
37701
+ }
37702
+ });
36614
37703
  if ("charCodeAt" in response) {
36615
37704
  const code = response.charCodeAt(0);
36616
37705
  if (code === 123 || code === 91)
@@ -36694,10 +37783,57 @@ for(const [k,v] of c.request.headers.entries())c.headers[k]=v
36694
37783
  c.body={}
36695
37784
  `;
36696
37785
  return isOptional ? fnLiteral += "let form;try{form=await c.request.formData()}catch{}" : fnLiteral += `const form=await c.request.formData()
36697
- `, fnLiteral + `for(const key of form.keys()){if(c.body[key]) continue
37786
+ `, fnLiteral + `const dangerousKeys=new Set(['__proto__','constructor','prototype'])
37787
+ const isDangerousKey=(k)=>{if(dangerousKeys.has(k))return true;const m=k.match(/^(.+)\\[(\\d+)\\]\$/);return m?dangerousKeys.has(m[1]):false}
37788
+ const parseArrayKey=(k)=>{const m=k.match(/^(.+)\\[(\\d+)\\]\$/);return m?{name:m[1],index:parseInt(m[2],10)}:null}
37789
+ for(const key of form.keys()){if(c.body[key])continue
36698
37790
  const value=form.getAll(key)
36699
- if(value.length===1)c.body[key]=value[0]
36700
- else c.body[key]=value}`;
37791
+ let finalValue
37792
+ if(value.length===1){
37793
+ const sv=value[0]
37794
+ if(typeof sv==='string'&&(sv.charCodeAt(0)===123||sv.charCodeAt(0)===91)){
37795
+ try{
37796
+ const p=JSON.parse(sv)
37797
+ if(p&&typeof p==='object')finalValue=p
37798
+ }catch{}
37799
+ }
37800
+ if(finalValue===undefined)finalValue=sv
37801
+ }else finalValue=value
37802
+ if(Array.isArray(finalValue)){
37803
+ const stringValue=finalValue.find((entry)=>typeof entry==='string')
37804
+ const files=typeof File==='undefined'?[]:finalValue.filter((entry)=>entry instanceof File)
37805
+ if(stringValue&&files.length&&stringValue.charCodeAt(0)===123){
37806
+ try{
37807
+ const parsed=JSON.parse(stringValue)
37808
+ if(parsed&&typeof parsed==='object'&&!Array.isArray(parsed)){
37809
+ if(!('file' in parsed)&&files.length===1)parsed.file=files[0]
37810
+ else if(!('files' in parsed)&&files.length>1)parsed.files=files
37811
+ finalValue=parsed
37812
+ }
37813
+ }catch{}
37814
+ }
37815
+ }
37816
+ if(key.includes('.')||key.includes('[')){const keys=key.split('.')
37817
+ const lastKey=keys.pop()
37818
+ if(isDangerousKey(lastKey)||keys.some(isDangerousKey))continue
37819
+ let current=c.body
37820
+ for(const k of keys){const arrayInfo=parseArrayKey(k)
37821
+ if(arrayInfo){if(!Array.isArray(current[arrayInfo.name]))current[arrayInfo.name]=[]
37822
+ const existing=current[arrayInfo.name][arrayInfo.index]
37823
+ const isFile=typeof File!=='undefined'&&existing instanceof File
37824
+ if(!existing||typeof existing!=='object'||Array.isArray(existing)||isFile){
37825
+ let parsed
37826
+ if(typeof existing==='string'&&existing.charCodeAt(0)===123){
37827
+ try{parsed=JSON.parse(existing)
37828
+ if(!parsed||typeof parsed!=='object'||Array.isArray(parsed))parsed=undefined}catch{}
37829
+ }
37830
+ current[arrayInfo.name][arrayInfo.index]=parsed||{}
37831
+ }
37832
+ current=current[arrayInfo.name][arrayInfo.index]}else{if(!current[k]||typeof current[k]!=='object')current[k]={}
37833
+ current=current[k]}}
37834
+ const arrayInfo=parseArrayKey(lastKey)
37835
+ if(arrayInfo){if(!Array.isArray(current[arrayInfo.name]))current[arrayInfo.name]=[]
37836
+ current[arrayInfo.name][arrayInfo.index]=finalValue}else{current[lastKey]=finalValue}}else c.body[key]=finalValue}`;
36701
37837
  }
36702
37838
  }
36703
37839
  },
@@ -36744,6 +37880,278 @@ const error404=new Response(error404Message,{status:404})
36744
37880
  }
36745
37881
  };
36746
37882
 
37883
+ // ../../node_modules/elysia/dist/adapter/bun/handler.mjs
37884
+ var mapResponse2 = (response, set, request) => {
37885
+ if (isNotEmpty(set.headers) || set.status !== 200 || set.cookie)
37886
+ switch (handleSet(set), response?.constructor?.name) {
37887
+ case "String":
37888
+ return new Response(response, set);
37889
+ case "Array":
37890
+ case "Object":
37891
+ return Response.json(response, set);
37892
+ case "ElysiaFile":
37893
+ return handleFile(response.value, set, request);
37894
+ case "File":
37895
+ return handleFile(response, set, request);
37896
+ case "Blob":
37897
+ return handleFile(response, set, request);
37898
+ case "ElysiaCustomStatusResponse":
37899
+ return set.status = response.code, mapResponse2(response.response, set, request);
37900
+ case undefined:
37901
+ return response ? Response.json(response, set) : new Response("", set);
37902
+ case "Response":
37903
+ return handleResponse2(response, set, request);
37904
+ case "Error":
37905
+ return errorToResponse2(response, set);
37906
+ case "Promise":
37907
+ return response.then((x) => mapResponse2(x, set, request));
37908
+ case "Function":
37909
+ return mapResponse2(response(), set, request);
37910
+ case "Number":
37911
+ case "Boolean":
37912
+ return new Response(response.toString(), set);
37913
+ case "Cookie":
37914
+ return response instanceof Cookie ? new Response(response.value, set) : new Response(response?.toString(), set);
37915
+ case "FormData":
37916
+ return new Response(response, set);
37917
+ default:
37918
+ if (response instanceof Response)
37919
+ return handleResponse2(response, set, request);
37920
+ if (response instanceof Promise)
37921
+ return response.then((x) => mapResponse2(x, set));
37922
+ if (response instanceof Error)
37923
+ return errorToResponse2(response, set);
37924
+ if (response instanceof ElysiaCustomStatusResponse)
37925
+ return set.status = response.code, mapResponse2(response.response, set, request);
37926
+ if (typeof response?.next == "function" || response instanceof ReadableStream)
37927
+ return handleStream2(response, set, request);
37928
+ if (typeof response?.then == "function")
37929
+ return response.then((x) => mapResponse2(x, set));
37930
+ if (Array.isArray(response))
37931
+ return Response.json(response);
37932
+ if (typeof response?.toResponse == "function")
37933
+ return mapResponse2(response.toResponse(), set);
37934
+ if ("charCodeAt" in response) {
37935
+ const code = response.charCodeAt(0);
37936
+ if (code === 123 || code === 91)
37937
+ return Response.json(response, set);
37938
+ }
37939
+ return new Response(response, set);
37940
+ }
37941
+ return typeof response?.next == "function" || response instanceof ReadableStream ? handleStream2(response, set, request) : mapCompactResponse2(response, request);
37942
+ };
37943
+ var mapEarlyResponse2 = (response, set, request) => {
37944
+ if (response != null)
37945
+ if (isNotEmpty(set.headers) || set.status !== 200 || set.cookie)
37946
+ switch (handleSet(set), response?.constructor?.name) {
37947
+ case "String":
37948
+ return new Response(response, set);
37949
+ case "Array":
37950
+ case "Object":
37951
+ return Response.json(response, set);
37952
+ case "ElysiaFile":
37953
+ return handleFile(response.value, set, request);
37954
+ case "File":
37955
+ return handleFile(response, set, request);
37956
+ case "Blob":
37957
+ return handleFile(response, set, request);
37958
+ case "ElysiaCustomStatusResponse":
37959
+ return set.status = response.code, mapEarlyResponse2(response.response, set, request);
37960
+ case undefined:
37961
+ return response ? Response.json(response, set) : undefined;
37962
+ case "Response":
37963
+ return handleResponse2(response, set, request);
37964
+ case "Promise":
37965
+ return response.then((x) => mapEarlyResponse2(x, set));
37966
+ case "Error":
37967
+ return errorToResponse2(response, set);
37968
+ case "Function":
37969
+ return mapEarlyResponse2(response(), set);
37970
+ case "Number":
37971
+ case "Boolean":
37972
+ return new Response(response.toString(), set);
37973
+ case "FormData":
37974
+ return new Response(response);
37975
+ case "Cookie":
37976
+ return response instanceof Cookie ? new Response(response.value, set) : new Response(response?.toString(), set);
37977
+ default:
37978
+ if (response instanceof Response)
37979
+ return handleResponse2(response, set, request);
37980
+ if (response instanceof Promise)
37981
+ return response.then((x) => mapEarlyResponse2(x, set));
37982
+ if (response instanceof Error)
37983
+ return errorToResponse2(response, set);
37984
+ if (response instanceof ElysiaCustomStatusResponse)
37985
+ return set.status = response.code, mapEarlyResponse2(response.response, set, request);
37986
+ if (typeof response?.next == "function" || response instanceof ReadableStream)
37987
+ return handleStream2(response, set, request);
37988
+ if (typeof response?.then == "function")
37989
+ return response.then((x) => mapEarlyResponse2(x, set));
37990
+ if (typeof response?.toResponse == "function")
37991
+ return mapEarlyResponse2(response.toResponse(), set);
37992
+ if (Array.isArray(response))
37993
+ return Response.json(response);
37994
+ if ("charCodeAt" in response) {
37995
+ const code = response.charCodeAt(0);
37996
+ if (code === 123 || code === 91)
37997
+ return Response.json(response, set);
37998
+ }
37999
+ return new Response(response, set);
38000
+ }
38001
+ else
38002
+ switch (response?.constructor?.name) {
38003
+ case "String":
38004
+ return new Response(response);
38005
+ case "Array":
38006
+ case "Object":
38007
+ return Response.json(response, set);
38008
+ case "ElysiaFile":
38009
+ return handleFile(response.value, set, request);
38010
+ case "File":
38011
+ return handleFile(response, set, request);
38012
+ case "Blob":
38013
+ return handleFile(response, set, request);
38014
+ case "ElysiaCustomStatusResponse":
38015
+ return set.status = response.code, mapEarlyResponse2(response.response, set, request);
38016
+ case undefined:
38017
+ return response ? Response.json(response) : new Response("");
38018
+ case "Response":
38019
+ return response;
38020
+ case "Promise":
38021
+ return response.then((x) => {
38022
+ const r = mapEarlyResponse2(x, set);
38023
+ if (r !== undefined)
38024
+ return r;
38025
+ });
38026
+ case "Error":
38027
+ return errorToResponse2(response, set);
38028
+ case "Function":
38029
+ return mapCompactResponse2(response(), request);
38030
+ case "Number":
38031
+ case "Boolean":
38032
+ return new Response(response.toString());
38033
+ case "Cookie":
38034
+ return response instanceof Cookie ? new Response(response.value, set) : new Response(response?.toString(), set);
38035
+ case "FormData":
38036
+ return new Response(response);
38037
+ default:
38038
+ if (response instanceof Response)
38039
+ return response;
38040
+ if (response instanceof Promise)
38041
+ return response.then((x) => mapEarlyResponse2(x, set));
38042
+ if (response instanceof Error)
38043
+ return errorToResponse2(response, set);
38044
+ if (response instanceof ElysiaCustomStatusResponse)
38045
+ return set.status = response.code, mapEarlyResponse2(response.response, set, request);
38046
+ if (typeof response?.next == "function" || response instanceof ReadableStream)
38047
+ return handleStream2(response, set, request);
38048
+ if (typeof response?.then == "function")
38049
+ return response.then((x) => mapEarlyResponse2(x, set));
38050
+ if (typeof response?.toResponse == "function")
38051
+ return mapEarlyResponse2(response.toResponse(), set);
38052
+ if (Array.isArray(response))
38053
+ return Response.json(response);
38054
+ if ("charCodeAt" in response) {
38055
+ const code = response.charCodeAt(0);
38056
+ if (code === 123 || code === 91)
38057
+ return Response.json(response, set);
38058
+ }
38059
+ return new Response(response);
38060
+ }
38061
+ };
38062
+ var mapCompactResponse2 = (response, request) => {
38063
+ switch (response?.constructor?.name) {
38064
+ case "String":
38065
+ return new Response(response);
38066
+ case "Object":
38067
+ case "Array":
38068
+ return Response.json(response);
38069
+ case "ElysiaFile":
38070
+ return handleFile(response.value, undefined, request);
38071
+ case "File":
38072
+ return handleFile(response, undefined, request);
38073
+ case "Blob":
38074
+ return handleFile(response, undefined, request);
38075
+ case "ElysiaCustomStatusResponse":
38076
+ return mapResponse2(response.response, {
38077
+ status: response.code,
38078
+ headers: {}
38079
+ });
38080
+ case undefined:
38081
+ return response ? Response.json(response) : new Response("");
38082
+ case "Response":
38083
+ return response;
38084
+ case "Error":
38085
+ return errorToResponse2(response);
38086
+ case "Promise":
38087
+ return response.then((x) => mapCompactResponse2(x, request));
38088
+ case "Function":
38089
+ return mapCompactResponse2(response(), request);
38090
+ case "Number":
38091
+ case "Boolean":
38092
+ return new Response(response.toString());
38093
+ case "FormData":
38094
+ return new Response(response);
38095
+ default:
38096
+ if (response instanceof Response)
38097
+ return response;
38098
+ if (response instanceof Promise)
38099
+ return response.then((x) => mapCompactResponse2(x, request));
38100
+ if (response instanceof Error)
38101
+ return errorToResponse2(response);
38102
+ if (response instanceof ElysiaCustomStatusResponse)
38103
+ return mapResponse2(response.response, {
38104
+ status: response.code,
38105
+ headers: {}
38106
+ });
38107
+ if (typeof response?.next == "function" || response instanceof ReadableStream)
38108
+ return handleStream2(response, undefined, request);
38109
+ if (typeof response?.then == "function")
38110
+ return response.then((x) => mapCompactResponse2(x, request));
38111
+ if (typeof response?.toResponse == "function")
38112
+ return mapCompactResponse2(response.toResponse());
38113
+ if (Array.isArray(response))
38114
+ return Response.json(response);
38115
+ if ("charCodeAt" in response) {
38116
+ const code = response.charCodeAt(0);
38117
+ if (code === 123 || code === 91)
38118
+ return Response.json(response);
38119
+ }
38120
+ return new Response(response);
38121
+ }
38122
+ };
38123
+ var errorToResponse2 = (error, set) => {
38124
+ if (typeof error?.toResponse == "function") {
38125
+ const raw = error.toResponse(), targetSet = set ?? { headers: {}, status: 200, redirect: "" }, apply = (resolved) => (resolved instanceof Response && (targetSet.status = resolved.status), mapResponse2(resolved, targetSet));
38126
+ return typeof raw?.then == "function" ? raw.then(apply) : apply(raw);
38127
+ }
38128
+ return Response.json({
38129
+ name: error?.name,
38130
+ message: error?.message,
38131
+ cause: error?.cause
38132
+ }, {
38133
+ status: set?.status !== 200 ? set?.status ?? 500 : 500,
38134
+ headers: set?.headers
38135
+ });
38136
+ };
38137
+ var createStaticHandler2 = (handle, hooks, setHeaders = {}) => {
38138
+ if (typeof handle == "function")
38139
+ return;
38140
+ const response = mapResponse2(handle, {
38141
+ headers: setHeaders
38142
+ });
38143
+ if (!hooks.parse?.length && !hooks.transform?.length && !hooks.beforeHandle?.length && !hooks.afterHandle?.length)
38144
+ return () => response.clone();
38145
+ };
38146
+ var handleResponse2 = createResponseHandler({
38147
+ mapResponse: mapResponse2,
38148
+ mapCompactResponse: mapCompactResponse2
38149
+ });
38150
+ var handleStream2 = createStreamHandler({
38151
+ mapResponse: mapResponse2,
38152
+ mapCompactResponse: mapCompactResponse2
38153
+ });
38154
+
36747
38155
  // ../../node_modules/elysia/dist/compose.mjs
36748
38156
  var import_fast_decode_uri_component3 = __toESM(require_fast_decode_uri_component(), 1);
36749
38157
 
@@ -37069,7 +38477,7 @@ var handleTuple = (schema, property, instruction) => {
37069
38477
  for (let i2 = 0;i2 < schema.length; i2++) {
37070
38478
  if (i2 !== 0)
37071
38479
  v += ",";
37072
- v += mirror(schema[i2], joinProperty(property, i2, instruction.parentIsOptional), instruction);
38480
+ v += mirror(schema[i2], joinProperty(property, i2, instruction.parentIsOptional || instruction.fromUnion), instruction);
37073
38481
  }
37074
38482
  v += `];`;
37075
38483
  if (!isRoot)
@@ -37119,13 +38527,15 @@ var handleUnion = (schemas, property, instruction) => {
37119
38527
  v += `if(d.unions[${ui}][${i}].Check(${property})){return ${mirror(type, property, {
37120
38528
  ...instruction,
37121
38529
  recursion: instruction.recursion + 1,
37122
- parentIsOptional: true
38530
+ parentIsOptional: true,
38531
+ fromUnion: true
37123
38532
  })}}
37124
38533
  `;
37125
38534
  cleanThenCheck += (i ? "" : "let ") + "tmp=" + mirror(type, property, {
37126
38535
  ...instruction,
37127
38536
  recursion: instruction.recursion + 1,
37128
- parentIsOptional: true
38537
+ parentIsOptional: true,
38538
+ fromUnion: true
37129
38539
  }) + `
37130
38540
  if(d.unions[${ui}][${i}].Check(tmp))return tmp
37131
38541
  `;
@@ -37165,7 +38575,7 @@ var mirror = (schema, property, instruction) => {
37165
38575
  for (let i2 = 0;i2 < keys.length; i2++) {
37166
38576
  const key = keys[i2];
37167
38577
  let isOptional = !schema.required || schema.required && !schema.required.includes(key) || Array.isArray(schema.properties[key].anyOf);
37168
- const name = joinProperty(property, key, instruction.parentIsOptional);
38578
+ const name = joinProperty(property, key, instruction.parentIsOptional || instruction.fromUnion);
37169
38579
  if (isOptional) {
37170
38580
  const index = instruction.array;
37171
38581
  if (property.startsWith("ar")) {
@@ -37520,10 +38930,16 @@ var hasElysiaMeta = (meta, _schema) => {
37520
38930
  };
37521
38931
  var hasProperty = (expectedProperty, _schema) => {
37522
38932
  if (!_schema)
37523
- return;
38933
+ return false;
37524
38934
  const schema = _schema.schema ?? _schema;
37525
38935
  if (schema[Kind] === "Import" && _schema.References)
37526
38936
  return _schema.References().some((schema2) => hasProperty(expectedProperty, schema2));
38937
+ if (schema.anyOf)
38938
+ return schema.anyOf.some((s) => hasProperty(expectedProperty, s));
38939
+ if (schema.allOf)
38940
+ return schema.allOf.some((s) => hasProperty(expectedProperty, s));
38941
+ if (schema.oneOf)
38942
+ return schema.oneOf.some((s) => hasProperty(expectedProperty, s));
37527
38943
  if (schema.type === "object") {
37528
38944
  const properties = schema.properties;
37529
38945
  if (!properties)
@@ -37676,6 +39092,42 @@ var getSchemaValidator = (s, {
37676
39092
  };
37677
39093
  let schema = mapSchema(s), _validators = validators;
37678
39094
  if ("~standard" in schema || validators?.length && validators.some((x) => x && typeof x != "string" && ("~standard" in x))) {
39095
+ let Check22 = function(value, validated = false) {
39096
+ let v = validated ? value : mainCheck.validate(value);
39097
+ if (v instanceof Promise)
39098
+ return v.then((v2) => Check22(v2, true));
39099
+ if (v.issues)
39100
+ return v;
39101
+ const values = [];
39102
+ return v && typeof v == "object" && values.push(v.value), runCheckers2(value, 0, values, v);
39103
+ }, runCheckers2 = function(value, startIndex, values, lastV) {
39104
+ for (let i = startIndex;i < checkers.length; i++) {
39105
+ let v = checkers[i].validate(value);
39106
+ if (v instanceof Promise)
39107
+ return v.then((resolved) => {
39108
+ if (resolved.issues)
39109
+ return resolved;
39110
+ const nextValues = [...values];
39111
+ return resolved && typeof resolved == "object" && nextValues.push(resolved.value), runCheckers2(value, i + 1, nextValues, resolved);
39112
+ });
39113
+ if (v.issues)
39114
+ return v;
39115
+ v && typeof v == "object" && values.push(v.value), lastV = v;
39116
+ }
39117
+ return mergeValues2(values, lastV);
39118
+ }, mergeValues2 = function(values, lastV) {
39119
+ if (!values.length)
39120
+ return { value: lastV };
39121
+ if (values.length === 1)
39122
+ return { value: values[0] };
39123
+ if (values.length === 2)
39124
+ return { value: mergeDeep(values[0], values[1]) };
39125
+ let newValue = mergeDeep(values[0], values[1]);
39126
+ for (let i = 2;i < values.length; i++)
39127
+ newValue = mergeDeep(newValue, values[i]);
39128
+ return { value: newValue };
39129
+ };
39130
+ var Check2 = Check22, runCheckers = runCheckers2, mergeValues = mergeValues2;
37679
39131
  const typeboxSubValidator = (schema2) => {
37680
39132
  let mirror2;
37681
39133
  if (normalize === true || normalize === "exactMirror")
@@ -37698,12 +39150,14 @@ var getSchemaValidator = (s, {
37698
39150
  coerce,
37699
39151
  additionalCoerce
37700
39152
  });
37701
- return vali.Decode = mirror2, (v) => vali.Check(v) ? {
37702
- value: vali.Decode(v)
37703
- } : {
37704
- issues: [...vali.Errors(v)]
39153
+ return vali.Decode = mirror2, {
39154
+ validate: (v) => vali.Check(v) ? {
39155
+ value: mirror2 ? mirror2(v) : v
39156
+ } : {
39157
+ issues: [...vali.Errors(v)]
39158
+ }
37705
39159
  };
37706
- }, mainCheck = schema["~standard"] ? schema["~standard"].validate : typeboxSubValidator(schema);
39160
+ }, mainCheck = schema["~standard"] ? schema["~standard"] : typeboxSubValidator(schema);
37707
39161
  let checkers = [];
37708
39162
  if (validators?.length) {
37709
39163
  for (const validator2 of validators)
@@ -37718,28 +39172,6 @@ var getSchemaValidator = (s, {
37718
39172
  }
37719
39173
  }
37720
39174
  }
37721
- async function Check2(value) {
37722
- let v = mainCheck(value);
37723
- if (v instanceof Promise && (v = await v), v.issues)
37724
- return v;
37725
- const values = [];
37726
- v && typeof v == "object" && values.push(v.value);
37727
- for (let i = 0;i < checkers.length; i++) {
37728
- if (v = checkers[i].validate(value), v instanceof Promise && (v = await v), v.issues)
37729
- return v;
37730
- v && typeof v == "object" && values.push(v.value);
37731
- }
37732
- if (!values.length)
37733
- return { value: v };
37734
- if (values.length === 1)
37735
- return { value: values[0] };
37736
- if (values.length === 2)
37737
- return { value: mergeDeep(values[0], values[1]) };
37738
- let newValue = mergeDeep(values[0], values[1]);
37739
- for (let i = 2;i < values.length; i++)
37740
- newValue = mergeDeep(newValue, values[i]);
37741
- return { value: newValue };
37742
- }
37743
39175
  const validator = {
37744
39176
  provider: "standard",
37745
39177
  schema,
@@ -37747,10 +39179,10 @@ var getSchemaValidator = (s, {
37747
39179
  checkFunc: () => {
37748
39180
  },
37749
39181
  code: "",
37750
- Check: Check2,
37751
- Errors: (value) => Check2(value)?.then?.((x) => x?.issues),
39182
+ Check: Check22,
39183
+ Errors: (value) => Check22(value)?.then?.((x) => x?.issues),
37752
39184
  Code: () => "",
37753
- Decode: Check2,
39185
+ Decode: Check22,
37754
39186
  Encode: (value) => value,
37755
39187
  hasAdditionalProperties: false,
37756
39188
  hasDefault: false,
@@ -38017,6 +39449,21 @@ var getSchemaValidator = (s, {
38017
39449
  }), compiled;
38018
39450
  };
38019
39451
  var isUnion = (schema) => schema[Kind] === "Union" || !schema.schema && !!schema.anyOf;
39452
+ var getSchemaProperties = (schema) => {
39453
+ if (!schema)
39454
+ return;
39455
+ if (schema.properties)
39456
+ return schema.properties;
39457
+ const members = schema.allOf ?? schema.anyOf ?? schema.oneOf;
39458
+ if (members) {
39459
+ const result = {};
39460
+ for (const member of members) {
39461
+ const props = getSchemaProperties(member);
39462
+ props && Object.assign(result, props);
39463
+ }
39464
+ return Object.keys(result).length > 0 ? result : undefined;
39465
+ }
39466
+ };
38020
39467
  var mergeObjectSchemas = (schemas) => {
38021
39468
  if (schemas.length === 0)
38022
39469
  return {
@@ -38286,7 +39733,7 @@ break
38286
39733
  encodeSchema && value.hasTransform && !noValidate ? (code += `try{${name}=validator.response[${status2}].Encode(${name})
38287
39734
  `, appliedCleaner || (code += clean2({ ignoreTryCatch: true })), code += `c.set.status=${status2}}catch{` + (applyErrorCleaner ? `try{
38288
39735
  ` + clean2({ ignoreTryCatch: true }) + `${name}=validator.response[${status2}].Encode(${name})
38289
- }catch{throw new ValidationError('response',validator.response[${status2}],${name},${allowUnsafeValidationDetails})}` : `throw new ValidationError('response',validator.response[${status2}],${name}),${allowUnsafeValidationDetails}`) + "}") : (appliedCleaner || (code += clean2()), noValidate || (code += `if(validator.response[${status2}].Check(${name})===false)throw new ValidationError('response',validator.response[${status2}],${name},${allowUnsafeValidationDetails})
39736
+ }catch{throw new ValidationError('response',validator.response[${status2}],${name},${allowUnsafeValidationDetails})}` : `throw new ValidationError('response',validator.response[${status2}],${name},${allowUnsafeValidationDetails})`) + "}") : (appliedCleaner || (code += clean2()), noValidate || (code += `if(validator.response[${status2}].Check(${name})===false)throw new ValidationError('response',validator.response[${status2}],${name},${allowUnsafeValidationDetails})
38290
39737
  c.set.status=${status2}
38291
39738
  `)), code += `break
38292
39739
  `;
@@ -38302,7 +39749,7 @@ var isAsync = (v) => {
38302
39749
  if (isObject2 && v.isAsync !== undefined)
38303
39750
  return v.isAsync;
38304
39751
  const fn = isObject2 ? v.fn : v;
38305
- if (fn.constructor.name === "AsyncFunction")
39752
+ if (fn.constructor.name === "AsyncFunction" || fn.constructor.name === "AsyncGeneratorFunction")
38306
39753
  return true;
38307
39754
  const literal = fn.toString();
38308
39755
  if (matchResponseClone.test(literal))
@@ -38371,8 +39818,14 @@ return function(){return a}`)(handler);
38371
39818
  if (_encodeCookie)
38372
39819
  return _encodeCookie;
38373
39820
  if (cookieMeta?.sign) {
39821
+ if (cookieMeta.secrets === "")
39822
+ throw new Error(`cookie secret can't be an empty string at (${method}) ${path}`, {
39823
+ cause: `(${method}) ${path}`
39824
+ });
38374
39825
  if (!cookieMeta.secrets)
38375
- throw new Error(`t.Cookie required secret which is not set in (${method}) ${path}.`);
39826
+ throw new Error(`cookie secret must be defined (${method}) ${path}`, {
39827
+ cause: `(${method}) ${path}`
39828
+ });
38376
39829
  const secret = cookieMeta.secrets ? typeof cookieMeta.secrets == "string" ? cookieMeta.secrets : cookieMeta.secrets[0] : undefined;
38377
39830
  if (_encodeCookie += `const _setCookie = c.set.cookie
38378
39831
  if(_setCookie){`, cookieMeta.sign === true)
@@ -38407,7 +39860,7 @@ if(_setCookie){`, cookieMeta.sign === true)
38407
39860
  const get = (name, defaultValue) => {
38408
39861
  const value = cookieMeta?.[name] ?? defaultValue;
38409
39862
  return value === undefined ? "" : value ? typeof value == "string" ? `${name}:${JSON.stringify(value)},` : value instanceof Date ? `${name}: new Date(${value.getTime()}),` : `${name}:${value},` : typeof defaultValue == "string" ? `${name}:"${defaultValue}",` : `${name}:${defaultValue},`;
38410
- }, options = cookieMeta ? `{secrets:${cookieMeta.secrets !== undefined ? typeof cookieMeta.secrets == "string" ? JSON.stringify(cookieMeta.secrets) : "[" + cookieMeta.secrets.map((x) => JSON.stringify(x)).join(",") + "]" : "undefined"},sign:${cookieMeta.sign === true ? true : cookieMeta.sign !== undefined ? typeof cookieMeta.sign == "string" ? JSON.stringify(cookieMeta.sign) : "[" + cookieMeta.sign.map((x) => JSON.stringify(x)).join(",") + "]" : "undefined"},` + get("domain") + get("expires") + get("httpOnly") + get("maxAge") + get("path", "/") + get("priority") + get("sameSite") + get("secure") + "}" : "undefined";
39863
+ }, options = cookieMeta ? `{secrets:${cookieMeta.secrets !== undefined && cookieMeta.secrets !== null ? typeof cookieMeta.secrets == "string" ? JSON.stringify(cookieMeta.secrets) : "[" + cookieMeta.secrets.map((x) => JSON.stringify(x)).join(",") + "]" : "undefined"},sign:${cookieMeta.sign === true ? true : cookieMeta.sign !== undefined ? typeof cookieMeta.sign == "string" ? JSON.stringify(cookieMeta.sign) : "[" + cookieMeta.sign.map((x) => JSON.stringify(x)).join(",") + "]" : "undefined"},` + get("domain") + get("expires") + get("httpOnly") + get("maxAge") + get("path", "/") + get("priority") + get("sameSite") + get("secure") + "}" : "undefined";
38411
39864
  hasHeaders ? fnLiteral += `
38412
39865
  c.cookie=await parseCookie(c.set,c.headers.cookie,${options})
38413
39866
  ` : fnLiteral += `
@@ -38417,9 +39870,9 @@ c.cookie=await parseCookie(c.set,c.request.headers.get('cookie'),${options})
38417
39870
  if (hasQuery) {
38418
39871
  let arrayProperties = {}, objectProperties = {}, hasArrayProperty = false, hasObjectProperty = false;
38419
39872
  if (validator.query?.schema) {
38420
- const schema = unwrapImportSchema(validator.query?.schema);
38421
- if (Kind in schema && schema.properties)
38422
- for (const [key, value] of Object.entries(schema.properties))
39873
+ const schema = unwrapImportSchema(validator.query?.schema), properties = getSchemaProperties(schema);
39874
+ if (properties)
39875
+ for (const [key, value] of Object.entries(properties))
38423
39876
  hasElysiaMeta("ArrayQuery", value) && (arrayProperties[key] = true, hasArrayProperty = true), hasElysiaMeta("ObjectString", value) && (objectProperties[key] = true, hasObjectProperty = true);
38424
39877
  }
38425
39878
  fnLiteral += `if(c.qi===-1){c.query=Object.create(null)}else{c.query=parseQueryFromURL(c.url,c.qi+1${hasArrayProperty ? "," + JSON.stringify(arrayProperties) : hasObjectProperty ? ",undefined" : ""}${hasObjectProperty ? "," + JSON.stringify(objectProperties) : ""})}`;
@@ -38454,11 +39907,11 @@ ${prefix}e.afterResponse[${i}](c)
38454
39907
  }
38455
39908
  return reporter.resolve(), afterResponse2 += `})
38456
39909
  `, _afterResponse = afterResponse2;
38457
- }, mapResponse2 = (r = "r") => {
38458
- const after = afterResponse(), response = `${hasSet ? "mapResponse" : "mapCompactResponse"}(${saveResponse}${r}${hasSet ? ",c.set" : ""}${mapResponseContext})
39910
+ }, mapResponse3 = (r = "r") => {
39911
+ const after = afterResponse(), response = `${maybeStream && maybeAsync ? "await " : ""}${hasSet ? "mapResponse" : "mapCompactResponse"}(${saveResponse}${r}${hasSet ? ",c.set" : ""}${mapResponseContext})
38459
39912
  `;
38460
39913
  return after ? `const _res=${response}` + after + "return _res" : `return ${response}`;
38461
- }, mapResponseContext = maybeStream && adapter.mapResponseContext ? `,${adapter.mapResponseContext}` : "";
39914
+ }, mapResponseContext = adapter.mapResponseContext ? `,${adapter.mapResponseContext}` : "";
38462
39915
  (hasTrace || inference.route) && (fnLiteral += `c.route=\`${path}\`
38463
39916
  `), (hasTrace || hooks.afterResponse?.length) && (fnLiteral += `let afterHandlerStreamListener
38464
39917
  `);
@@ -38500,7 +39953,7 @@ try{`;
38500
39953
  fnLiteral += adapter.parser.formData(isOptionalBody);
38501
39954
  break;
38502
39955
  default:
38503
- parser[0] in app["~parser"] && (fnLiteral += hasHeaders ? "let contentType = c.headers['content-type']" : "let contentType = c.request.headers.get('content-type')", fnLiteral += `
39956
+ parser in app["~parser"] && (fnLiteral += hasHeaders ? "let contentType = c.headers['content-type']" : "let contentType = c.request.headers.get('content-type')", fnLiteral += `
38504
39957
  if(contentType){const index=contentType.indexOf(';')
38505
39958
  if(index!==-1)contentType=contentType.substring(0,index)}
38506
39959
  else{contentType=''}c.contentType=contentType
@@ -38599,7 +40052,7 @@ case 'multipart/form-data':` + adapter.parser.formData(isOptionalBody) + `break
38599
40052
  for (const key of Object.keys(app["~parser"]))
38600
40053
  fnLiteral += `case '${key}':let bo${key}=parser['${key}'](c,contentType)
38601
40054
  if(bo${key} instanceof Promise)bo${key}=await bo${key}
38602
- if(bo${key} instanceof ElysiaCustomStatusResponse){` + mapResponse2(`bo${key}`) + `}if(bo${key}!==undefined)c.body=bo${key}
40055
+ if(bo${key} instanceof ElysiaCustomStatusResponse){` + mapResponse3(`bo${key}`) + `}if(bo${key}!==undefined)c.body=bo${key}
38603
40056
  break
38604
40057
  `;
38605
40058
  hooks.parse?.length && (fnLiteral += "}"), fnLiteral += "}";
@@ -38620,7 +40073,7 @@ delete c.contentType`);
38620
40073
  const transform2 = hooks.transform[i], endUnit = reporter.resolveChild(transform2.fn.name);
38621
40074
  fnLiteral += isAsync(transform2) ? `transformed=await e.transform[${i}](c)
38622
40075
  ` : `transformed=e.transform[${i}](c)
38623
- `, transform2.subType === "mapDerive" ? fnLiteral += "if(transformed instanceof ElysiaCustomStatusResponse){" + mapResponse2("transformed") + `}else{transformed.request=c.request
40076
+ `, transform2.subType === "mapDerive" ? fnLiteral += "if(transformed instanceof ElysiaCustomStatusResponse){" + mapResponse3("transformed") + `}else{transformed.request=c.request
38624
40077
  transformed.store=c.store
38625
40078
  transformed.qi=c.qi
38626
40079
  transformed.path=c.path
@@ -38628,7 +40081,7 @@ transformed.url=c.url
38628
40081
  transformed.redirect=c.redirect
38629
40082
  transformed.set=c.set
38630
40083
  transformed.error=c.error
38631
- c=transformed}` : fnLiteral += "if(transformed instanceof ElysiaCustomStatusResponse){" + mapResponse2("transformed") + `}else Object.assign(c,transformed)
40084
+ c=transformed}` : fnLiteral += "if(transformed instanceof ElysiaCustomStatusResponse){" + mapResponse3("transformed") + `}else Object.assign(c,transformed)
38632
40085
  `, endUnit();
38633
40086
  }
38634
40087
  }
@@ -38738,12 +40191,7 @@ if(vab.issues){` + validation.validate("body", undefined, "vab.issues") + `}else
38738
40191
  sanitize: () => app.config.sanitize
38739
40192
  });
38740
40193
  if (candidate) {
38741
- const isFirst = fileUnions.length === 0;
38742
- let properties = candidate.schema?.properties ?? type.properties;
38743
- if (!properties && candidate.schema?.anyOf) {
38744
- const objectSchema = candidate.schema.anyOf.find((s) => s.type === "object" || (Kind in s) && s[Kind] === "Object");
38745
- objectSchema && (properties = objectSchema.properties);
38746
- }
40194
+ const isFirst = fileUnions.length === 0, properties = getSchemaProperties(candidate.schema) ?? getSchemaProperties(type);
38747
40195
  if (!properties)
38748
40196
  continue;
38749
40197
  const iterator2 = Object.entries(properties);
@@ -38762,22 +40210,25 @@ if(vab.issues){` + validation.validate("body", undefined, "vab.issues") + `}else
38762
40210
  }
38763
40211
  }
38764
40212
  } else if (hasNonUnionFileWithDefault || !hasUnion && (hasType("File", unwrapImportSchema(validator.body.schema)) || hasType("Files", unwrapImportSchema(validator.body.schema)))) {
38765
- let validateFile2 = "", i = 0;
38766
- for (const [k, v] of Object.entries(unwrapImportSchema(validator.body.schema).properties))
38767
- !v.extension || v[Kind] !== "File" && v[Kind] !== "Files" || (i && (validateFile2 += ","), validateFile2 += `fileType(c.body.${k},${JSON.stringify(v.extension)},'body.${k}')`, i++);
40213
+ let validateFile2 = "";
40214
+ const bodyProperties = getSchemaProperties(unwrapImportSchema(validator.body.schema));
40215
+ let i = 0;
40216
+ if (bodyProperties)
40217
+ for (const [k, v] of Object.entries(bodyProperties))
40218
+ !v.extension || v[Kind] !== "File" && v[Kind] !== "Files" || (i && (validateFile2 += ","), validateFile2 += `fileType(c.body.${k},${JSON.stringify(v.extension)},'body.${k}')`, i++);
38768
40219
  i && (fnLiteral += `
38769
40220
  `), i === 1 ? fnLiteral += `await ${validateFile2}
38770
40221
  ` : i > 1 && (fnLiteral += `await Promise.all([${validateFile2}])
38771
40222
  `);
38772
40223
  }
38773
40224
  }
38774
- validator.cookie && (validator.cookie.config = mergeCookie(validator.cookie.config, validator.cookie?.config ?? {}), fnLiteral += `let cookieValue={}
40225
+ validator.cookie && (validator.cookie.config = mergeCookie(validator.cookie.config, app.config.cookie ?? {}), fnLiteral += `let cookieValue={}
38775
40226
  for(const [key,value] of Object.entries(c.cookie))cookieValue[key]=value.value
38776
40227
  `, validator.cookie.isOptional && (fnLiteral += "if(isNotEmpty(c.cookie)){"), validator.cookie.provider === "standard" ? (fnLiteral += `let vac=validator.cookie.Check(cookieValue)
38777
40228
  if(vac instanceof Promise)vac=await vac
38778
40229
  if(vac.issues){` + validation.validate("cookie", undefined, "vac.issues") + `}else{cookieValue=vac.value}
38779
40230
  `, fnLiteral += `for(const k of Object.keys(cookieValue))c.cookie[k].value=cookieValue[k]
38780
- `) : validator.body?.schema?.noValidate !== true && (fnLiteral += "if(validator.cookie.Check(cookieValue)===false){" + validation.validate("cookie", "cookieValue") + "}", validator.cookie.hasTransform && (fnLiteral += coerceTransformDecodeError("for(const [key,value] of Object.entries(validator.cookie.Decode(cookieValue))){c.cookie[key].cookie.value = value}", "cookie", allowUnsafeValidationDetails))), validator.cookie.isOptional && (fnLiteral += "}"));
40231
+ `) : validator.cookie?.schema?.noValidate !== true && (fnLiteral += "if(validator.cookie.Check(cookieValue)===false){" + validation.validate("cookie", "cookieValue") + "}", validator.cookie.hasTransform && (fnLiteral += coerceTransformDecodeError("for(const [key,value] of Object.entries(validator.cookie.Decode(cookieValue))){c.cookie[key].value = value}", "cookie", allowUnsafeValidationDetails))), validator.cookie.isOptional && (fnLiteral += "}"));
38781
40232
  }
38782
40233
  if (hooks?.beforeHandle || hasTrace) {
38783
40234
  const reporter = report("beforeHandle", {
@@ -38792,7 +40243,7 @@ if(vac.issues){` + validation.validate("cookie", undefined, "vac.issues") + `}el
38792
40243
  let resolved
38793
40244
  `), fnLiteral += isAsync(beforeHandle) ? `resolved=await e.beforeHandle[${i}](c);
38794
40245
  ` : `resolved=e.beforeHandle[${i}](c);
38795
- `, beforeHandle.subType === "mapResolve" ? fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){" + mapResponse2("resolved") + `}else{resolved.request=c.request
40246
+ `, beforeHandle.subType === "mapResolve" ? fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){" + mapResponse3("resolved") + `}else{resolved.request=c.request
38796
40247
  resolved.store=c.store
38797
40248
  resolved.qi=c.qi
38798
40249
  resolved.path=c.path
@@ -38800,7 +40251,7 @@ resolved.url=c.url
38800
40251
  resolved.redirect=c.redirect
38801
40252
  resolved.set=c.set
38802
40253
  resolved.error=c.error
38803
- c=resolved}` : fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){" + mapResponse2("resolved") + `}else Object.assign(c, resolved)
40254
+ c=resolved}` : fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){" + mapResponse3("resolved") + `}else Object.assign(c, resolved)
38804
40255
  `, endUnit();
38805
40256
  else if (!returning)
38806
40257
  fnLiteral += isAsync(beforeHandle) ? `await e.beforeHandle[${i}](c)
@@ -38856,7 +40307,8 @@ if(mr!==undefined)be=c.response=c.responseValue=mr}`, endUnit2();
38856
40307
  return () => {
38857
40308
  hasTrace && (fnLiteral += 'if(r&&(r[Symbol.iterator]||r[Symbol.asyncIterator])&&typeof r.next==="function"){' + (maybeAsync ? "" : "(async()=>{") + `const stream=await tee(r,3)
38858
40309
  r=stream[0]
38859
- const listener=stream[1]
40310
+ ` + (hooks.afterHandle?.length ? `c.response=c.responseValue=r
40311
+ ` : "") + `const listener=stream[1]
38860
40312
  ` + (hasTrace || hooks.afterResponse?.length ? `afterHandlerStreamListener=stream[2]
38861
40313
  ` : "") + `${setImmediateFn}(async ()=>{if(listener)for await(const v of listener){}
38862
40314
  `, handleReporter.resolve(), fnLiteral += "})" + (maybeAsync ? "" : "})()") + "}else{", handleReporter.resolve(), fnLiteral += `}
@@ -38894,7 +40346,7 @@ const listener=stream[1]
38894
40346
  if(mr!==undefined)r=c.response=c.responseValue=mr
38895
40347
  `, endUnit();
38896
40348
  }
38897
- mapResponseReporter.resolve(), fnLiteral += mapResponse2();
40349
+ mapResponseReporter.resolve(), fnLiteral += mapResponse3();
38898
40350
  } else {
38899
40351
  const resolveHandler = reportHandler(isHandleFn ? handler.name : undefined);
38900
40352
  if (validator.response || hooks.mapResponse?.length || hasTrace) {
@@ -38918,7 +40370,7 @@ if(mr!==undefined)r=c.response=c.responseValue=mr}
38918
40370
  }
38919
40371
  mapResponseReporter.resolve(), fnLiteral += encodeCookie(), handler instanceof Response ? (fnLiteral += afterResponse(), fnLiteral += inference.set ? `if(isNotEmpty(c.set.headers)||c.set.status!==200||c.set.redirect||c.set.cookie)return mapResponse(${saveResponse}${handle}.clone(),c.set${mapResponseContext})
38920
40372
  else return ${handle}.clone()` : `return ${handle}.clone()`, fnLiteral += `
38921
- `) : fnLiteral += mapResponse2();
40373
+ `) : fnLiteral += mapResponse3();
38922
40374
  } else if (hasCookie || hasTrace) {
38923
40375
  fnLiteral += isAsyncHandler ? `let r=await ${handle}
38924
40376
  ` : `let r=${handle}
@@ -38935,14 +40387,14 @@ else return ${handle}.clone()` : `return ${handle}.clone()`, fnLiteral += `
38935
40387
  if(mr!==undefined)r=c.response=c.responseValue=mr}`, endUnit();
38936
40388
  }
38937
40389
  }
38938
- mapResponseReporter.resolve(), fnLiteral += encodeCookie() + mapResponse2();
40390
+ mapResponseReporter.resolve(), fnLiteral += encodeCookie() + mapResponse3();
38939
40391
  } else {
38940
40392
  resolveHandler();
38941
40393
  const handled = isAsyncHandler ? `await ${handle}` : handle;
38942
40394
  handler instanceof Response ? (fnLiteral += afterResponse(), fnLiteral += inference.set ? `if(isNotEmpty(c.set.headers)||c.set.status!==200||c.set.redirect||c.set.cookie)return mapResponse(${saveResponse}${handle}.clone(),c.set${mapResponseContext})
38943
40395
  else return ${handle}.clone()
38944
40396
  ` : `return ${handle}.clone()
38945
- `) : fnLiteral += mapResponse2(handled);
40397
+ `) : fnLiteral += mapResponse3(handled);
38946
40398
  }
38947
40399
  }
38948
40400
  if (fnLiteral += `
@@ -38975,7 +40427,7 @@ if(er instanceof Promise)er=await er
38975
40427
  const mapResponse22 = hooks.mapResponse[i2], endUnit2 = mapResponseReporter.resolveChild(mapResponse22.fn.name);
38976
40428
  fnLiteral += `c.response=c.responseValue=er
38977
40429
  mep=e.mapResponse[${i2}](c)
38978
- if(mep instanceof Promise)er=await er
40430
+ if(mep instanceof Promise)mep=await mep
38979
40431
  if(mep!==undefined)er=mep
38980
40432
  `, endUnit2();
38981
40433
  }
@@ -39260,9 +40712,9 @@ error.message=error.response}if(set.status===200||!set.status)set.status=error.s
39260
40712
  });
39261
40713
  if (hooks.mapResponse?.length)
39262
40714
  for (let i2 = 0;i2 < hooks.mapResponse.length; i2++) {
39263
- const mapResponse2 = hooks.mapResponse[i2], endUnit = mapResponseReporter2.resolveChild(mapResponse2.fn.name);
40715
+ const mapResponse3 = hooks.mapResponse[i2], endUnit = mapResponseReporter2.resolveChild(mapResponse3.fn.name);
39264
40716
  fnLiteral += `context.response=context.responseValue=_r
39265
- _r=${isAsyncName(mapResponse2) ? "await " : ""}onMapResponse[${i2}](context)
40717
+ _r=${isAsyncName(mapResponse3) ? "await " : ""}onMapResponse[${i2}](context)
39266
40718
  `, endUnit();
39267
40719
  }
39268
40720
  mapResponseReporter2.resolve(), fnLiteral += afterResponse() + `return mapResponse(${saveResponse}_r,set${adapter.mapResponseContext})}`;
@@ -39287,8 +40739,8 @@ if(!context.response)context.response=context.responseValue=error.message??error
39287
40739
  fnLiteral += `let mr
39288
40740
  `;
39289
40741
  for (let i = 0;i < hooks.mapResponse.length; i++) {
39290
- const mapResponse2 = hooks.mapResponse[i], endUnit = mapResponseReporter.resolveChild(mapResponse2.fn.name);
39291
- fnLiteral += `if(mr===undefined){mr=${isAsyncName(mapResponse2) ? "await " : ""}onMapResponse[${i}](context)
40742
+ const mapResponse3 = hooks.mapResponse[i], endUnit = mapResponseReporter.resolveChild(mapResponse3.fn.name);
40743
+ fnLiteral += `if(mr===undefined){mr=${isAsyncName(mapResponse3) ? "await " : ""}onMapResponse[${i}](context)
39292
40744
  if(mr!==undefined)error=context.response=context.responseValue=mr}`, endUnit();
39293
40745
  }
39294
40746
  }
@@ -39312,587 +40764,6 @@ return mapResponse(${saveResponse}error,set${adapter.mapResponseContext})}`;
39312
40764
  });
39313
40765
  };
39314
40766
 
39315
- // ../../node_modules/elysia/dist/adapter/cloudflare-worker/index.mjs
39316
- function isCloudflareWorker() {
39317
- try {
39318
- if (typeof caches < "u" && typeof caches.default < "u" || typeof WebSocketPair < "u")
39319
- return true;
39320
- } catch {
39321
- return false;
39322
- }
39323
- return false;
39324
- }
39325
- var CloudflareAdapter = {
39326
- ...WebStandardAdapter,
39327
- name: "cloudflare-worker",
39328
- composeGeneralHandler: {
39329
- ...WebStandardAdapter.composeGeneralHandler,
39330
- error404(hasEventHook, hasErrorHook, afterHandle) {
39331
- const { code } = WebStandardAdapter.composeGeneralHandler.error404(hasEventHook, hasErrorHook, afterHandle);
39332
- return {
39333
- code,
39334
- declare: hasErrorHook ? "" : `const error404Message=notFound.message.toString()
39335
- const error404={clone:()=>new Response(error404Message,{status:404})}
39336
- `
39337
- };
39338
- }
39339
- },
39340
- beforeCompile(app) {
39341
- app.handleError = composeErrorHandler(app);
39342
- for (const route of app.routes)
39343
- route.compile();
39344
- },
39345
- listen() {
39346
- return () => {
39347
- console.warn("Cloudflare Worker does not support listen method. Please export default Elysia instance instead.");
39348
- };
39349
- }
39350
- };
39351
-
39352
- // ../../node_modules/elysia/dist/sucrose.mjs
39353
- var separateFunction = (code) => {
39354
- code.startsWith("async") && (code = code.slice(5)), code = code.trimStart();
39355
- let index = -1;
39356
- if (code.charCodeAt(0) === 40 && (index = code.indexOf("=>", code.indexOf(")")), index !== -1)) {
39357
- let bracketEndIndex = index;
39358
- for (;bracketEndIndex > 0 && code.charCodeAt(--bracketEndIndex) !== 41; )
39359
- ;
39360
- let body = code.slice(index + 2);
39361
- return body.charCodeAt(0) === 32 && (body = body.trimStart()), [
39362
- code.slice(1, bracketEndIndex),
39363
- body,
39364
- {
39365
- isArrowReturn: body.charCodeAt(0) !== 123
39366
- }
39367
- ];
39368
- }
39369
- if (/^(\w+)=>/g.test(code) && (index = code.indexOf("=>"), index !== -1)) {
39370
- let body = code.slice(index + 2);
39371
- return body.charCodeAt(0) === 32 && (body = body.trimStart()), [
39372
- code.slice(0, index),
39373
- body,
39374
- {
39375
- isArrowReturn: body.charCodeAt(0) !== 123
39376
- }
39377
- ];
39378
- }
39379
- if (code.startsWith("function")) {
39380
- index = code.indexOf("(");
39381
- const end = code.indexOf(")");
39382
- return [
39383
- code.slice(index + 1, end),
39384
- code.slice(end + 2),
39385
- {
39386
- isArrowReturn: false
39387
- }
39388
- ];
39389
- }
39390
- const start = code.indexOf("(");
39391
- if (start !== -1) {
39392
- const sep = code.indexOf(`
39393
- `, 2), parameter = code.slice(0, sep), end = parameter.lastIndexOf(")") + 1, body = code.slice(sep + 1);
39394
- return [
39395
- parameter.slice(start, end),
39396
- "{" + body,
39397
- {
39398
- isArrowReturn: false
39399
- }
39400
- ];
39401
- }
39402
- const x = code.split(`
39403
- `, 2);
39404
- return [x[0], x[1], { isArrowReturn: false }];
39405
- };
39406
- var bracketPairRange = (parameter) => {
39407
- const start = parameter.indexOf("{");
39408
- if (start === -1)
39409
- return [-1, 0];
39410
- let end = start + 1, deep = 1;
39411
- for (;end < parameter.length; end++) {
39412
- const char = parameter.charCodeAt(end);
39413
- if (char === 123 ? deep++ : char === 125 && deep--, deep === 0)
39414
- break;
39415
- }
39416
- return deep !== 0 ? [0, parameter.length] : [start, end + 1];
39417
- };
39418
- var bracketPairRangeReverse = (parameter) => {
39419
- const end = parameter.lastIndexOf("}");
39420
- if (end === -1)
39421
- return [-1, 0];
39422
- let start = end - 1, deep = 1;
39423
- for (;start >= 0; start--) {
39424
- const char = parameter.charCodeAt(start);
39425
- if (char === 125 ? deep++ : char === 123 && deep--, deep === 0)
39426
- break;
39427
- }
39428
- return deep !== 0 ? [-1, 0] : [start, end + 1];
39429
- };
39430
- var removeColonAlias = (parameter) => {
39431
- for (;; ) {
39432
- const start = parameter.indexOf(":");
39433
- if (start === -1)
39434
- break;
39435
- let end = parameter.indexOf(",", start);
39436
- end === -1 && (end = parameter.indexOf("}", start) - 1), end === -2 && (end = parameter.length), parameter = parameter.slice(0, start) + parameter.slice(end);
39437
- }
39438
- return parameter;
39439
- };
39440
- var retrieveRootParamters = (parameter) => {
39441
- let hasParenthesis = false;
39442
- parameter.charCodeAt(0) === 40 && (parameter = parameter.slice(1, -1)), parameter.charCodeAt(0) === 123 && (hasParenthesis = true, parameter = parameter.slice(1, -1)), parameter = parameter.replace(/( |\t|\n)/g, "").trim();
39443
- let parameters = [];
39444
- for (;; ) {
39445
- let [start, end] = bracketPairRange(parameter);
39446
- if (start === -1)
39447
- break;
39448
- parameters.push(parameter.slice(0, start - 1)), parameter.charCodeAt(end) === 44 && end++, parameter = parameter.slice(end);
39449
- }
39450
- parameter = removeColonAlias(parameter), parameter && (parameters = parameters.concat(parameter.split(",")));
39451
- const parameterMap = /* @__PURE__ */ Object.create(null);
39452
- for (const p of parameters) {
39453
- if (p.indexOf(",") === -1) {
39454
- parameterMap[p] = true;
39455
- continue;
39456
- }
39457
- for (const q of p.split(","))
39458
- parameterMap[q.trim()] = true;
39459
- }
39460
- return {
39461
- hasParenthesis,
39462
- parameters: parameterMap
39463
- };
39464
- };
39465
- var findParameterReference = (parameter, inference) => {
39466
- const { parameters, hasParenthesis } = retrieveRootParamters(parameter);
39467
- return parameters.query && (inference.query = true), parameters.headers && (inference.headers = true), parameters.body && (inference.body = true), parameters.cookie && (inference.cookie = true), parameters.set && (inference.set = true), parameters.server && (inference.server = true), parameters.route && (inference.route = true), parameters.url && (inference.url = true), parameters.path && (inference.path = true), hasParenthesis ? `{ ${Object.keys(parameters).join(", ")} }` : Object.keys(parameters).join(", ");
39468
- };
39469
- var findEndIndex = (type, content, index) => {
39470
- const regex2 = new RegExp(`${type.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\n\\t,; ]`);
39471
- index !== undefined && (regex2.lastIndex = index);
39472
- const match = regex2.exec(content);
39473
- return match ? match.index : -1;
39474
- };
39475
- var findAlias = (type, body, depth = 0) => {
39476
- if (depth > 5)
39477
- return [];
39478
- const aliases = [];
39479
- let content = body;
39480
- for (;; ) {
39481
- let index = findEndIndex(" = " + type, content);
39482
- if (index === -1 && (index = findEndIndex("=" + type, content)), index === -1) {
39483
- let lastIndex = content.indexOf(" = " + type);
39484
- if (lastIndex === -1 && (lastIndex = content.indexOf("=" + type)), lastIndex + 3 + type.length !== content.length)
39485
- break;
39486
- index = lastIndex;
39487
- }
39488
- const part = content.slice(0, index), lastPart = part.lastIndexOf(" ");
39489
- let variable = part.slice(lastPart !== -1 ? lastPart + 1 : -1);
39490
- if (variable === "}") {
39491
- const [start, end] = bracketPairRangeReverse(part);
39492
- aliases.push(removeColonAlias(content.slice(start, end))), content = content.slice(index + 3 + type.length);
39493
- continue;
39494
- }
39495
- for (;variable.charCodeAt(0) === 44; )
39496
- variable = variable.slice(1);
39497
- for (;variable.charCodeAt(0) === 9; )
39498
- variable = variable.slice(1);
39499
- variable.includes("(") || aliases.push(variable), content = content.slice(index + 3 + type.length);
39500
- }
39501
- for (const alias of aliases) {
39502
- if (alias.charCodeAt(0) === 123)
39503
- continue;
39504
- const deepAlias = findAlias(alias, body);
39505
- deepAlias.length > 0 && aliases.push(...deepAlias);
39506
- }
39507
- return aliases;
39508
- };
39509
- var extractMainParameter = (parameter) => {
39510
- if (!parameter)
39511
- return;
39512
- if (parameter.charCodeAt(0) !== 123)
39513
- return parameter;
39514
- if (parameter = parameter.slice(2, -2), !parameter.includes(","))
39515
- return parameter.indexOf("...") !== -1 ? parameter.slice(parameter.indexOf("...") + 3) : undefined;
39516
- const spreadIndex = parameter.indexOf("...");
39517
- if (spreadIndex !== -1)
39518
- return parameter.slice(spreadIndex + 3).trimEnd();
39519
- };
39520
- var inferBodyReference = (code, aliases, inference) => {
39521
- const access = (type, alias) => new RegExp(`${alias}\\.(${type})|${alias}\\["${type}"\\]|${alias}\\['${type}'\\]`).test(code);
39522
- for (const alias of aliases)
39523
- if (alias) {
39524
- if (alias.charCodeAt(0) === 123) {
39525
- const parameters = retrieveRootParamters(alias).parameters;
39526
- parameters.query && (inference.query = true), parameters.headers && (inference.headers = true), parameters.body && (inference.body = true), parameters.cookie && (inference.cookie = true), parameters.set && (inference.set = true), parameters.server && (inference.server = true), parameters.url && (inference.url = true), parameters.route && (inference.route = true), parameters.path && (inference.path = true);
39527
- continue;
39528
- }
39529
- if (!inference.query && (access("query", alias) || code.includes("return " + alias) || code.includes("return " + alias + ".query")) && (inference.query = true), !inference.headers && access("headers", alias) && (inference.headers = true), !inference.body && access("body", alias) && (inference.body = true), !inference.cookie && access("cookie", alias) && (inference.cookie = true), !inference.set && access("set", alias) && (inference.set = true), !inference.server && access("server", alias) && (inference.server = true), !inference.route && access("route", alias) && (inference.route = true), !inference.url && access("url", alias) && (inference.url = true), !inference.path && access("path", alias) && (inference.path = true), inference.query && inference.headers && inference.body && inference.cookie && inference.set && inference.server && inference.route && inference.url && inference.path)
39530
- break;
39531
- }
39532
- return aliases;
39533
- };
39534
- var isContextPassToFunction = (context, body, inference) => {
39535
- try {
39536
- const captureFunction = new RegExp(`\\w\\((?:.*?)?${context}(?:.*?)?\\)`, "gs"), exactParameter = new RegExp(`${context}(,|\\))`, "gs"), length = body.length;
39537
- let fn;
39538
- for (fn = captureFunction.exec(body) + "";captureFunction.lastIndex !== 0 && captureFunction.lastIndex < length + (fn ? fn.length : 0); ) {
39539
- if (fn && exactParameter.test(fn))
39540
- return inference.query = true, inference.headers = true, inference.body = true, inference.cookie = true, inference.set = true, inference.server = true, inference.url = true, inference.route = true, inference.path = true, true;
39541
- fn = captureFunction.exec(body) + "";
39542
- }
39543
- const nextChar = body.charCodeAt(captureFunction.lastIndex);
39544
- return nextChar === 41 || nextChar === 44 ? (inference.query = true, inference.headers = true, inference.body = true, inference.cookie = true, inference.set = true, inference.server = true, inference.url = true, inference.route = true, inference.path = true, true) : false;
39545
- } catch {
39546
- return console.log("[Sucrose] warning: unexpected isContextPassToFunction error, you may continue development as usual but please report the following to maintainers:"), console.log("--- body ---"), console.log(body), console.log("--- context ---"), console.log(context), true;
39547
- }
39548
- };
39549
- var pendingGC;
39550
- var caches2 = {};
39551
- var clearSucroseCache = (delay) => {
39552
- delay === null || isCloudflareWorker() || (delay === undefined && (delay = 4 * 60 * 1000 + 55 * 1000), pendingGC && clearTimeout(pendingGC), pendingGC = setTimeout(() => {
39553
- caches2 = {}, pendingGC = undefined, isBun && Bun.gc(false);
39554
- }, delay), pendingGC.unref?.());
39555
- };
39556
- var mergeInference = (a, b) => ({
39557
- body: a.body || b.body,
39558
- cookie: a.cookie || b.cookie,
39559
- headers: a.headers || b.headers,
39560
- query: a.query || b.query,
39561
- set: a.set || b.set,
39562
- server: a.server || b.server,
39563
- url: a.url || b.url,
39564
- route: a.route || b.route,
39565
- path: a.path || b.path
39566
- });
39567
- var sucrose = (lifeCycle, inference = {
39568
- query: false,
39569
- headers: false,
39570
- body: false,
39571
- cookie: false,
39572
- set: false,
39573
- server: false,
39574
- url: false,
39575
- route: false,
39576
- path: false
39577
- }, settings = {}) => {
39578
- const events = [];
39579
- lifeCycle.request?.length && events.push(...lifeCycle.request), lifeCycle.beforeHandle?.length && events.push(...lifeCycle.beforeHandle), lifeCycle.parse?.length && events.push(...lifeCycle.parse), lifeCycle.error?.length && events.push(...lifeCycle.error), lifeCycle.transform?.length && events.push(...lifeCycle.transform), lifeCycle.afterHandle?.length && events.push(...lifeCycle.afterHandle), lifeCycle.mapResponse?.length && events.push(...lifeCycle.mapResponse), lifeCycle.afterResponse?.length && events.push(...lifeCycle.afterResponse), lifeCycle.handler && typeof lifeCycle.handler == "function" && events.push(lifeCycle.handler);
39580
- for (let i = 0;i < events.length; i++) {
39581
- const e = events[i];
39582
- if (!e)
39583
- continue;
39584
- const event = typeof e == "object" ? e.fn : e;
39585
- if (typeof event != "function")
39586
- continue;
39587
- const content = event.toString(), key = checksum(content), cachedInference = caches2[key];
39588
- if (cachedInference) {
39589
- inference = mergeInference(inference, cachedInference);
39590
- continue;
39591
- }
39592
- clearSucroseCache(settings.gcTime);
39593
- const fnInference = {
39594
- query: false,
39595
- headers: false,
39596
- body: false,
39597
- cookie: false,
39598
- set: false,
39599
- server: false,
39600
- url: false,
39601
- route: false,
39602
- path: false
39603
- }, [parameter, body] = separateFunction(content), rootParameters = findParameterReference(parameter, fnInference), mainParameter = extractMainParameter(rootParameters);
39604
- if (mainParameter) {
39605
- const aliases = findAlias(mainParameter, body.slice(1, -1));
39606
- aliases.splice(0, -1, mainParameter);
39607
- let code = body;
39608
- code.charCodeAt(0) === 123 && code.charCodeAt(body.length - 1) === 125 && (code = code.slice(1, -1).trim()), isContextPassToFunction(mainParameter, code, fnInference) || inferBodyReference(code, aliases, fnInference), !fnInference.query && code.includes("return " + mainParameter + ".query") && (fnInference.query = true);
39609
- }
39610
- if (caches2[key] || (caches2[key] = fnInference), inference = mergeInference(inference, fnInference), inference.query && inference.headers && inference.body && inference.cookie && inference.set && inference.server && inference.url && inference.route && inference.path)
39611
- break;
39612
- }
39613
- return inference;
39614
- };
39615
-
39616
- // ../../node_modules/elysia/dist/adapter/bun/handler.mjs
39617
- var mapResponse2 = (response, set, request) => {
39618
- if (isNotEmpty(set.headers) || set.status !== 200 || set.cookie)
39619
- switch (handleSet(set), response?.constructor?.name) {
39620
- case "String":
39621
- return new Response(response, set);
39622
- case "Array":
39623
- case "Object":
39624
- return set.headers["content-type"] = "application/json", new Response(JSON.stringify(response), set);
39625
- case "ElysiaFile":
39626
- return handleFile(response.value, set);
39627
- case "File":
39628
- return handleFile(response, set);
39629
- case "Blob":
39630
- return handleFile(response, set);
39631
- case "ElysiaCustomStatusResponse":
39632
- return set.status = response.code, mapResponse2(response.response, set, request);
39633
- case undefined:
39634
- return response ? new Response(JSON.stringify(response), set) : new Response("", set);
39635
- case "Response":
39636
- return handleResponse2(response, set, request);
39637
- case "Error":
39638
- return errorToResponse2(response, set);
39639
- case "Promise":
39640
- return response.then((x) => mapResponse2(x, set, request));
39641
- case "Function":
39642
- return mapResponse2(response(), set, request);
39643
- case "Number":
39644
- case "Boolean":
39645
- return new Response(response.toString(), set);
39646
- case "Cookie":
39647
- return response instanceof Cookie ? new Response(response.value, set) : new Response(response?.toString(), set);
39648
- case "FormData":
39649
- return new Response(response, set);
39650
- default:
39651
- if (response instanceof Response)
39652
- return handleResponse2(response, set, request);
39653
- if (response instanceof Promise)
39654
- return response.then((x) => mapResponse2(x, set));
39655
- if (response instanceof Error)
39656
- return errorToResponse2(response, set);
39657
- if (response instanceof ElysiaCustomStatusResponse)
39658
- return set.status = response.code, mapResponse2(response.response, set, request);
39659
- if (typeof response?.next == "function" || response instanceof ReadableStream)
39660
- return handleStream2(response, set, request);
39661
- if (typeof response?.then == "function")
39662
- return response.then((x) => mapResponse2(x, set));
39663
- if (typeof response?.toResponse == "function")
39664
- return mapResponse2(response.toResponse(), set);
39665
- if ("charCodeAt" in response) {
39666
- const code = response.charCodeAt(0);
39667
- if (code === 123 || code === 91)
39668
- return set.headers["Content-Type"] || (set.headers["Content-Type"] = "application/json"), new Response(JSON.stringify(response), set);
39669
- }
39670
- return new Response(response, set);
39671
- }
39672
- return typeof response?.next == "function" || response instanceof ReadableStream ? handleStream2(response, set, request) : mapCompactResponse2(response, request);
39673
- };
39674
- var mapEarlyResponse2 = (response, set, request) => {
39675
- if (response != null)
39676
- if (isNotEmpty(set.headers) || set.status !== 200 || set.cookie)
39677
- switch (handleSet(set), response?.constructor?.name) {
39678
- case "String":
39679
- return new Response(response, set);
39680
- case "Array":
39681
- case "Object":
39682
- return set.headers["content-type"] = "application/json", new Response(JSON.stringify(response), set);
39683
- case "ElysiaFile":
39684
- return handleFile(response.value, set);
39685
- case "File":
39686
- return handleFile(response, set);
39687
- case "Blob":
39688
- return handleFile(response, set);
39689
- case "ElysiaCustomStatusResponse":
39690
- return set.status = response.code, mapEarlyResponse2(response.response, set, request);
39691
- case undefined:
39692
- return response ? new Response(JSON.stringify(response), set) : undefined;
39693
- case "Response":
39694
- return handleResponse2(response, set, request);
39695
- case "Promise":
39696
- return response.then((x) => mapEarlyResponse2(x, set));
39697
- case "Error":
39698
- return errorToResponse2(response, set);
39699
- case "Function":
39700
- return mapEarlyResponse2(response(), set);
39701
- case "Number":
39702
- case "Boolean":
39703
- return new Response(response.toString(), set);
39704
- case "FormData":
39705
- return new Response(response);
39706
- case "Cookie":
39707
- return response instanceof Cookie ? new Response(response.value, set) : new Response(response?.toString(), set);
39708
- default:
39709
- if (response instanceof Response)
39710
- return handleResponse2(response, set, request);
39711
- if (response instanceof Promise)
39712
- return response.then((x) => mapEarlyResponse2(x, set));
39713
- if (response instanceof Error)
39714
- return errorToResponse2(response, set);
39715
- if (response instanceof ElysiaCustomStatusResponse)
39716
- return set.status = response.code, mapEarlyResponse2(response.response, set, request);
39717
- if (typeof response?.next == "function" || response instanceof ReadableStream)
39718
- return handleStream2(response, set, request);
39719
- if (typeof response?.then == "function")
39720
- return response.then((x) => mapEarlyResponse2(x, set));
39721
- if (typeof response?.toResponse == "function")
39722
- return mapEarlyResponse2(response.toResponse(), set);
39723
- if ("charCodeAt" in response) {
39724
- const code = response.charCodeAt(0);
39725
- if (code === 123 || code === 91)
39726
- return set.headers["Content-Type"] || (set.headers["Content-Type"] = "application/json"), new Response(JSON.stringify(response), set);
39727
- }
39728
- return new Response(response, set);
39729
- }
39730
- else
39731
- switch (response?.constructor?.name) {
39732
- case "String":
39733
- return new Response(response);
39734
- case "Array":
39735
- case "Object":
39736
- return set.headers["content-type"] = "application/json", new Response(JSON.stringify(response), set);
39737
- case "ElysiaFile":
39738
- return handleFile(response.value, set);
39739
- case "File":
39740
- return handleFile(response, set);
39741
- case "Blob":
39742
- return handleFile(response, set);
39743
- case "ElysiaCustomStatusResponse":
39744
- return set.status = response.code, mapEarlyResponse2(response.response, set, request);
39745
- case undefined:
39746
- return response ? new Response(JSON.stringify(response), {
39747
- headers: {
39748
- "content-type": "application/json"
39749
- }
39750
- }) : new Response("");
39751
- case "Response":
39752
- return response;
39753
- case "Promise":
39754
- return response.then((x) => {
39755
- const r = mapEarlyResponse2(x, set);
39756
- if (r !== undefined)
39757
- return r;
39758
- });
39759
- case "Error":
39760
- return errorToResponse2(response, set);
39761
- case "Function":
39762
- return mapCompactResponse2(response(), request);
39763
- case "Number":
39764
- case "Boolean":
39765
- return new Response(response.toString());
39766
- case "Cookie":
39767
- return response instanceof Cookie ? new Response(response.value, set) : new Response(response?.toString(), set);
39768
- case "FormData":
39769
- return new Response(response);
39770
- default:
39771
- if (response instanceof Response)
39772
- return response;
39773
- if (response instanceof Promise)
39774
- return response.then((x) => mapEarlyResponse2(x, set));
39775
- if (response instanceof Error)
39776
- return errorToResponse2(response, set);
39777
- if (response instanceof ElysiaCustomStatusResponse)
39778
- return set.status = response.code, mapEarlyResponse2(response.response, set, request);
39779
- if (typeof response?.next == "function" || response instanceof ReadableStream)
39780
- return handleStream2(response, set, request);
39781
- if (typeof response?.then == "function")
39782
- return response.then((x) => mapEarlyResponse2(x, set));
39783
- if (typeof response?.toResponse == "function")
39784
- return mapEarlyResponse2(response.toResponse(), set);
39785
- if ("charCodeAt" in response) {
39786
- const code = response.charCodeAt(0);
39787
- if (code === 123 || code === 91)
39788
- return set.headers["Content-Type"] || (set.headers["Content-Type"] = "application/json"), new Response(JSON.stringify(response), set);
39789
- }
39790
- return new Response(response);
39791
- }
39792
- };
39793
- var mapCompactResponse2 = (response, request) => {
39794
- switch (response?.constructor?.name) {
39795
- case "String":
39796
- return new Response(response);
39797
- case "Object":
39798
- case "Array":
39799
- return new Response(JSON.stringify(response), {
39800
- headers: {
39801
- "Content-Type": "application/json"
39802
- }
39803
- });
39804
- case "ElysiaFile":
39805
- return handleFile(response.value);
39806
- case "File":
39807
- return handleFile(response);
39808
- case "Blob":
39809
- return handleFile(response);
39810
- case "ElysiaCustomStatusResponse":
39811
- return mapResponse2(response.response, {
39812
- status: response.code,
39813
- headers: {}
39814
- });
39815
- case undefined:
39816
- return response ? new Response(JSON.stringify(response), {
39817
- headers: {
39818
- "content-type": "application/json"
39819
- }
39820
- }) : new Response("");
39821
- case "Response":
39822
- return response;
39823
- case "Error":
39824
- return errorToResponse2(response);
39825
- case "Promise":
39826
- return response.then((x) => mapCompactResponse2(x, request));
39827
- case "Function":
39828
- return mapCompactResponse2(response(), request);
39829
- case "Number":
39830
- case "Boolean":
39831
- return new Response(response.toString());
39832
- case "FormData":
39833
- return new Response(response);
39834
- default:
39835
- if (response instanceof Response)
39836
- return response;
39837
- if (response instanceof Promise)
39838
- return response.then((x) => mapCompactResponse2(x, request));
39839
- if (response instanceof Error)
39840
- return errorToResponse2(response);
39841
- if (response instanceof ElysiaCustomStatusResponse)
39842
- return mapResponse2(response.response, {
39843
- status: response.code,
39844
- headers: {}
39845
- });
39846
- if (typeof response?.next == "function" || response instanceof ReadableStream)
39847
- return handleStream2(response, undefined, request);
39848
- if (typeof response?.then == "function")
39849
- return response.then((x) => mapCompactResponse2(x, request));
39850
- if (typeof response?.toResponse == "function")
39851
- return mapCompactResponse2(response.toResponse());
39852
- if ("charCodeAt" in response) {
39853
- const code = response.charCodeAt(0);
39854
- if (code === 123 || code === 91)
39855
- return new Response(JSON.stringify(response), {
39856
- headers: {
39857
- "Content-Type": "application/json"
39858
- }
39859
- });
39860
- }
39861
- return new Response(response);
39862
- }
39863
- };
39864
- var errorToResponse2 = (error, set) => {
39865
- if (typeof error?.toResponse == "function") {
39866
- const raw = error.toResponse(), targetSet = set ?? { headers: {}, status: 200, redirect: "" }, apply = (resolved) => (resolved instanceof Response && (targetSet.status = resolved.status), mapResponse2(resolved, targetSet));
39867
- return typeof raw?.then == "function" ? raw.then(apply) : apply(raw);
39868
- }
39869
- return new Response(JSON.stringify({
39870
- name: error?.name,
39871
- message: error?.message,
39872
- cause: error?.cause
39873
- }), {
39874
- status: set?.status !== 200 ? set?.status ?? 500 : 500,
39875
- headers: set?.headers
39876
- });
39877
- };
39878
- var createStaticHandler2 = (handle, hooks, setHeaders = {}) => {
39879
- if (typeof handle == "function")
39880
- return;
39881
- const response = mapResponse2(handle, {
39882
- headers: setHeaders
39883
- });
39884
- if (!hooks.parse?.length && !hooks.transform?.length && !hooks.beforeHandle?.length && !hooks.afterHandle?.length)
39885
- return () => response.clone();
39886
- };
39887
- var handleResponse2 = createResponseHandler({
39888
- mapResponse: mapResponse2,
39889
- mapCompactResponse: mapCompactResponse2
39890
- });
39891
- var handleStream2 = createStreamHandler({
39892
- mapResponse: mapResponse2,
39893
- mapCompactResponse: mapCompactResponse2
39894
- });
39895
-
39896
40767
  // ../../node_modules/elysia/dist/adapter/bun/compose.mjs
39897
40768
  var allocateIf2 = (value, condition) => condition ? value : "";
39898
40769
  var createContext = (app, route, inference, isInline = false) => {
@@ -39950,14 +40821,14 @@ var createNativeStaticHandler = (handle, hooks, set) => {
39950
40821
  return;
39951
40822
  if (isHTMLBundle(handle))
39952
40823
  return () => handle;
39953
- const response = mapResponse2(handle, set ?? {
40824
+ const response = mapResponse2(handle instanceof Response ? handle.clone() : handle instanceof Promise ? handle.then((x) => x instanceof Response ? x.clone() : isHTMLBundle(x) ? () => x : x) : handle, set ?? {
39954
40825
  headers: {}
39955
40826
  });
39956
40827
  if (!hooks.parse?.length && !hooks.transform?.length && !hooks.beforeHandle?.length && !hooks.afterHandle?.length)
39957
40828
  return response instanceof Promise ? response.then((response2) => {
39958
40829
  if (response2)
39959
- return response2.headers.has("content-type") || response2.headers.append("content-type", "text/plain"), response2.clone();
39960
- }) : (response.headers.has("content-type") || response.headers.append("content-type", "text/plain"), () => response.clone());
40830
+ return response2.clone();
40831
+ }) : () => response.clone();
39961
40832
  };
39962
40833
 
39963
40834
  // ../../node_modules/elysia/dist/ws/index.mjs
@@ -40137,6 +41008,11 @@ var mergeRoutes = (r1, r2) => {
40137
41008
  }
40138
41009
  return r1;
40139
41010
  };
41011
+ var removeTrailingPath = (routes) => {
41012
+ for (const key of Object.keys(routes))
41013
+ key.length > 1 && key.charCodeAt(key.length - 1) === 47 && (routes[key.slice(0, -1)] = routes[key], delete routes[key]);
41014
+ return routes;
41015
+ };
40140
41016
  var BunAdapter = {
40141
41017
  ...WebStandardAdapter,
40142
41018
  name: "bun",
@@ -40193,13 +41069,13 @@ for(const [k,v] of c.request.headers.entries())c.headers[k]=v
40193
41069
  staticRoutes[path] = route;
40194
41070
  }
40195
41071
  return withAsync ? Promise.all(ops).then(() => staticRoutes) : staticRoutes;
40196
- }, serve = typeof options == "object" ? {
41072
+ }, routes = removeTrailingPath(mergeRoutes(mergeRoutes(createStaticRoute(app.router.response), mapRoutes(app)), app.config.serve?.routes)), serve = typeof options == "object" ? {
40197
41073
  development: !isProduction,
40198
41074
  reusePort: true,
40199
41075
  idleTimeout: 30,
40200
41076
  ...app.config.serve || {},
40201
41077
  ...options || {},
40202
- routes: mergeRoutes(mergeRoutes(createStaticRoute(app.router.response), mapRoutes(app)), app.config.serve?.routes),
41078
+ routes,
40203
41079
  websocket: {
40204
41080
  ...app.config.websocket || {},
40205
41081
  ...websocket || {},
@@ -40211,7 +41087,7 @@ for(const [k,v] of c.request.headers.entries())c.headers[k]=v
40211
41087
  reusePort: true,
40212
41088
  idleTimeout: 30,
40213
41089
  ...app.config.serve || {},
40214
- routes: mergeRoutes(mergeRoutes(createStaticRoute(app.router.response), mapRoutes(app)), app.config.serve?.routes),
41090
+ routes,
40215
41091
  websocket: {
40216
41092
  ...app.config.websocket || {},
40217
41093
  ...websocket || {}
@@ -40227,12 +41103,14 @@ for(const [k,v] of c.request.headers.entries())c.headers[k]=v
40227
41103
  for (let i = 0;i < app.event.stop.length; i++)
40228
41104
  app.event.stop[i].fn(app);
40229
41105
  }), app.promisedModules.then(async () => {
40230
- app.config.aot, app.compile(), app.server?.reload({
41106
+ app.config.aot, app.compile();
41107
+ const routes2 = removeTrailingPath(mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response, {
41108
+ withAsync: true
41109
+ }), mapRoutes(app)), app.config.serve?.routes));
41110
+ app.server?.reload({
40231
41111
  ...serve,
40232
41112
  fetch: app.fetch,
40233
- routes: mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response, {
40234
- withAsync: true
40235
- }), mapRoutes(app)), app.config.serve?.routes)
41113
+ routes: routes2
40236
41114
  }), Bun?.gc(false);
40237
41115
  });
40238
41116
  };
@@ -40342,11 +41220,86 @@ for(const [k,v] of c.request.headers.entries())c.headers[k]=v
40342
41220
  }
40343
41221
  };
40344
41222
 
41223
+ // ../../node_modules/elysia/dist/universal/env.mjs
41224
+ var env2 = isBun ? Bun.env : typeof process < "u" && process?.env ? process.env : {};
41225
+
40345
41226
  // ../../node_modules/elysia/dist/dynamic-handle.mjs
41227
+ var ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/;
41228
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
41229
+ var isDangerousKey = (key) => {
41230
+ if (DANGEROUS_KEYS.has(key))
41231
+ return true;
41232
+ const match = key.match(ARRAY_INDEX_REGEX);
41233
+ return match ? DANGEROUS_KEYS.has(match[1]) : false;
41234
+ };
41235
+ var parseArrayKey = (key) => {
41236
+ const match = key.match(ARRAY_INDEX_REGEX);
41237
+ return match ? {
41238
+ name: match[1],
41239
+ index: parseInt(match[2], 10)
41240
+ } : null;
41241
+ };
41242
+ var parseObjectString = (entry) => {
41243
+ if (!(typeof entry != "string" || entry.charCodeAt(0) !== 123))
41244
+ try {
41245
+ const parsed = JSON.parse(entry);
41246
+ if (parsed && typeof parsed == "object" && !Array.isArray(parsed))
41247
+ return parsed;
41248
+ } catch {
41249
+ return;
41250
+ }
41251
+ };
41252
+ var setNestedValue = (obj, path, value) => {
41253
+ const keys = path.split("."), lastKey = keys.pop();
41254
+ if (isDangerousKey(lastKey) || keys.some(isDangerousKey))
41255
+ return;
41256
+ let current = obj;
41257
+ for (const key of keys) {
41258
+ const arrayInfo2 = parseArrayKey(key);
41259
+ if (arrayInfo2) {
41260
+ Array.isArray(current[arrayInfo2.name]) || (current[arrayInfo2.name] = []);
41261
+ const existing = current[arrayInfo2.name][arrayInfo2.index], isFile = typeof File < "u" && existing instanceof File;
41262
+ (!existing || typeof existing != "object" || Array.isArray(existing) || isFile) && (current[arrayInfo2.name][arrayInfo2.index] = parseObjectString(existing) ?? {}), current = current[arrayInfo2.name][arrayInfo2.index];
41263
+ } else
41264
+ (!current[key] || typeof current[key] != "object") && (current[key] = {}), current = current[key];
41265
+ }
41266
+ const arrayInfo = parseArrayKey(lastKey);
41267
+ arrayInfo ? (Array.isArray(current[arrayInfo.name]) || (current[arrayInfo.name] = []), current[arrayInfo.name][arrayInfo.index] = value) : current[lastKey] = value;
41268
+ };
41269
+ var normalizeFormValue = (value) => {
41270
+ if (value.length === 1) {
41271
+ const stringValue2 = value[0];
41272
+ if (typeof stringValue2 == "string" && (stringValue2.charCodeAt(0) === 123 || stringValue2.charCodeAt(0) === 91))
41273
+ try {
41274
+ const parsed2 = JSON.parse(stringValue2);
41275
+ if (parsed2 && typeof parsed2 == "object")
41276
+ return parsed2;
41277
+ } catch {
41278
+ }
41279
+ return value[0];
41280
+ }
41281
+ const stringValue = value.find((entry) => typeof entry == "string");
41282
+ if (!stringValue || typeof File > "u")
41283
+ return value;
41284
+ const files = value.filter((entry) => entry instanceof File);
41285
+ if (!files.length || stringValue.charCodeAt(0) !== 123)
41286
+ return value;
41287
+ let parsed;
41288
+ try {
41289
+ parsed = JSON.parse(stringValue);
41290
+ } catch {
41291
+ return value;
41292
+ }
41293
+ return typeof parsed != "object" || parsed === null ? value : (!("file" in parsed) && files.length === 1 ? parsed.file = files[0] : !("files" in parsed) && files.length > 1 && (parsed.files = files), parsed);
41294
+ };
40346
41295
  var injectDefaultValues = (typeChecker, obj) => {
40347
41296
  let schema = typeChecker.schema;
40348
- if (schema && (schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]), !!schema?.properties))
40349
- for (const [key, keySchema] of Object.entries(schema.properties))
41297
+ if (!schema)
41298
+ return;
41299
+ schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
41300
+ const properties = getSchemaProperties(schema);
41301
+ if (properties)
41302
+ for (const [key, keySchema] of Object.entries(properties))
40350
41303
  obj[key] ??= keySchema.default;
40351
41304
  };
40352
41305
  var createDynamicHandler = (app) => {
@@ -40403,8 +41356,8 @@ var createDynamicHandler = (app) => {
40403
41356
  for (const key of form2.keys()) {
40404
41357
  if (body[key])
40405
41358
  continue;
40406
- const value = form2.getAll(key);
40407
- value.length === 1 ? body[key] = value[0] : body[key] = value;
41359
+ const value = form2.getAll(key), finalValue = normalizeFormValue(value);
41360
+ key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
40408
41361
  }
40409
41362
  break;
40410
41363
  }
@@ -40441,8 +41394,8 @@ var createDynamicHandler = (app) => {
40441
41394
  for (const key of form2.keys()) {
40442
41395
  if (body[key])
40443
41396
  continue;
40444
- const value = form2.getAll(key);
40445
- value.length === 1 ? body[key] = value[0] : body[key] = value;
41397
+ const value = form2.getAll(key), finalValue = normalizeFormValue(value);
41398
+ key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
40446
41399
  }
40447
41400
  break;
40448
41401
  }
@@ -40486,8 +41439,8 @@ var createDynamicHandler = (app) => {
40486
41439
  for (const key of form2.keys()) {
40487
41440
  if (body[key])
40488
41441
  continue;
40489
- const value = form2.getAll(key);
40490
- value.length === 1 ? body[key] = value[0] : body[key] = value;
41442
+ const value = form2.getAll(key), finalValue = normalizeFormValue(value);
41443
+ key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
40491
41444
  }
40492
41445
  break;
40493
41446
  }
@@ -40541,11 +41494,12 @@ var createDynamicHandler = (app) => {
40541
41494
  if (validator.params?.Decode && (context.params = validator.params.Decode(context.params)), validator.query?.schema) {
40542
41495
  let schema = validator.query.schema;
40543
41496
  schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
40544
- const properties = schema.properties;
40545
- for (const property of Object.keys(properties)) {
40546
- const value = properties[property];
40547
- (value.type === "array" || value.items?.type === "string") && typeof context.query[property] == "string" && context.query[property] && (context.query[property] = context.query[property].split(","));
40548
- }
41497
+ const properties = getSchemaProperties(schema);
41498
+ if (properties)
41499
+ for (const property of Object.keys(properties)) {
41500
+ const value = properties[property];
41501
+ (value.type === "array" || value.items?.type === "string") && typeof context.query[property] == "string" && context.query[property] && (context.query[property] = context.query[property].split(","));
41502
+ }
40549
41503
  }
40550
41504
  if (queryValidator?.Check(context.query) === false)
40551
41505
  throw new ValidationError("query", validator.query, context.query);
@@ -40559,7 +41513,10 @@ var createDynamicHandler = (app) => {
40559
41513
  }
40560
41514
  if (validator.createBody?.()?.Check(body) === false)
40561
41515
  throw new ValidationError("body", validator.body, body);
40562
- validator.body?.Decode && (context.body = validator.body.Decode(body));
41516
+ if (validator.body?.Decode) {
41517
+ let decoded = validator.body.Decode(body);
41518
+ decoded instanceof Promise && (decoded = await decoded), context.body = decoded?.value ?? decoded;
41519
+ }
40563
41520
  }
40564
41521
  if (hooks.beforeHandle)
40565
41522
  for (let i = 0;i < hooks.beforeHandle.length; i++) {
@@ -40595,14 +41552,22 @@ var createDynamicHandler = (app) => {
40595
41552
  isCustomStatuResponse && (set.status = status2, response2 = response2.response);
40596
41553
  const responseValidator = validator?.createResponse?.()?.[status2];
40597
41554
  if (responseValidator?.Check(response2) === false)
40598
- if (responseValidator?.Clean) {
40599
- const temp = responseValidator.Clean(response2);
40600
- if (responseValidator?.Check(temp) === false)
40601
- throw new ValidationError("response", responseValidator, response2);
40602
- response2 = temp;
40603
- } else
41555
+ if (responseValidator?.Clean)
41556
+ try {
41557
+ const temp = responseValidator.Clean(response2);
41558
+ if (responseValidator?.Check(temp) === false)
41559
+ throw new ValidationError("response", responseValidator, response2);
41560
+ response2 = temp;
41561
+ } catch (error) {
41562
+ throw error instanceof ValidationError ? error : new ValidationError("response", responseValidator, response2);
41563
+ }
41564
+ else
40604
41565
  throw new ValidationError("response", responseValidator, response2);
40605
- responseValidator?.Encode && (context.response = response2 = responseValidator.Encode(response2)), responseValidator?.Clean && (context.response = response2 = responseValidator.Clean(response2));
41566
+ if (responseValidator?.Encode && (context.response = response2 = responseValidator.Encode(response2)), responseValidator?.Clean)
41567
+ try {
41568
+ context.response = response2 = responseValidator.Clean(response2);
41569
+ } catch {
41570
+ }
40606
41571
  const result = mapEarlyResponse3(response2, context.set);
40607
41572
  if (result !== undefined)
40608
41573
  return context.response = result;
@@ -40612,14 +41577,22 @@ var createDynamicHandler = (app) => {
40612
41577
  isCustomStatuResponse && (set.status = status2, response = response.response);
40613
41578
  const responseValidator = validator?.createResponse?.()?.[status2];
40614
41579
  if (responseValidator?.Check(response) === false)
40615
- if (responseValidator?.Clean) {
40616
- const temp = responseValidator.Clean(response);
40617
- if (responseValidator?.Check(temp) === false)
40618
- throw new ValidationError("response", responseValidator, response);
40619
- response = temp;
40620
- } else
41580
+ if (responseValidator?.Clean)
41581
+ try {
41582
+ const temp = responseValidator.Clean(response);
41583
+ if (responseValidator?.Check(temp) === false)
41584
+ throw new ValidationError("response", responseValidator, response);
41585
+ response = temp;
41586
+ } catch (error) {
41587
+ throw error instanceof ValidationError ? error : new ValidationError("response", responseValidator, response);
41588
+ }
41589
+ else
40621
41590
  throw new ValidationError("response", responseValidator, response);
40622
- responseValidator?.Encode && (response = responseValidator.Encode(response)), responseValidator?.Clean && (response = responseValidator.Clean(response));
41591
+ if (responseValidator?.Encode && (response = responseValidator.Encode(response)), responseValidator?.Clean)
41592
+ try {
41593
+ response = responseValidator.Clean(response);
41594
+ } catch {
41595
+ }
40623
41596
  }
40624
41597
  if (context.set.cookie && cookieMeta?.sign) {
40625
41598
  const secret = cookieMeta.secrets ? typeof cookieMeta.secrets == "string" ? cookieMeta.secrets : cookieMeta.secrets[0] : undefined;
@@ -40628,10 +41601,10 @@ var createDynamicHandler = (app) => {
40628
41601
  for (const [key, cookie] of Object.entries(context.set.cookie))
40629
41602
  context.set.cookie[key].value = await signCookie(cookie.value, secret);
40630
41603
  } else {
40631
- const properties = validator?.cookie?.schema?.properties;
41604
+ const properties = getSchemaProperties(validator?.cookie?.schema);
40632
41605
  if (secret)
40633
41606
  for (const name of cookieMeta.sign)
40634
- name in properties && context.set.cookie[name]?.value && (context.set.cookie[name].value = await signCookie(context.set.cookie[name].value, secret));
41607
+ !properties || !(name in properties) || context.set.cookie[name]?.value && (context.set.cookie[name].value = await signCookie(context.set.cookie[name].value, secret));
40635
41608
  }
40636
41609
  }
40637
41610
  return mapResponse3(context.response = response, context.set);
@@ -41264,7 +42237,7 @@ var _Elysia = class _Elysia2 {
41264
42237
  }, this.inference, this.config.sucrose));
41265
42238
  for (const handle of handles) {
41266
42239
  const fn = asHookType(handle, "global", { skipIfHasType: true });
41267
- switch (type) {
42240
+ switch ((this.config.name || this.config.seed) && (fn.checksum = checksum(this.config.name + JSON.stringify(this.config.seed))), type) {
41268
42241
  case "start":
41269
42242
  this.event.start ??= [], this.event.start.push(fn);
41270
42243
  break;
@@ -41412,7 +42385,7 @@ var _Elysia = class _Elysia2 {
41412
42385
  });
41413
42386
  instance.singleton = { ...this.singleton }, instance.definitions = { ...this.definitions }, instance.inference = cloneInference(this.inference), instance.extender = { ...this.extender }, instance.getServer = () => this.getServer();
41414
42387
  const sandbox = run(instance);
41415
- return this.singleton = mergeDeep(this.singleton, instance.singleton), this.definitions = mergeDeep(this.definitions, instance.definitions), sandbox.getServer = () => this.server, sandbox.event.request?.length && (this.event.request = [
42388
+ if (this.singleton = mergeDeep(this.singleton, instance.singleton), this.definitions = mergeDeep(this.definitions, instance.definitions), sandbox.getServer = () => this.server, sandbox.event.request?.length && (this.event.request = [
41416
42389
  ...this.event.request || [],
41417
42390
  ...sandbox.event.request || []
41418
42391
  ]), sandbox.event.mapResponse?.length && (this.event.mapResponse = [
@@ -41449,7 +42422,52 @@ var _Elysia = class _Elysia2 {
41449
42422
  }
41450
42423
  ] : localHook.standaloneValidator
41451
42424
  }));
41452
- }), this;
42425
+ }), instance.promisedModules.size > 0) {
42426
+ let processedUntil = instance.router.history.length;
42427
+ for (const promise of instance.promisedModules.promises)
42428
+ this.promisedModules.add(promise.then(() => {
42429
+ const {
42430
+ body,
42431
+ headers,
42432
+ query,
42433
+ params,
42434
+ cookie,
42435
+ response,
42436
+ ...guardHook
42437
+ } = hook, hasStandaloneSchema = body || headers || query || params || cookie || response, startIndex = processedUntil;
42438
+ processedUntil = instance.router.history.length;
42439
+ for (let i = startIndex;i < instance.router.history.length; i++) {
42440
+ const {
42441
+ method,
42442
+ path,
42443
+ handler,
42444
+ hooks: localHook
42445
+ } = instance.router.history[i];
42446
+ this.add(method, path, handler, mergeHook(guardHook, {
42447
+ ...localHook || {},
42448
+ error: localHook.error ? Array.isArray(localHook.error) ? [
42449
+ ...localHook.error ?? [],
42450
+ ...sandbox.event.error ?? []
42451
+ ] : [
42452
+ localHook.error,
42453
+ ...sandbox.event.error ?? []
42454
+ ] : sandbox.event.error,
42455
+ standaloneValidator: hasStandaloneSchema ? [
42456
+ ...localHook.standaloneValidator ?? [],
42457
+ {
42458
+ body,
42459
+ headers,
42460
+ query,
42461
+ params,
42462
+ cookie,
42463
+ response
42464
+ }
42465
+ ] : localHook.standaloneValidator
42466
+ }));
42467
+ }
42468
+ }));
42469
+ }
42470
+ return this;
41453
42471
  }
41454
42472
  use(plugin) {
41455
42473
  if (!plugin)
@@ -41650,19 +42668,7 @@ var _Elysia = class _Elysia2 {
41650
42668
  if (path instanceof _Elysia2 || typeof path == "function" || path.length === 0 || path === "/") {
41651
42669
  const run = typeof path == "function" ? path : path instanceof _Elysia2 ? path.compile().fetch : handleOrConfig instanceof _Elysia2 ? handleOrConfig.compile().fetch : typeof handleOrConfig == "function" ? handleOrConfig : (() => {
41652
42670
  throw new Error("Invalid handler");
41653
- })(), handler2 = ({ request, path: path2 }) => run(new Request(replaceUrlPath(request.url, path2), {
41654
- method: request.method,
41655
- headers: request.headers,
41656
- signal: request.signal,
41657
- credentials: request.credentials,
41658
- referrerPolicy: request.referrerPolicy,
41659
- duplex: request.duplex,
41660
- redirect: request.redirect,
41661
- mode: request.mode,
41662
- keepalive: request.keepalive,
41663
- integrity: request.integrity,
41664
- body: request.body
41665
- }));
42671
+ })(), handler2 = ({ request, path: path2 }) => run(new Request(replaceUrlPath(request.url, path2), request));
41666
42672
  return this.route("ALL", "/*", handler2, {
41667
42673
  parse: "none",
41668
42674
  ...config,
@@ -41677,19 +42683,7 @@ var _Elysia = class _Elysia2 {
41677
42683
  }
41678
42684
  const handle = handleOrConfig instanceof _Elysia2 ? handleOrConfig.compile().fetch : typeof handleOrConfig == "function" ? handleOrConfig : (() => {
41679
42685
  throw new Error("Invalid handler");
41680
- })(), length = (typeof path == "string" && this.config.prefix ? this.config.prefix + path : path).length - (path.endsWith("*") ? 1 : 0), handler = ({ request, path: path2 }) => handle(new Request(replaceUrlPath(request.url, path2.slice(length) || "/"), {
41681
- method: request.method,
41682
- headers: request.headers,
41683
- signal: request.signal,
41684
- credentials: request.credentials,
41685
- referrerPolicy: request.referrerPolicy,
41686
- duplex: request.duplex,
41687
- redirect: request.redirect,
41688
- mode: request.mode,
41689
- keepalive: request.keepalive,
41690
- integrity: request.integrity,
41691
- body: request.body
41692
- }));
42686
+ })(), length = (typeof path == "string" && this.config.prefix ? this.config.prefix + path : path).length - (path.endsWith("*") ? 1 : 0), handler = ({ request, path: path2 }) => handle(new Request(replaceUrlPath(request.url, path2.slice(length) || "/"), request));
41693
42687
  return this.route("ALL", path, handler, {
41694
42688
  parse: "none",
41695
42689
  ...config,
@@ -41983,13 +42977,14 @@ async function createDoneHttpLocalServer(config, chain) {
41983
42977
  set.headers["access-control-allow-methods"] = "GET,POST,OPTIONS";
41984
42978
  }).options("*", ({ set }) => {
41985
42979
  set.status = 204;
41986
- }).get("/healthz", () => ({ ok: true, height: runtime.height })).post("/contracts/js", async ({ body, set }) => {
42980
+ }).get("/healthz", () => ({ ok: true, height: runtime.height, updated: true })).post("/contracts/js", async ({ body, set }) => {
41987
42981
  const payload = body;
41988
42982
  try {
41989
42983
  if (!payload.script && !payload.script_path) {
41990
42984
  set.status = 400;
41991
42985
  return { error: "provide script or script_path" };
41992
42986
  }
42987
+ console.log("deploying...");
41993
42988
  const result = await deployJsContract({
41994
42989
  chain: runtime,
41995
42990
  sender: config.owner,
@@ -42042,6 +43037,7 @@ async function createDoneHttpLocalServer(config, chain) {
42042
43037
  try {
42043
43038
  const msg = decodeQueryMsg(query.msg);
42044
43039
  const result = runtime.query(params.address, msg);
43040
+ console.log("Query result:", result);
42045
43041
  return unwrapQueryResult(result);
42046
43042
  } catch (error) {
42047
43043
  set.status = 400;
@@ -42419,6 +43415,24 @@ var createEventStream = (pubsub, subscriptionPath) => {
42419
43415
  });
42420
43416
  };
42421
43417
  // src/index.ts
43418
+ function readCliPackageMetadata() {
43419
+ try {
43420
+ const pkgUrl = new URL("../package.json", import.meta.url);
43421
+ const raw = readFileSync3(pkgUrl);
43422
+ return JSON.parse(raw.toString("utf8"));
43423
+ } catch {
43424
+ return {};
43425
+ }
43426
+ }
43427
+ function normalizeVersion(value) {
43428
+ if (typeof value === "string" && value.trim().length > 0) {
43429
+ return value.trim();
43430
+ }
43431
+ return null;
43432
+ }
43433
+ function toCaretRange(version) {
43434
+ return version.startsWith("^") ? version : `^${version}`;
43435
+ }
42422
43436
  function notImplemented(label) {
42423
43437
  console.error(`The command segment '${label}' is not implemented yet.\nSee packages/done-cli/SPEC.md for the planned behaviour.`);
42424
43438
  process.exit(1);
@@ -42461,7 +43475,7 @@ async function handleBuild(options) {
42461
43475
  const entryPath = path.resolve(manifestInfo.manifestDir, contract.entry);
42462
43476
  const outFilePath = path.resolve(manifestInfo.manifestDir, contract.outFile);
42463
43477
  await ensureEntryExists(entryPath, contract.name);
42464
- await fs.mkdir(path.dirname(outFilePath), { recursive: true });
43478
+ await fs2.mkdir(path.dirname(outFilePath), { recursive: true });
42465
43479
  const relEntry = path.relative(process.cwd(), entryPath) || entryPath;
42466
43480
  const relOutFile = path.relative(process.cwd(), outFilePath) || outFilePath;
42467
43481
  console.log(`- bundling ${contract.name} (${relEntry})`);
@@ -42479,7 +43493,7 @@ async function handleBuild(options) {
42479
43493
  async function handlePublish(options) {
42480
43494
  const scriptPath = path.resolve(process.cwd(), options.script);
42481
43495
  await ensureFileExists(scriptPath, "script");
42482
- const script = await fs.readFile(scriptPath, "utf8");
43496
+ const script = await fs2.readFile(scriptPath, "utf8");
42483
43497
  const msg = options.msg ? await loadMsgPayload(options.msg) : undefined;
42484
43498
  const baseUrl = resolveDoneHttpBase(options.http);
42485
43499
  const backend = new DoneBackendClient({ baseUrl });
@@ -42503,7 +43517,7 @@ async function detectWorkspace(root) {
42503
43517
  if (!existsSync2(configPath)) {
42504
43518
  return null;
42505
43519
  }
42506
- const configRaw = await fs.readFile(configPath, "utf8");
43520
+ const configRaw = await fs2.readFile(configPath, "utf8");
42507
43521
  const config2 = JSON.parse(configRaw);
42508
43522
  const configuredManifestPath = config2.contractsFile ? path.isAbsolute(config2.contractsFile) ? config2.contractsFile : path.resolve(root, config2.contractsFile) : path.join(root, "done.json");
42509
43523
  const fallbackManifestPath = path.join(root, "done.json");
@@ -42511,7 +43525,7 @@ async function detectWorkspace(root) {
42511
43525
  if (!manifestPath) {
42512
43526
  return null;
42513
43527
  }
42514
- const manifestRaw = await fs.readFile(manifestPath, "utf8");
43528
+ const manifestRaw = await fs2.readFile(manifestPath, "utf8");
42515
43529
  const manifest = JSON.parse(manifestRaw);
42516
43530
  return { root, manifestPath, configPath, manifest, config: config2 };
42517
43531
  }
@@ -42544,7 +43558,7 @@ async function findWorkspace(startDir) {
42544
43558
  async function readManifest(manifestPath) {
42545
43559
  let raw;
42546
43560
  try {
42547
- raw = await fs.readFile(manifestPath, "utf8");
43561
+ raw = await fs2.readFile(manifestPath, "utf8");
42548
43562
  } catch (error) {
42549
43563
  if (error.code === "ENOENT") {
42550
43564
  throw new Error(`Could not find ${manifestPath}. Pass a valid --contracts path or run from a Done workspace.`);
@@ -42568,7 +43582,7 @@ async function scaffoldWorkspace(rawName, options) {
42568
43582
  await prepareTargetDir(targetDir, options.force === true);
42569
43583
  const localTemplatePath = await resolveLocalTemplate(templateRef);
42570
43584
  if (localTemplatePath) {
42571
- await fs.cp(localTemplatePath, targetDir, { recursive: true });
43585
+ await fs2.cp(localTemplatePath, targetDir, { recursive: true });
42572
43586
  } else {
42573
43587
  await runCommand("git", ["clone", "--depth", "1", templateRef, targetDir]);
42574
43588
  }
@@ -42579,6 +43593,7 @@ async function scaffoldWorkspace(rawName, options) {
42579
43593
  await updatePackageJson(path.join(targetDir, "frontend", "package.json"), (pkg) => {
42580
43594
  pkg.name = `${slug}-frontend`;
42581
43595
  });
43596
+ await syncWorkspaceDependencyVersions(targetDir);
42582
43597
  if (options.install !== false) {
42583
43598
  await runCommand("bun", ["install"], { cwd: targetDir });
42584
43599
  }
@@ -42599,7 +43614,7 @@ async function scaffoldContract(workspace, rawName, options) {
42599
43614
  const contractsDir = resolveContractsDir(workspace.root, workspace.config.contractsDir);
42600
43615
  const contractDir = path.join(contractsDir, slug);
42601
43616
  await ensureDirAvailable(contractDir, options.force === true);
42602
- await fs.mkdir(path.join(contractDir, "src"), { recursive: true });
43617
+ await fs2.mkdir(path.join(contractDir, "src"), { recursive: true });
42603
43618
  const pkgJsonPath = path.join(contractDir, "package.json");
42604
43619
  const pkgJson = {
42605
43620
  name: slug,
@@ -42610,7 +43625,7 @@ async function scaffoldContract(workspace, rawName, options) {
42610
43625
  typecheck: "tsc -p tsconfig.json --noEmit"
42611
43626
  },
42612
43627
  dependencies: {
42613
- "done.zone": "^0.1.0"
43628
+ "done.zone": DONE_ZONE_VERSION_RANGE
42614
43629
  }
42615
43630
  };
42616
43631
  await writeJson(pkgJsonPath, pkgJson);
@@ -42673,7 +43688,7 @@ export default Done.serve()
42673
43688
  },
42674
43689
  );
42675
43690
  `;
42676
- await fs.writeFile(path.join(contractDir, "src", "index.ts"), contractSource, "utf8");
43691
+ await fs2.writeFile(path.join(contractDir, "src", "index.ts"), contractSource, "utf8");
42677
43692
  workspace.manifest.contracts ??= [];
42678
43693
  const contractDirRel = normalizeJsonPath(path.relative(workspace.root, contractDir));
42679
43694
  const entry = ensureDotSlash(`${contractDirRel}/src/index.ts`);
@@ -42704,7 +43719,7 @@ export default Done.serve()
42704
43719
  async function resolveLocalTemplate(reference) {
42705
43720
  const potentialPath = path.isAbsolute(reference) ? reference : path.resolve(process.cwd(), reference);
42706
43721
  try {
42707
- const stats = await fs.stat(potentialPath);
43722
+ const stats = await fs2.stat(potentialPath);
42708
43723
  if (stats.isDirectory()) {
42709
43724
  return potentialPath;
42710
43725
  }
@@ -42719,7 +43734,7 @@ async function prepareTargetDir(targetDir, force) {
42719
43734
  if (!force) {
42720
43735
  throw new Error(`Directory '${path.relative(process.cwd(), targetDir) || targetDir}' already exists. Use --force to overwrite.`);
42721
43736
  }
42722
- await fs.rm(targetDir, { recursive: true, force: true });
43737
+ await fs2.rm(targetDir, { recursive: true, force: true });
42723
43738
  }
42724
43739
  async function ensureDirAvailable(targetDir, force) {
42725
43740
  if (!existsSync2(targetDir)) {
@@ -42728,10 +43743,10 @@ async function ensureDirAvailable(targetDir, force) {
42728
43743
  if (!force) {
42729
43744
  throw new Error(`Directory '${path.relative(process.cwd(), targetDir) || targetDir}' already exists. Use --force to overwrite.`);
42730
43745
  }
42731
- await fs.rm(targetDir, { recursive: true, force: true });
43746
+ await fs2.rm(targetDir, { recursive: true, force: true });
42732
43747
  }
42733
43748
  async function removeGitFolder(targetDir) {
42734
- await fs.rm(path.join(targetDir, ".git"), { recursive: true, force: true });
43749
+ await fs2.rm(path.join(targetDir, ".git"), { recursive: true, force: true });
42735
43750
  }
42736
43751
  function resolveContractsDir(root, configured) {
42737
43752
  if (!configured) {
@@ -42744,7 +43759,7 @@ function resolveContractsDir(root, configured) {
42744
43759
  }
42745
43760
  async function updatePackageJson(file2, mutator) {
42746
43761
  try {
42747
- const current = JSON.parse(await fs.readFile(file2, "utf8"));
43762
+ const current = JSON.parse(await fs2.readFile(file2, "utf8"));
42748
43763
  mutator(current);
42749
43764
  await writeJson(file2, current);
42750
43765
  } catch (error) {
@@ -42761,6 +43776,50 @@ function normalizeJsonPath(relativePath) {
42761
43776
  const normalized = relativePath.split(path.sep).join("/");
42762
43777
  return normalized.startsWith("./") || normalized.startsWith("../") ? normalized : `./${normalized}`;
42763
43778
  }
43779
+ function ensureDependency(pkg, field, name, version) {
43780
+ const bucket = pkg[field] ??= {};
43781
+ bucket[name] = version;
43782
+ }
43783
+ function updateDependencyIfPresent(pkg, name, version) {
43784
+ let updated = false;
43785
+ const fields = ["dependencies", "devDependencies"];
43786
+ for (const field of fields) {
43787
+ const bucket = pkg[field];
43788
+ if (bucket && typeof bucket === "object" && bucket[name]) {
43789
+ bucket[name] = version;
43790
+ updated = true;
43791
+ }
43792
+ }
43793
+ return updated;
43794
+ }
43795
+ async function syncWorkspaceDependencyVersions(targetDir) {
43796
+ await updatePackageJson(path.join(targetDir, "package.json"), (pkg) => {
43797
+ ensureDependency(pkg, "devDependencies", "@donezone/cli", CLI_VERSION_RANGE);
43798
+ ensureDependency(pkg, "devDependencies", "done.zone", DONE_ZONE_VERSION_RANGE);
43799
+ });
43800
+ await updatePackageJson(path.join(targetDir, "frontend", "package.json"), (pkg) => {
43801
+ if (!updateDependencyIfPresent(pkg, "@donezone/client", DONE_CLIENT_VERSION_RANGE)) {
43802
+ ensureDependency(pkg, "dependencies", "@donezone/client", DONE_CLIENT_VERSION_RANGE);
43803
+ }
43804
+ });
43805
+ await updateContractDependencyVersions(path.join(targetDir, "contracts"));
43806
+ }
43807
+ async function updateContractDependencyVersions(contractsDir) {
43808
+ let entries;
43809
+ try {
43810
+ entries = await fs2.readdir(contractsDir, { withFileTypes: true });
43811
+ } catch {
43812
+ return;
43813
+ }
43814
+ await Promise.all(entries.filter((entry) => entry.isDirectory()).map(async (entry) => {
43815
+ const pkgPath = path.join(contractsDir, entry.name, "package.json");
43816
+ await updatePackageJson(pkgPath, (pkg) => {
43817
+ if (!updateDependencyIfPresent(pkg, "done.zone", DONE_ZONE_VERSION_RANGE)) {
43818
+ ensureDependency(pkg, "dependencies", "done.zone", DONE_ZONE_VERSION_RANGE);
43819
+ }
43820
+ });
43821
+ }));
43822
+ }
42764
43823
  function matchesContract(contract, manifestDir, matchers) {
42765
43824
  const candidates = [];
42766
43825
  if (contract.name) {
@@ -42801,7 +43860,7 @@ function escapeRegExp(value) {
42801
43860
  }
42802
43861
  async function ensureEntryExists(entryPath, contractName) {
42803
43862
  try {
42804
- const stats = await fs.stat(entryPath);
43863
+ const stats = await fs2.stat(entryPath);
42805
43864
  if (!stats.isFile()) {
42806
43865
  const relPath = path.relative(process.cwd(), entryPath) || entryPath;
42807
43866
  throw new Error(`Entry path for contract '${contractName}' is not a file (${relPath})`);
@@ -42816,7 +43875,7 @@ async function ensureEntryExists(entryPath, contractName) {
42816
43875
  }
42817
43876
  async function ensureFileExists(filePath, label) {
42818
43877
  try {
42819
- const stats = await fs.stat(filePath);
43878
+ const stats = await fs2.stat(filePath);
42820
43879
  if (!stats.isFile()) {
42821
43880
  throw new Error(`The ${label} path is not a file (${filePath})`);
42822
43881
  }
@@ -42830,7 +43889,7 @@ async function ensureFileExists(filePath, label) {
42830
43889
  async function loadMsgPayload(input) {
42831
43890
  const potentialPath = path.resolve(process.cwd(), input);
42832
43891
  if (await pathExists(potentialPath)) {
42833
- const raw = await fs.readFile(potentialPath, "utf8");
43892
+ const raw = await fs2.readFile(potentialPath, "utf8");
42834
43893
  return JSON.parse(raw);
42835
43894
  }
42836
43895
  return JSON.parse(input);
@@ -42840,7 +43899,7 @@ function resolveDoneHttpBase(override) {
42840
43899
  }
42841
43900
  async function pathExists(candidate) {
42842
43901
  try {
42843
- await fs.access(candidate);
43902
+ await fs2.access(candidate);
42844
43903
  return true;
42845
43904
  } catch {
42846
43905
  return false;
@@ -42869,7 +43928,7 @@ async function runBunBuild(entryPath, outFilePath) {
42869
43928
  throw new Error("Bun.build did not emit an output file");
42870
43929
  }
42871
43930
  const bundledSource = await output2.text();
42872
- await fs.writeFile(outFilePath, bundledSource);
43931
+ await fs2.writeFile(outFilePath, bundledSource);
42873
43932
  return;
42874
43933
  }
42875
43934
  await runBunCliBuild(entryPath, outFilePath);
@@ -42930,7 +43989,49 @@ function toContractName(slug) {
42930
43989
  }
42931
43990
  async function writeJson(file2, data) {
42932
43991
  const json = JSON.stringify(data, null, 2);
42933
- await fs.writeFile(file2, `${json}\n`, "utf8");
43992
+ await fs2.writeFile(file2, `${json}\n`, "utf8");
43993
+ }
43994
+ function describeStorageEntry(entry) {
43995
+ const valueBase64 = entry.value ?? "";
43996
+ const keyText = decodeUtf8FromBase64(entry.key);
43997
+ const valueText = decodeUtf8FromBase64(valueBase64);
43998
+ const snapshot = {
43999
+ key: {
44000
+ base64: entry.key,
44001
+ utf8: keyText
44002
+ },
44003
+ value: {
44004
+ base64: valueBase64,
44005
+ utf8: valueText
44006
+ }
44007
+ };
44008
+ const parsed = tryParseJsonLike(valueText);
44009
+ if (parsed !== undefined) {
44010
+ snapshot.value.json = parsed;
44011
+ }
44012
+ return snapshot;
44013
+ }
44014
+ function decodeUtf8FromBase64(base64) {
44015
+ if (!base64)
44016
+ return;
44017
+ try {
44018
+ const bytes2 = Buffer.from(base64, "base64");
44019
+ if (bytes2.length === 0) {
44020
+ return "";
44021
+ }
44022
+ return utf8Decoder2.decode(bytes2);
44023
+ } catch {
44024
+ return;
44025
+ }
44026
+ }
44027
+ function tryParseJsonLike(text) {
44028
+ if (!text)
44029
+ return;
44030
+ try {
44031
+ return JSON.parse(text);
44032
+ } catch {
44033
+ return;
44034
+ }
42934
44035
  }
42935
44036
  async function runCommand(command, args, options = {}) {
42936
44037
  await new Promise((resolve3, reject) => {
@@ -42995,15 +44096,15 @@ function resolveDevConfig(workspace) {
42995
44096
  };
42996
44097
  }
42997
44098
  async function writeDevEnvFile(file2, entries) {
42998
- await fs.mkdir(path.dirname(file2), { recursive: true });
44099
+ await fs2.mkdir(path.dirname(file2), { recursive: true });
42999
44100
  const lines = ["# generated by done dev", `# ${new Date().toISOString()}`];
43000
44101
  for (const key of Object.keys(entries).sort()) {
43001
44102
  lines.push(`${key}=${entries[key]}`);
43002
44103
  }
43003
- await fs.writeFile(file2, `${lines.join("\n")}\n`, "utf8");
44104
+ await fs2.writeFile(file2, `${lines.join("\n")}\n`, "utf8");
43004
44105
  }
43005
44106
  async function readDevEnvFile(file2) {
43006
- const data = await fs.readFile(file2, "utf8");
44107
+ const data = await fs2.readFile(file2, "utf8");
43007
44108
  const entries = {};
43008
44109
  for (const line of data.split(/\r?\n/)) {
43009
44110
  if (!line || line.startsWith("#"))
@@ -43040,6 +44141,13 @@ function openBrowser(url) {
43040
44141
  }
43041
44142
  });
43042
44143
  }
44144
+ var packageMetadata = readCliPackageMetadata();
44145
+ var CLI_VERSION = normalizeVersion(packageMetadata.version) ?? "0.0.0-spec";
44146
+ var CLI_VERSION_RANGE = toCaretRange(CLI_VERSION);
44147
+ var DONE_ZONE_VERSION = normalizeVersion(packageMetadata.doneZoneVersion) ?? CLI_VERSION;
44148
+ var DONE_ZONE_VERSION_RANGE = toCaretRange(DONE_ZONE_VERSION);
44149
+ var DONE_CLIENT_VERSION = normalizeVersion(packageMetadata.doneClientVersion) ?? CLI_VERSION;
44150
+ var DONE_CLIENT_VERSION_RANGE = toCaretRange(DONE_CLIENT_VERSION);
43043
44151
  var bunRuntime = globalThis.Bun;
43044
44152
  if (typeof bunRuntime === "undefined") {
43045
44153
  const bunExecutable = process.env.BUN ?? "bun";
@@ -43054,7 +44162,7 @@ if (typeof bunRuntime === "undefined") {
43054
44162
  }
43055
44163
  var DEFAULT_TEMPLATE_REPO = "https://github.com/mccallofthewild/done-template.git";
43056
44164
  var program2 = new Command;
43057
- program2.name("done").description("Done developer toolkit (spec-first stub)").version("0.0.0-spec");
44165
+ program2.name("done").description("Done developer toolkit (spec-first stub)").version(CLI_VERSION);
43058
44166
  program2.command("build").description("Bundle Done contracts defined in done.json").option("-j, --contracts <path>", "Path to done.json").option("-n, --name <name...>", "Filter contract names").action(async (options) => {
43059
44167
  try {
43060
44168
  await handleBuild(options);
@@ -43093,6 +44201,7 @@ program2.parseAsync().catch((error) => {
43093
44201
  console.error(error instanceof Error ? error.message : String(error));
43094
44202
  process.exit(1);
43095
44203
  });
44204
+ var utf8Decoder2 = new TextDecoder2;
43096
44205
  var DEV_LOG_PREFIX = import_picocolors.default.bold(import_picocolors.default.cyan("[done dev]"));
43097
44206
  var DEV_WARN_PREFIX = import_picocolors.default.bold(import_picocolors.default.yellow("[done dev]"));
43098
44207
  var DEV_ERROR_PREFIX = import_picocolors.default.bold(import_picocolors.default.red("[done dev]"));
@@ -43197,7 +44306,7 @@ class DoneDevOrchestrator {
43197
44306
  if (contracts.length === 0) {
43198
44307
  throw new Error("No contracts defined in done.json. Run `bunx done init <name>` first.");
43199
44308
  }
43200
- return contracts.map((contract) => {
44309
+ return contracts.map((contract, index) => {
43201
44310
  if (!contract.entry) {
43202
44311
  throw new Error(`Contract '${contract.name}' is missing an entry path.`);
43203
44312
  }
@@ -43207,8 +44316,10 @@ class DoneDevOrchestrator {
43207
44316
  const entryPath = path.resolve(manifestDir, contract.entry);
43208
44317
  const outFilePath = path.resolve(manifestDir, contract.outFile);
43209
44318
  const watchGlobs = (contract.watch && contract.watch.length > 0 ? contract.watch : [contract.entry]).map((pattern) => path.resolve(manifestDir, pattern));
44319
+ const slug = toSlug(contract.name) || `contract-${index + 1}`;
43210
44320
  return {
43211
44321
  name: contract.name,
44322
+ slug,
43212
44323
  envKey: toEnvVarKey(contract.name),
43213
44324
  entryPath,
43214
44325
  outFilePath,
@@ -43228,7 +44339,7 @@ class DoneDevOrchestrator {
43228
44339
  }
43229
44340
  async buildBundle(contract, initial, reason) {
43230
44341
  await ensureEntryExists(contract.entryPath, contract.name);
43231
- await fs.mkdir(path.dirname(contract.outFilePath), { recursive: true });
44342
+ await fs2.mkdir(path.dirname(contract.outFilePath), { recursive: true });
43232
44343
  const startedAt = Date.now();
43233
44344
  const label = initial ? "Building" : "Rebuilding";
43234
44345
  this.logInfo(`${label} ${contract.name}${reason ? ` (${reason})` : ""}`);
@@ -43254,6 +44365,7 @@ class DoneDevOrchestrator {
43254
44365
  contract.address = deployment.address;
43255
44366
  this.chain.advanceBlock();
43256
44367
  this.logInfo(`${import_picocolors.default.green("\u2022")} ${contract.name} deployed at ${deployment.address}`);
44368
+ await this.dumpContractStorage(contract);
43257
44369
  }
43258
44370
  }
43259
44371
  async startHttpServer() {
@@ -43307,7 +44419,7 @@ class DoneDevOrchestrator {
43307
44419
  async publishContract(contract) {
43308
44420
  if (!this.chain || !contract.address)
43309
44421
  return;
43310
- const script = await fs.readFile(contract.outFilePath, "utf8");
44422
+ const script = await fs2.readFile(contract.outFilePath, "utf8");
43311
44423
  const execResult = this.chain.execute(contract.address, {
43312
44424
  publish_code: {
43313
44425
  script,
@@ -43323,6 +44435,29 @@ class DoneDevOrchestrator {
43323
44435
  this.chain.advanceBlock();
43324
44436
  await this.writeEnvFile({ DONE_DEV_UPDATED_AT: new Date().toISOString() });
43325
44437
  this.logInfo(`${import_picocolors.default.green("\u21BB")} updated ${contract.name} (height ${this.chain.height})`);
44438
+ await this.dumpContractStorage(contract);
44439
+ }
44440
+ async dumpContractStorage(contract) {
44441
+ if (!this.chain || !contract.address)
44442
+ return;
44443
+ let entries;
44444
+ try {
44445
+ entries = this.chain.dumpStorage(contract.address);
44446
+ } catch (error) {
44447
+ this.logWarn(`Unable to snapshot storage for ${contract.name}: ${error.message}`);
44448
+ return;
44449
+ }
44450
+ const snapshot = {
44451
+ contract: contract.name,
44452
+ address: contract.address,
44453
+ height: this.chain.height,
44454
+ updatedAt: new Date().toISOString(),
44455
+ entries: entries.map(describeStorageEntry)
44456
+ };
44457
+ const storageDir = path.join(this.options.workspace.root, ".done", "storage");
44458
+ await fs2.mkdir(storageDir, { recursive: true });
44459
+ const filePath = path.join(storageDir, `${contract.slug}.json`);
44460
+ await writeJson(filePath, snapshot);
43326
44461
  }
43327
44462
  async launchFrontend() {
43328
44463
  const frontend = this.options.devConfig.frontend;